Decompiled source of BoobooBuilding v1.0.0

BooBoo Building/BepInEx/core/0Harmony.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using HarmonyLib.Internal.Patching;
using HarmonyLib.Internal.RuntimeFixes;
using HarmonyLib.Internal.Util;
using HarmonyLib.Public.Patching;
using HarmonyLib.Tools;
using JetBrains.Annotations;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using MonoMod.Utils;
using MonoMod.Utils.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("HarmonyTests")]
[assembly: InternalsVisibleTo("MonoMod.Utils.Cil.ILGeneratorProxy")]
[assembly: Guid("69aee16a-b6e7-4642-8081-3928b32455df")]
[assembly: AssemblyCompany("BepInEx")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © BepInEx 2022")]
[assembly: AssemblyDescription("A library for patching, replacing and decorating .NET and Mono methods during runtime powered by MonoMod.")]
[assembly: AssemblyFileVersion("2.9.0.0")]
[assembly: AssemblyInformationalVersion("2.9.0")]
[assembly: AssemblyProduct("HarmonyX")]
[assembly: AssemblyTitle("0Harmony")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.9.0.0")]
[module: UnverifiableCode]
namespace System
{
	internal struct ValueTuple<T1, T2>
	{
		public T1 Item1;

		public T2 Item2;

		public ValueTuple(T1 first, T2 second)
		{
			Item1 = first;
			Item2 = second;
		}
	}
	internal struct ValueTuple<T1, T2, T3>
	{
		public T1 Item1;

		public T2 Item2;

		public T3 Item3;

		public ValueTuple(T1 first, T2 second, T3 third)
		{
			Item1 = first;
			Item2 = second;
			Item3 = third;
		}
	}
}
namespace JetBrains.Annotations
{
	[AttributeUsage(AttributeTargets.All)]
	internal sealed class UsedImplicitlyAttribute : Attribute
	{
		public ImplicitUseKindFlags UseKindFlags { get; }

		public ImplicitUseTargetFlags TargetFlags { get; }

		public UsedImplicitlyAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter | AttributeTargets.GenericParameter)]
	internal sealed class MeansImplicitUseAttribute : Attribute
	{
		[UsedImplicitly]
		public ImplicitUseKindFlags UseKindFlags { get; }

		[UsedImplicitly]
		public ImplicitUseTargetFlags TargetFlags { get; }

		public MeansImplicitUseAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[Flags]
	internal enum ImplicitUseKindFlags
	{
		Default = 7,
		Access = 1,
		Assign = 2,
		InstantiatedWithFixedConstructorSignature = 4,
		InstantiatedNoFixedConstructorSignature = 8
	}
	[Flags]
	internal enum ImplicitUseTargetFlags
	{
		Default = 1,
		Itself = 1,
		Members = 2,
		WithInheritors = 4,
		WithMembers = 3
	}
}
namespace HarmonyLib
{
	public class DelegateTypeFactory
	{
		private class DelegateEntry
		{
			public CallingConvention? callingConvention;

			public Type delegateType;
		}

		private static int counter;

		private static readonly Dictionary<MethodInfo, List<DelegateEntry>> TypeCache = new Dictionary<MethodInfo, List<DelegateEntry>>();

		private static readonly MethodBase CallingConvAttr = AccessTools.Constructor(typeof(UnmanagedFunctionPointerAttribute), new Type[1] { typeof(CallingConvention) });

		public static readonly DelegateTypeFactory instance = new DelegateTypeFactory();

		public Type CreateDelegateType(Type returnType, Type[] argTypes)
		{
			return CreateDelegateType(returnType, argTypes, null);
		}

		public Type CreateDelegateType(Type returnType, Type[] argTypes, CallingConvention? convention)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//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_0098: Expected O, but got Unknown
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Expected O, but got Unknown
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Expected O, but got Unknown
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			counter++;
			AssemblyDefinition val = AssemblyDefinition.CreateAssembly(new AssemblyNameDefinition($"HarmonyDTFAssembly{counter}", new Version(1, 0)), $"HarmonyDTFModule{counter}", (ModuleKind)0);
			ModuleDefinition module = val.MainModule;
			TypeDefinition val2 = new TypeDefinition("", $"HarmonyDTFType{counter}", (TypeAttributes)257)
			{
				BaseType = module.ImportReference(typeof(MulticastDelegate))
			};
			module.Types.Add(val2);
			if (convention.HasValue)
			{
				CustomAttribute val3 = new CustomAttribute(module.ImportReference(CallingConvAttr));
				val3.ConstructorArguments.Add(new CustomAttributeArgument(module.ImportReference(typeof(CallingConvention)), (object)convention.Value));
				val2.CustomAttributes.Add(val3);
			}
			MethodDefinition val4 = new MethodDefinition(".ctor", (MethodAttributes)4230, module.ImportReference(typeof(void)))
			{
				ImplAttributes = (MethodImplAttributes)3
			};
			Extensions.AddRange<ParameterDefinition>(((MethodReference)val4).Parameters, (IEnumerable<ParameterDefinition>)(object)new ParameterDefinition[2]
			{
				new ParameterDefinition(module.ImportReference(typeof(object))),
				new ParameterDefinition(module.ImportReference(typeof(IntPtr)))
			});
			val2.Methods.Add(val4);
			MethodDefinition val5 = new MethodDefinition("Invoke", (MethodAttributes)198, module.ImportReference(returnType))
			{
				ImplAttributes = (MethodImplAttributes)3
			};
			Extensions.AddRange<ParameterDefinition>(((MethodReference)val5).Parameters, ((IEnumerable<Type>)argTypes).Select((Func<Type, ParameterDefinition>)((Type t) => new ParameterDefinition(module.ImportReference(t)))));
			val2.Methods.Add(val5);
			return ReflectionHelper.Load(val.MainModule).GetType($"HarmonyDTFType{counter}");
		}

		public Type CreateDelegateType(MethodInfo method)
		{
			return CreateDelegateType(method, null);
		}

		public Type CreateDelegateType(MethodInfo method, CallingConvention? convention)
		{
			DelegateEntry delegateEntry;
			if (TypeCache.TryGetValue(method, out var value) && (delegateEntry = value.FirstOrDefault((DelegateEntry e) => e.callingConvention == convention)) != null)
			{
				return delegateEntry.delegateType;
			}
			if (value == null)
			{
				value = (TypeCache[method] = new List<DelegateEntry>());
			}
			delegateEntry = new DelegateEntry
			{
				delegateType = CreateDelegateType(method.ReturnType, method.GetParameters().Types().ToArray(), convention),
				callingConvention = convention
			};
			value.Add(delegateEntry);
			return delegateEntry.delegateType;
		}
	}
	[Obsolete("Use AccessTools.FieldRefAccess<T, S> for fields and AccessTools.MethodDelegate<Func<T, S>> for property getters")]
	public delegate S GetterHandler<in T, out S>(T source);
	[Obsolete("Use AccessTools.FieldRefAccess<T, S> for fields and AccessTools.MethodDelegate<Action<T, S>> for property setters")]
	public delegate void SetterHandler<in T, in S>(T source, S value);
	public delegate T InstantiationHandler<out T>();
	public static class FastAccess
	{
		public static InstantiationHandler<T> CreateInstantiationHandler<T>()
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			ConstructorInfo constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
			if ((object)constructor == null)
			{
				throw new ApplicationException($"The type {typeof(T)} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).");
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition("InstantiateObject_" + typeof(T).Name, typeof(T), (Type[])null);
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Newobj, constructor);
			iLGenerator.Emit(OpCodes.Ret);
			return (InstantiationHandler<T>)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(InstantiationHandler<T>));
		}

		[Obsolete("Use AccessTools.MethodDelegate<Func<T, S>>(PropertyInfo.GetGetMethod(true))")]
		public static GetterHandler<T, S> CreateGetterHandler<T, S>(PropertyInfo propertyInfo)
		{
			MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true);
			DynamicMethodDefinition obj = CreateGetDynamicMethod<T, S>(propertyInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Call, getMethod);
			iLGenerator.Emit(OpCodes.Ret);
			return (GetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(GetterHandler<T, S>));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")]
		public static GetterHandler<T, S> CreateGetterHandler<T, S>(FieldInfo fieldInfo)
		{
			DynamicMethodDefinition obj = CreateGetDynamicMethod<T, S>(fieldInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldfld, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return (GetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(GetterHandler<T, S>));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(name) for fields and AccessTools.MethodDelegate<Func<T, S>>(AccessTools.PropertyGetter(typeof(T), name)) for properties")]
		public static GetterHandler<T, S> CreateFieldGetter<T, S>(params string[] names)
		{
			foreach (string name in names)
			{
				FieldInfo field = typeof(T).GetField(name, AccessTools.all);
				if ((object)field != null)
				{
					return CreateGetterHandler<T, S>(field);
				}
				PropertyInfo property = typeof(T).GetProperty(name, AccessTools.all);
				if ((object)property != null)
				{
					return CreateGetterHandler<T, S>(property);
				}
			}
			return null;
		}

		[Obsolete("Use AccessTools.MethodDelegate<Action<T, S>>(PropertyInfo.GetSetMethod(true))")]
		public static SetterHandler<T, S> CreateSetterHandler<T, S>(PropertyInfo propertyInfo)
		{
			MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
			DynamicMethodDefinition obj = CreateSetDynamicMethod<T, S>(propertyInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Call, setMethod);
			iLGenerator.Emit(OpCodes.Ret);
			return (SetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(SetterHandler<T, S>));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")]
		public static SetterHandler<T, S> CreateSetterHandler<T, S>(FieldInfo fieldInfo)
		{
			DynamicMethodDefinition obj = CreateSetDynamicMethod<T, S>(fieldInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Stfld, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return (SetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(SetterHandler<T, S>));
		}

		private static DynamicMethodDefinition CreateGetDynamicMethod<T, S>(Type type)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			return new DynamicMethodDefinition("DynamicGet_" + type.Name, typeof(S), new Type[1] { typeof(T) });
		}

		private static DynamicMethodDefinition CreateSetDynamicMethod<T, S>(Type type)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			return new DynamicMethodDefinition("DynamicSet_" + type.Name, typeof(void), new Type[2]
			{
				typeof(T),
				typeof(S)
			});
		}
	}
	public delegate object FastInvokeHandler(object target, params object[] parameters);
	public static class MethodInvoker
	{
		public static FastInvokeHandler GetHandler(MethodInfo methodInfo, bool directBoxValueAccess = false)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			DynamicMethodDefinition val = new DynamicMethodDefinition("FastInvoke_" + methodInfo.Name + "_" + (directBoxValueAccess ? "direct" : "indirect"), typeof(object), new Type[2]
			{
				typeof(object),
				typeof(object[])
			});
			ILGenerator iLGenerator = val.GetILGenerator();
			if (!methodInfo.IsStatic)
			{
				Emit(iLGenerator, OpCodes.Ldarg_0);
				EmitUnboxIfNeeded(iLGenerator, methodInfo.DeclaringType);
			}
			bool flag = true;
			ParameterInfo[] parameters = methodInfo.GetParameters();
			for (int i = 0; i < parameters.Length; i++)
			{
				Type type = parameters[i].ParameterType;
				bool isByRef = type.IsByRef;
				if (isByRef)
				{
					type = type.GetElementType();
				}
				bool isValueType = type.IsValueType;
				if (isByRef && isValueType && !directBoxValueAccess)
				{
					Emit(iLGenerator, OpCodes.Ldarg_1);
					EmitFastInt(iLGenerator, i);
				}
				Emit(iLGenerator, OpCodes.Ldarg_1);
				EmitFastInt(iLGenerator, i);
				if (isByRef && !isValueType)
				{
					Emit(iLGenerator, OpCodes.Ldelema, typeof(object));
					continue;
				}
				Emit(iLGenerator, OpCodes.Ldelem_Ref);
				if (!isValueType)
				{
					continue;
				}
				if (!isByRef || !directBoxValueAccess)
				{
					Emit(iLGenerator, OpCodes.Unbox_Any, type);
					if (isByRef)
					{
						Emit(iLGenerator, OpCodes.Box, type);
						Emit(iLGenerator, OpCodes.Dup);
						if (flag)
						{
							flag = false;
							iLGenerator.DeclareLocal(typeof(object), pinned: false);
						}
						Emit(iLGenerator, OpCodes.Stloc_0);
						Emit(iLGenerator, OpCodes.Stelem_Ref);
						Emit(iLGenerator, OpCodes.Ldloc_0);
						Emit(iLGenerator, OpCodes.Unbox, type);
					}
				}
				else
				{
					Emit(iLGenerator, OpCodes.Unbox, type);
				}
			}
			if (methodInfo.IsStatic)
			{
				EmitCall(iLGenerator, OpCodes.Call, methodInfo);
			}
			else
			{
				EmitCall(iLGenerator, OpCodes.Callvirt, methodInfo);
			}
			if ((object)methodInfo.ReturnType == typeof(void))
			{
				Emit(iLGenerator, OpCodes.Ldnull);
			}
			else
			{
				EmitBoxIfNeeded(iLGenerator, methodInfo.ReturnType);
			}
			Emit(iLGenerator, OpCodes.Ret);
			return (FastInvokeHandler)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(FastInvokeHandler));
		}

		internal static void Emit(ILGenerator il, OpCode opcode)
		{
			il.Emit(opcode);
		}

		internal static void Emit(ILGenerator il, OpCode opcode, Type type)
		{
			il.Emit(opcode, type);
		}

		internal static void EmitCall(ILGenerator il, OpCode opcode, MethodInfo methodInfo)
		{
			il.EmitCall(opcode, methodInfo, null);
		}

		private static void EmitUnboxIfNeeded(ILGenerator il, Type type)
		{
			if (type.IsValueType)
			{
				Emit(il, OpCodes.Unbox_Any, type);
			}
		}

		private static void EmitBoxIfNeeded(ILGenerator il, Type type)
		{
			if (type.IsValueType)
			{
				Emit(il, OpCodes.Box, type);
			}
		}

		internal static void EmitFastInt(ILGenerator il, int value)
		{
			switch (value)
			{
			case -1:
				il.Emit(OpCodes.Ldc_I4_M1);
				return;
			case 0:
				il.Emit(OpCodes.Ldc_I4_0);
				return;
			case 1:
				il.Emit(OpCodes.Ldc_I4_1);
				return;
			case 2:
				il.Emit(OpCodes.Ldc_I4_2);
				return;
			case 3:
				il.Emit(OpCodes.Ldc_I4_3);
				return;
			case 4:
				il.Emit(OpCodes.Ldc_I4_4);
				return;
			case 5:
				il.Emit(OpCodes.Ldc_I4_5);
				return;
			case 6:
				il.Emit(OpCodes.Ldc_I4_6);
				return;
			case 7:
				il.Emit(OpCodes.Ldc_I4_7);
				return;
			case 8:
				il.Emit(OpCodes.Ldc_I4_8);
				return;
			}
			if (value > -129 && value < 128)
			{
				il.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
			}
			else
			{
				il.Emit(OpCodes.Ldc_I4, value);
			}
		}
	}
	internal class AccessCache
	{
		internal enum MemberType
		{
			Any,
			Static,
			Instance
		}

		private const BindingFlags BasicFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty;

		private static readonly Dictionary<MemberType, BindingFlags> declaredOnlyBindingFlags = new Dictionary<MemberType, BindingFlags>
		{
			{
				MemberType.Any,
				BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty
			},
			{
				MemberType.Instance,
				BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty
			},
			{
				MemberType.Static,
				BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty
			}
		};

		private readonly Dictionary<Type, Dictionary<string, FieldInfo>> declaredFields = new Dictionary<Type, Dictionary<string, FieldInfo>>();

		private readonly Dictionary<Type, Dictionary<string, PropertyInfo>> declaredProperties = new Dictionary<Type, Dictionary<string, PropertyInfo>>();

		private readonly Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>> declaredMethods = new Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>>();

		private readonly Dictionary<Type, Dictionary<string, FieldInfo>> inheritedFields = new Dictionary<Type, Dictionary<string, FieldInfo>>();

		private readonly Dictionary<Type, Dictionary<string, PropertyInfo>> inheritedProperties = new Dictionary<Type, Dictionary<string, PropertyInfo>>();

		private readonly Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>> inheritedMethods = new Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>>();

		private static T Get<T>(Dictionary<Type, Dictionary<string, T>> dict, Type type, string name, Func<T> fetcher)
		{
			lock (dict)
			{
				if (!dict.TryGetValue(type, out var value))
				{
					value = (dict[type] = new Dictionary<string, T>());
				}
				if (!value.TryGetValue(name, out var value2))
				{
					value2 = (value[name] = fetcher());
				}
				return value2;
			}
		}

		private static T Get<T>(Dictionary<Type, Dictionary<string, Dictionary<int, T>>> dict, Type type, string name, Type[] arguments, Func<T> fetcher)
		{
			lock (dict)
			{
				if (!dict.TryGetValue(type, out var value))
				{
					value = (dict[type] = new Dictionary<string, Dictionary<int, T>>());
				}
				if (!value.TryGetValue(name, out var value2))
				{
					value2 = (value[name] = new Dictionary<int, T>());
				}
				int key = AccessTools.CombinedHashCode(arguments);
				if (!value2.TryGetValue(key, out var value3))
				{
					value3 = (value2[key] = fetcher());
				}
				return value3;
			}
		}

		internal FieldInfo GetFieldInfo(Type type, string name, MemberType memberType = MemberType.Any, bool declaredOnly = false)
		{
			FieldInfo fieldInfo = Get(declaredFields, type, name, () => type.GetField(name, declaredOnlyBindingFlags[memberType]));
			if ((object)fieldInfo == null && !declaredOnly)
			{
				fieldInfo = Get(inheritedFields, type, name, () => AccessTools.FindIncludingBaseTypes(type, (Type t) => t.GetField(name, AccessTools.all)));
			}
			return fieldInfo;
		}

		internal PropertyInfo GetPropertyInfo(Type type, string name, MemberType memberType = MemberType.Any, bool declaredOnly = false)
		{
			PropertyInfo propertyInfo = Get(declaredProperties, type, name, () => type.GetProperty(name, declaredOnlyBindingFlags[memberType]));
			if ((object)propertyInfo == null && !declaredOnly)
			{
				propertyInfo = Get(inheritedProperties, type, name, () => AccessTools.FindIncludingBaseTypes(type, (Type t) => t.GetProperty(name, AccessTools.all)));
			}
			return propertyInfo;
		}

		internal MethodBase GetMethodInfo(Type type, string name, Type[] arguments, MemberType memberType = MemberType.Any, bool declaredOnly = false)
		{
			MethodBase methodBase = Get(declaredMethods, type, name, arguments, () => type.GetMethod(name, declaredOnlyBindingFlags[memberType], null, arguments, null));
			if ((object)methodBase == null && !declaredOnly)
			{
				methodBase = Get(inheritedMethods, type, name, arguments, () => AccessTools.Method(type, name, arguments));
			}
			return methodBase;
		}
	}
	internal static class PatchArgumentExtensions
	{
		private static HarmonyArgument[] AllHarmonyArguments(object[] attributes)
		{
			return (from attr in attributes
				select (attr.GetType().Name != "HarmonyArgument") ? null : AccessTools.MakeDeepCopy<HarmonyArgument>(attr) into harg
				where harg != null
				select harg).ToArray();
		}

		private static HarmonyArgument GetArgumentAttribute(this ParameterInfo parameter)
		{
			return AllHarmonyArguments(parameter.GetCustomAttributes(inherit: false)).FirstOrDefault();
		}

		private static HarmonyArgument[] GetArgumentAttributes(this MethodInfo method)
		{
			if ((object)method == null || method is DynamicMethod)
			{
				return null;
			}
			return AllHarmonyArguments(method.GetCustomAttributes(inherit: false));
		}

		private static HarmonyArgument[] GetArgumentAttributes(this Type type)
		{
			return AllHarmonyArguments(type.GetCustomAttributes(inherit: false));
		}

		private static string GetOriginalArgumentName(this ParameterInfo parameter, string[] originalParameterNames)
		{
			HarmonyArgument argumentAttribute = parameter.GetArgumentAttribute();
			if (argumentAttribute == null)
			{
				return null;
			}
			if (!string.IsNullOrEmpty(argumentAttribute.OriginalName))
			{
				return argumentAttribute.OriginalName;
			}
			if (argumentAttribute.Index >= 0 && argumentAttribute.Index < originalParameterNames.Length)
			{
				return originalParameterNames[argumentAttribute.Index];
			}
			return null;
		}

		private static string GetOriginalArgumentName(HarmonyArgument[] attributes, string name, string[] originalParameterNames)
		{
			if (((attributes != null && attributes.Length != 0) ? 1 : 0) <= (false ? 1 : 0))
			{
				return null;
			}
			HarmonyArgument harmonyArgument = attributes.SingleOrDefault((HarmonyArgument p) => p.NewName == name);
			if (harmonyArgument == null)
			{
				return null;
			}
			if (!string.IsNullOrEmpty(harmonyArgument.OriginalName))
			{
				return harmonyArgument.OriginalName;
			}
			if (originalParameterNames != null && harmonyArgument.Index >= 0 && harmonyArgument.Index < originalParameterNames.Length)
			{
				return originalParameterNames[harmonyArgument.Index];
			}
			return null;
		}

		private static string GetOriginalArgumentName(this MethodInfo method, string[] originalParameterNames, string name)
		{
			string originalArgumentName = GetOriginalArgumentName(((object)method != null) ? method.GetArgumentAttributes() : null, name, originalParameterNames);
			if (originalArgumentName != null)
			{
				return originalArgumentName;
			}
			object attributes;
			if ((object)method == null)
			{
				attributes = null;
			}
			else
			{
				Type? declaringType = method.DeclaringType;
				attributes = (((object)declaringType != null) ? declaringType.GetArgumentAttributes() : null);
			}
			originalArgumentName = GetOriginalArgumentName((HarmonyArgument[])attributes, name, originalParameterNames);
			if (originalArgumentName != null)
			{
				return originalArgumentName;
			}
			return name;
		}

		internal static int GetArgumentIndex(this MethodInfo patch, string[] originalParameterNames, ParameterInfo patchParam)
		{
			if (patch is DynamicMethod)
			{
				return Array.IndexOf<string>(originalParameterNames, patchParam.Name);
			}
			string originalArgumentName = patchParam.GetOriginalArgumentName(originalParameterNames);
			if (originalArgumentName != null)
			{
				return Array.IndexOf(originalParameterNames, originalArgumentName);
			}
			originalArgumentName = patch.GetOriginalArgumentName(originalParameterNames, patchParam.Name);
			if (originalArgumentName != null)
			{
				return Array.IndexOf(originalParameterNames, originalArgumentName);
			}
			return -1;
		}
	}
	internal static class PatchFunctions
	{
		internal static List<MethodInfo> GetSortedPatchMethods(MethodBase original, Patch[] patches, bool debug)
		{
			return new PatchSorter(patches, debug).Sort(original);
		}

		internal static Patch[] GetSortedPatchMethodsAsPatches(MethodBase original, Patch[] patches, bool debug)
		{
			return new PatchSorter(patches, debug).SortAsPatches(original);
		}

		internal static MethodInfo UpdateWrapper(MethodBase original, PatchInfo patchInfo)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			MethodPatcher methodPatcher = original.GetMethodPatcher();
			DynamicMethodDefinition val = methodPatcher.PrepareOriginal();
			if (val != null)
			{
				ILContext ctx = new ILContext(val.Definition);
				HarmonyManipulator.Manipulate(original, patchInfo, ctx);
			}
			try
			{
				return methodPatcher.DetourTo((val != null) ? val.Generate() : null) as MethodInfo;
			}
			catch (Exception ex)
			{
				object body;
				if (val == null)
				{
					body = null;
				}
				else
				{
					MethodDefinition definition = val.Definition;
					body = ((definition != null) ? definition.Body : null);
				}
				throw HarmonyException.Create(ex, (MethodBody)body);
			}
		}

		internal static MethodInfo ReversePatch(HarmonyMethod standin, MethodBase original, MethodInfo postTranspiler, MethodInfo postManipulator)
		{
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Expected O, but got Unknown
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			if (standin == null)
			{
				throw new ArgumentNullException("standin");
			}
			if ((object)standin.method == null)
			{
				throw new ArgumentNullException("standin", "standin.method is NULL");
			}
			bool debug = standin.debug.GetValueOrDefault();
			List<MethodInfo> transpilers = new List<MethodInfo>();
			List<MethodInfo> ilmanipulators = new List<MethodInfo>();
			if (standin.reversePatchType == HarmonyReversePatchType.Snapshot)
			{
				Patches patchInfo = Harmony.GetPatchInfo(original);
				transpilers.AddRange(GetSortedPatchMethods(original, patchInfo.Transpilers.ToArray(), debug));
				ilmanipulators.AddRange(GetSortedPatchMethods(original, patchInfo.ILManipulators.ToArray(), debug));
			}
			if ((object)postTranspiler != null)
			{
				transpilers.Add(postTranspiler);
			}
			if ((object)postManipulator != null)
			{
				ilmanipulators.Add(postManipulator);
			}
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.AppendLine("Reverse patching " + standin.method.FullDescription() + " with " + original.FullDescription());
				PrintInfo(stringBuilder, transpilers, "Transpiler");
				PrintInfo(stringBuilder, ilmanipulators, "Manipulators");
				return stringBuilder.ToString();
			}, debug);
			MethodBody patchBody = null;
			ILHook val = new ILHook((MethodBase)standin.method, (Manipulator)delegate(ILContext ctx)
			{
				//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fb: Expected O, but got Unknown
				//IL_01e1: 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)
				if (original is MethodInfo methodInfo2)
				{
					patchBody = ctx.Body;
					MethodPatcher methodPatcher = methodInfo2.GetMethodPatcher();
					DynamicMethodDefinition val2 = methodPatcher.CopyOriginal();
					if (val2 == null)
					{
						throw new NullReferenceException("Cannot reverse patch " + methodInfo2.FullDescription() + ": method patcher (" + methodPatcher.GetType().FullDescription() + ") can't copy original method body");
					}
					ILManipulator iLManipulator = new ILManipulator(val2.Definition.Body, debug);
					ctx.Body.Variables.Clear();
					Enumerator<VariableDefinition> enumerator2 = iLManipulator.Body.Variables.GetEnumerator();
					try
					{
						while (enumerator2.MoveNext())
						{
							VariableDefinition current2 = enumerator2.Current;
							ctx.Body.Variables.Add(new VariableDefinition(ctx.Module.ImportReference(((VariableReference)current2).VariableType)));
						}
					}
					finally
					{
						((IDisposable)enumerator2).Dispose();
					}
					foreach (MethodInfo item in transpilers)
					{
						iLManipulator.AddTranspiler(item);
					}
					iLManipulator.WriteTo(ctx.Body, standin.method);
					HarmonyManipulator.ApplyManipulators(ctx, original, ilmanipulators, null);
					Instruction val3 = null;
					foreach (Instruction item2 in ((IEnumerable<Instruction>)ctx.Instrs).Where((Instruction i) => i.OpCode == OpCodes.Ret))
					{
						if (val3 == null)
						{
							val3 = ctx.IL.Create(OpCodes.Ret);
						}
						item2.OpCode = OpCodes.Br;
						item2.Operand = val3;
					}
					if (val3 != null)
					{
						ctx.IL.Append(val3);
					}
					Logger.Log(Logger.LogChannel.IL, () => "Generated reverse patcher (" + ((MemberReference)ctx.Method).FullName + "):\n" + ctx.Body.ToILDasmString(), debug);
				}
			}, new ILHookConfig
			{
				ManualApply = true
			});
			try
			{
				val.Apply();
			}
			catch (Exception ex)
			{
				throw HarmonyException.Create(ex, patchBody);
			}
			MethodInfo methodInfo = val.GetCurrentTarget() as MethodInfo;
			PatchTools.RememberObject(standin.method, methodInfo);
			return methodInfo;
			static void PrintInfo(StringBuilder sb, ICollection<MethodInfo> methods, string name)
			{
				if (methods.Count <= 0)
				{
					return;
				}
				sb.AppendLine(name + ":");
				foreach (MethodInfo method in methods)
				{
					sb.AppendLine("  * " + method.FullDescription());
				}
			}
		}

		internal static IEnumerable<CodeInstruction> ApplyTranspilers(MethodBase methodBase, ILGenerator generator, int maxTranspilers = 0)
		{
			MethodPatcher methodPatcher = methodBase.GetMethodPatcher();
			DynamicMethodDefinition val = methodPatcher.CopyOriginal();
			if (val == null)
			{
				throw new NullReferenceException("Cannot reverse patch " + methodBase.FullDescription() + ": method patcher (" + methodPatcher.GetType().FullDescription() + ") can't copy original method body");
			}
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body, debug: false);
			PatchInfo patchInfo = methodBase.GetPatchInfo();
			if (patchInfo != null)
			{
				List<MethodInfo> sortedPatchMethods = GetSortedPatchMethods(methodBase, patchInfo.transpilers, debug: false);
				for (int i = 0; i < maxTranspilers && i < sortedPatchMethods.Count; i++)
				{
					iLManipulator.AddTranspiler(sortedPatchMethods[i]);
				}
			}
			return iLManipulator.GetInstructions(generator, methodBase);
		}

		internal static void UnpatchConditional(Func<Patch, bool> executionCondition)
		{
			foreach (MethodBase item in PatchProcessor.GetAllPatchedMethods().ToList())
			{
				bool num = item.HasMethodBody();
				Patches patchInfo2 = PatchProcessor.GetPatchInfo(item);
				PatchProcessor patchProcessor = new PatchProcessor(null, item);
				if (num)
				{
					patchInfo2.Postfixes.DoIf(executionCondition, delegate(Patch patchInfo)
					{
						patchProcessor.Unpatch(patchInfo.PatchMethod);
					});
					patchInfo2.Prefixes.DoIf(executionCondition, delegate(Patch patchInfo)
					{
						patchProcessor.Unpatch(patchInfo.PatchMethod);
					});
				}
				patchInfo2.ILManipulators.DoIf(executionCondition, delegate(Patch patchInfo)
				{
					patchProcessor.Unpatch(patchInfo.PatchMethod);
				});
				patchInfo2.Transpilers.DoIf(executionCondition, delegate(Patch patchInfo)
				{
					patchProcessor.Unpatch(patchInfo.PatchMethod);
				});
				if (num)
				{
					patchInfo2.Finalizers.DoIf(executionCondition, delegate(Patch patchInfo)
					{
						patchProcessor.Unpatch(patchInfo.PatchMethod);
					});
				}
			}
		}
	}
	internal class PatchJobs<T>
	{
		internal class Job
		{
			internal MethodBase original;

			internal T replacement;

			internal List<HarmonyMethod> prefixes = new List<HarmonyMethod>();

			internal List<HarmonyMethod> postfixes = new List<HarmonyMethod>();

			internal List<HarmonyMethod> transpilers = new List<HarmonyMethod>();

			internal List<HarmonyMethod> finalizers = new List<HarmonyMethod>();

			internal List<HarmonyMethod> ilmanipulators = new List<HarmonyMethod>();

			internal void AddPatch(AttributePatch patch)
			{
				HarmonyPatchType? type = patch.type;
				if (type.HasValue)
				{
					switch (type.GetValueOrDefault())
					{
					case HarmonyPatchType.Prefix:
						prefixes.Add(patch.info);
						break;
					case HarmonyPatchType.Postfix:
						postfixes.Add(patch.info);
						break;
					case HarmonyPatchType.Transpiler:
						transpilers.Add(patch.info);
						break;
					case HarmonyPatchType.Finalizer:
						finalizers.Add(patch.info);
						break;
					case HarmonyPatchType.ILManipulator:
						ilmanipulators.Add(patch.info);
						break;
					case HarmonyPatchType.ReversePatch:
						break;
					}
				}
			}
		}

		internal Dictionary<MethodBase, Job> state = new Dictionary<MethodBase, Job>();

		internal Job GetJob(MethodBase method)
		{
			if ((object)method == null)
			{
				return null;
			}
			if (!state.TryGetValue(method, out var value))
			{
				value = new Job
				{
					original = method
				};
				state[method] = value;
			}
			return value;
		}

		internal List<Job> GetJobs()
		{
			return state.Values.Where((Job job) => job.prefixes.Count + job.postfixes.Count + job.transpilers.Count + job.finalizers.Count + job.ilmanipulators.Count > 0).ToList();
		}

		internal List<T> GetReplacements()
		{
			return state.Values.Select((Job job) => job.replacement).ToList();
		}
	}
	internal class AttributePatch
	{
		private static readonly HarmonyPatchType[] allPatchTypes = new HarmonyPatchType[6]
		{
			HarmonyPatchType.Prefix,
			HarmonyPatchType.Postfix,
			HarmonyPatchType.Transpiler,
			HarmonyPatchType.Finalizer,
			HarmonyPatchType.ReversePatch,
			HarmonyPatchType.ILManipulator
		};

		internal HarmonyMethod info;

		internal HarmonyPatchType? type;

		private static readonly string harmonyAttributeName = typeof(HarmonyAttribute).FullName;

		internal static IEnumerable<AttributePatch> Create(MethodInfo patch, bool collectIncomplete = false)
		{
			if ((object)patch == null)
			{
				throw new NullReferenceException("Patch method cannot be null");
			}
			object[] customAttributes = patch.GetCustomAttributes(inherit: true);
			string name = patch.Name;
			HarmonyPatchType? type = GetPatchType(name, customAttributes);
			if (!type.HasValue)
			{
				return Enumerable.Empty<AttributePatch>();
			}
			if (type != HarmonyPatchType.ReversePatch && !patch.IsStatic)
			{
				throw new ArgumentException("Patch method " + patch.FullDescription() + " must be static");
			}
			List<HarmonyMethod> list = (from attr in customAttributes
				where attr.GetType().BaseType.FullName == harmonyAttributeName
				select AccessTools.Field(attr.GetType(), "info").GetValue(attr) into harmonyInfo
				select AccessTools.MakeDeepCopy<HarmonyMethod>(harmonyInfo)).ToList();
			List<HarmonyMethod> list2 = new List<HarmonyMethod>();
			ILookup<bool, HarmonyMethod> lookup = list.ToLookup((HarmonyMethod m) => IsComplete(m, collectIncomplete));
			List<HarmonyMethod> incomplete = lookup[false].ToList();
			HarmonyMethod info = HarmonyMethod.Merge(incomplete);
			List<HarmonyMethod> list3 = lookup[true].Where((HarmonyMethod m) => !Same(m, info)).ToList();
			if (list3.Count > 1)
			{
				list2.AddRange(list3.Select((HarmonyMethod m) => HarmonyMethod.Merge(incomplete.AddItem(m))));
			}
			else
			{
				list2.Add(HarmonyMethod.Merge(list));
			}
			foreach (HarmonyMethod item in list2)
			{
				item.method = patch;
			}
			return list2.Select((HarmonyMethod i) => new AttributePatch
			{
				info = i,
				type = type
			}).ToList();
			static bool IsComplete(HarmonyMethod m, bool collectIncomplete)
			{
				if (collectIncomplete || (object)m.GetDeclaringType() != null)
				{
					return m.methodName != null;
				}
				return false;
			}
			static bool Same(HarmonyMethod m1, HarmonyMethod m2)
			{
				if ((object)m1.GetDeclaringType() == m2.GetDeclaringType() && m1.methodName == m2.methodName)
				{
					return m1.GetArgumentList().SequenceEqual(m2.GetArgumentList());
				}
				return false;
			}
		}

		private static HarmonyPatchType? GetPatchType(string methodName, object[] allAttributes)
		{
			HashSet<string> hashSet = new HashSet<string>(from attr in allAttributes
				select attr.GetType().FullName into name
				where name.StartsWith("Harmony")
				select name);
			HarmonyPatchType? result = null;
			HarmonyPatchType[] array = allPatchTypes;
			for (int i = 0; i < array.Length; i++)
			{
				HarmonyPatchType value = array[i];
				string text = value.ToString();
				if (text == methodName || hashSet.Contains("HarmonyLib.Harmony" + text))
				{
					result = value;
					break;
				}
			}
			return result;
		}
	}
	internal class PatchSorter
	{
		private class PatchSortingWrapper : IComparable
		{
			internal readonly HashSet<PatchSortingWrapper> after;

			internal readonly HashSet<PatchSortingWrapper> before;

			internal readonly Patch innerPatch;

			internal PatchSortingWrapper(Patch patch)
			{
				innerPatch = patch;
				before = new HashSet<PatchSortingWrapper>();
				after = new HashSet<PatchSortingWrapper>();
			}

			public int CompareTo(object obj)
			{
				return PatchInfoSerialization.PriorityComparer((obj as PatchSortingWrapper)?.innerPatch, innerPatch.index, innerPatch.priority);
			}

			public override bool Equals(object obj)
			{
				if (obj is PatchSortingWrapper patchSortingWrapper)
				{
					return (object)innerPatch.PatchMethod == patchSortingWrapper.innerPatch.PatchMethod;
				}
				return false;
			}

			public override int GetHashCode()
			{
				return innerPatch.PatchMethod.GetHashCode();
			}

			internal void AddBeforeDependency(IEnumerable<PatchSortingWrapper> dependencies)
			{
				foreach (PatchSortingWrapper dependency in dependencies)
				{
					before.Add(dependency);
					dependency.after.Add(this);
				}
			}

			internal void AddAfterDependency(IEnumerable<PatchSortingWrapper> dependencies)
			{
				foreach (PatchSortingWrapper dependency in dependencies)
				{
					after.Add(dependency);
					dependency.before.Add(this);
				}
			}

			internal void RemoveAfterDependency(PatchSortingWrapper afterNode)
			{
				after.Remove(afterNode);
				afterNode.before.Remove(this);
			}

			internal void RemoveBeforeDependency(PatchSortingWrapper beforeNode)
			{
				before.Remove(beforeNode);
				beforeNode.after.Remove(this);
			}
		}

		internal class PatchDetailedComparer : IEqualityComparer<Patch>
		{
			public bool Equals(Patch x, Patch y)
			{
				if (y != null && x != null && x.owner == y.owner && (object)x.PatchMethod == y.PatchMethod && x.index == y.index && x.priority == y.priority && x.before.Length == y.before.Length && x.after.Length == y.after.Length && x.before.All(((IEnumerable<string>)y.before).Contains<string>))
				{
					return x.after.All(((IEnumerable<string>)y.after).Contains<string>);
				}
				return false;
			}

			public int GetHashCode(Patch obj)
			{
				return obj.GetHashCode();
			}
		}

		private List<PatchSortingWrapper> patches;

		private HashSet<PatchSortingWrapper> handledPatches;

		private List<PatchSortingWrapper> result;

		private List<PatchSortingWrapper> waitingList;

		internal Patch[] sortedPatchArray;

		private readonly bool debug;

		internal PatchSorter(Patch[] patches, bool debug = false)
		{
			this.patches = patches.Select((Patch x) => new PatchSortingWrapper(x)).ToList();
			this.debug = debug;
			foreach (PatchSortingWrapper node in this.patches)
			{
				node.AddBeforeDependency(this.patches.Where((PatchSortingWrapper x) => node.innerPatch.before.Contains(x.innerPatch.owner)));
				node.AddAfterDependency(this.patches.Where((PatchSortingWrapper x) => node.innerPatch.after.Contains(x.innerPatch.owner)));
			}
			this.patches.Sort();
		}

		internal List<MethodInfo> Sort(MethodBase original)
		{
			return (from x in SortAsPatches(original)
				select x.GetMethod(original)).ToList();
		}

		internal Patch[] SortAsPatches(MethodBase original)
		{
			if (sortedPatchArray != null)
			{
				return sortedPatchArray;
			}
			handledPatches = new HashSet<PatchSortingWrapper>();
			waitingList = new List<PatchSortingWrapper>();
			result = new List<PatchSortingWrapper>(patches.Count);
			Queue<PatchSortingWrapper> queue = new Queue<PatchSortingWrapper>(patches);
			while (queue.Count != 0)
			{
				foreach (PatchSortingWrapper item in queue)
				{
					if (item.after.All((PatchSortingWrapper x) => handledPatches.Contains(x)))
					{
						AddNodeToResult(item);
						if (item.before.Count != 0)
						{
							ProcessWaitingList();
						}
					}
					else
					{
						waitingList.Add(item);
					}
				}
				CullDependency();
				queue = new Queue<PatchSortingWrapper>(waitingList);
				waitingList.Clear();
			}
			sortedPatchArray = result.Select((PatchSortingWrapper x) => x.innerPatch).ToArray();
			handledPatches = null;
			waitingList = null;
			patches = null;
			return sortedPatchArray;
		}

		internal bool ComparePatchLists(Patch[] patches)
		{
			if (sortedPatchArray == null)
			{
				Sort(null);
			}
			if (patches != null && sortedPatchArray.Length == patches.Length)
			{
				return sortedPatchArray.All((Patch x) => patches.Contains(x, new PatchDetailedComparer()));
			}
			return false;
		}

		private void CullDependency()
		{
			for (int i = waitingList.Count - 1; i >= 0; i--)
			{
				foreach (PatchSortingWrapper afterNode in waitingList[i].after)
				{
					if (!handledPatches.Contains(afterNode))
					{
						waitingList[i].RemoveAfterDependency(afterNode);
						Logger.Log(Logger.LogChannel.Debug, delegate
						{
							string text = afterNode.innerPatch.PatchMethod.FullDescription();
							string text2 = waitingList[i].innerPatch.PatchMethod.FullDescription();
							return "Breaking dependence between " + text + " and " + text2;
						}, debug);
						return;
					}
				}
			}
		}

		private void ProcessWaitingList()
		{
			int num = waitingList.Count;
			int num2 = 0;
			while (num2 < num)
			{
				PatchSortingWrapper patchSortingWrapper = waitingList[num2];
				if (patchSortingWrapper.after.All(handledPatches.Contains))
				{
					waitingList.Remove(patchSortingWrapper);
					AddNodeToResult(patchSortingWrapper);
					num--;
					num2 = 0;
				}
				else
				{
					num2++;
				}
			}
		}

		private void AddNodeToResult(PatchSortingWrapper node)
		{
			result.Add(node);
			handledPatches.Add(node);
		}
	}
	internal static class PatchTools
	{
		[ThreadStatic]
		private static Dictionary<object, object> objectReferences;

		internal static void RememberObject(object key, object value)
		{
			if (objectReferences == null)
			{
				objectReferences = new Dictionary<object, object>();
			}
			objectReferences[key] = value;
		}

		internal static MethodInfo GetPatchMethod(Type patchType, string attributeName)
		{
			MethodInfo methodInfo = patchType.GetMethods(AccessTools.all).FirstOrDefault((MethodInfo m) => m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == attributeName));
			if ((object)methodInfo == null)
			{
				string name = attributeName.Replace("HarmonyLib.Harmony", "");
				methodInfo = patchType.GetMethod(name, AccessTools.all);
			}
			return methodInfo;
		}

		internal static AssemblyBuilder DefineDynamicAssembly(string name)
		{
			AssemblyName assemblyName = new AssemblyName(name);
			return AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
		}

		internal static List<AttributePatch> GetPatchMethods(Type type, bool collectIncomplete = false)
		{
			return (from attributePatch in AccessTools.GetDeclaredMethods(type).SelectMany((MethodInfo m) => AttributePatch.Create(m, collectIncomplete))
				where attributePatch != null
				select attributePatch).ToList();
		}

		internal static MethodBase GetOriginalMethod(this HarmonyMethod attr)
		{
			try
			{
				MethodType? methodType = attr.methodType;
				if (methodType.HasValue)
				{
					switch (methodType.GetValueOrDefault())
					{
					case MethodType.Normal:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.DeclaredMethod(attr.GetDeclaringType(), attr.methodName, attr.argumentTypes);
					case MethodType.Getter:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.DeclaredProperty(attr.GetDeclaringType(), attr.methodName).GetGetMethod(nonPublic: true);
					case MethodType.Setter:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.DeclaredProperty(attr.GetDeclaringType(), attr.methodName).GetSetMethod(nonPublic: true);
					case MethodType.Constructor:
						return AccessTools.DeclaredConstructor(attr.GetDeclaringType(), attr.argumentTypes);
					case MethodType.StaticConstructor:
						return AccessTools.GetDeclaredConstructors(attr.GetDeclaringType()).FirstOrDefault((ConstructorInfo c) => c.IsStatic);
					case MethodType.Enumerator:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.EnumeratorMoveNext(AccessTools.DeclaredMethod(attr.GetDeclaringType(), attr.methodName, attr.argumentTypes));
					}
				}
			}
			catch (AmbiguousMatchException ex)
			{
				throw new HarmonyException("Ambiguous match for HarmonyMethod[" + attr.Description() + "]", ex.InnerException ?? ex);
			}
			return null;
		}
	}
	public enum MethodType
	{
		Normal,
		Getter,
		Setter,
		Constructor,
		StaticConstructor,
		Enumerator
	}
	public enum ArgumentType
	{
		Normal,
		Ref,
		Out,
		Pointer
	}
	public enum HarmonyPatchType
	{
		All,
		Prefix,
		Postfix,
		Transpiler,
		Finalizer,
		ReversePatch,
		ILManipulator
	}
	public enum HarmonyReversePatchType
	{
		Original,
		Snapshot
	}
	public enum MethodDispatchType
	{
		VirtualCall,
		Call
	}
	[MeansImplicitUse]
	public class HarmonyAttribute : Attribute
	{
		public HarmonyMethod info = new HarmonyMethod();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Delegate, AllowMultiple = true)]
	public class HarmonyPatch : HarmonyAttribute
	{
		public HarmonyPatch()
		{
		}

		public HarmonyPatch(Type declaringType)
		{
			info.declaringType = declaringType;
		}

		public HarmonyPatch(Type declaringType, Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
		}

		public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(string assemblyQualifiedDeclaringType, string methodName)
		{
			info.assemblyQualifiedDeclaringTypeName = assemblyQualifiedDeclaringType;
			info.methodName = methodName;
		}

		public HarmonyPatch(string assemblyQualifiedDeclaringType, string methodName, MethodType methodType, Type[] argumentTypes = null, ArgumentType[] argumentVariations = null)
		{
			info.assemblyQualifiedDeclaringTypeName = assemblyQualifiedDeclaringType;
			info.methodName = methodName;
			info.methodType = methodType;
			if (argumentTypes != null)
			{
				ParseSpecialArguments(argumentTypes, argumentVariations);
			}
		}

		public HarmonyPatch(Type declaringType, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type declaringType, string methodName, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(string methodName)
		{
			info.methodName = methodName;
		}

		public HarmonyPatch(string methodName, params Type[] argumentTypes)
		{
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(string methodName, MethodType methodType)
		{
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType)
		{
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType, params Type[] argumentTypes)
		{
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type[] argumentTypes)
		{
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		private void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			if (argumentVariations == null || argumentVariations.Length == 0)
			{
				info.argumentTypes = argumentTypes;
				return;
			}
			if (argumentTypes.Length < argumentVariations.Length)
			{
				throw new ArgumentException("argumentVariations contains more elements than argumentTypes", "argumentVariations");
			}
			List<Type> list = new List<Type>();
			for (int i = 0; i < argumentTypes.Length; i++)
			{
				Type type = argumentTypes[i];
				switch (argumentVariations[i])
				{
				case ArgumentType.Ref:
				case ArgumentType.Out:
					type = type.MakeByRefType();
					break;
				case ArgumentType.Pointer:
					type = type.MakePointerType();
					break;
				}
				list.Add(type);
			}
			info.argumentTypes = list.ToArray();
		}
	}
	[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = true)]
	public class HarmonyDelegate : HarmonyPatch
	{
		public HarmonyDelegate(Type declaringType)
			: base(declaringType)
		{
		}

		public HarmonyDelegate(Type declaringType, Type[] argumentTypes)
			: base(declaringType, argumentTypes)
		{
		}

		public HarmonyDelegate(Type declaringType, string methodName)
			: base(declaringType, methodName)
		{
		}

		public HarmonyDelegate(Type declaringType, string methodName, params Type[] argumentTypes)
			: base(declaringType, methodName, argumentTypes)
		{
		}

		public HarmonyDelegate(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(declaringType, methodName, argumentTypes, argumentVariations)
		{
		}

		public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType)
			: base(declaringType, MethodType.Normal)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, params Type[] argumentTypes)
			: base(declaringType, MethodType.Normal, argumentTypes)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(declaringType, MethodType.Normal, argumentTypes, argumentVariations)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type declaringType, string methodName, MethodDispatchType methodDispatchType)
			: base(declaringType, methodName, MethodType.Normal)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(string methodName)
			: base(methodName)
		{
		}

		public HarmonyDelegate(string methodName, params Type[] argumentTypes)
			: base(methodName, argumentTypes)
		{
		}

		public HarmonyDelegate(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(methodName, argumentTypes, argumentVariations)
		{
		}

		public HarmonyDelegate(string methodName, MethodDispatchType methodDispatchType)
			: base(methodName, MethodType.Normal)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(MethodDispatchType methodDispatchType)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(MethodDispatchType methodDispatchType, params Type[] argumentTypes)
			: base(MethodType.Normal, argumentTypes)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(MethodType.Normal, argumentTypes, argumentVariations)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type[] argumentTypes)
			: base(argumentTypes)
		{
		}

		public HarmonyDelegate(Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(argumentTypes, argumentVariations)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
	public class HarmonyReversePatch : HarmonyAttribute
	{
		public HarmonyReversePatch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
		{
			info.reversePatchType = type;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	public class HarmonyPatchAll : HarmonyAttribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyPriority : HarmonyAttribute
	{
		public HarmonyPriority(int priority)
		{
			info.priority = priority;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyBefore : HarmonyAttribute
	{
		public HarmonyBefore(params string[] before)
		{
			info.before = before;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyAfter : HarmonyAttribute
	{
		public HarmonyAfter(params string[] after)
		{
			info.after = after;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyDebug : HarmonyAttribute
	{
		public HarmonyDebug()
		{
			info.debug = true;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyEmitIL : HarmonyAttribute
	{
		public HarmonyEmitIL()
		{
			info.debugEmitPath = "./";
		}

		public HarmonyEmitIL(string dir)
		{
			info.debugEmitPath = dir;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyWrapSafe : HarmonyAttribute
	{
		public HarmonyWrapSafe()
		{
			info.wrapTryCatch = true;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrepare : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyCleanup : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethod : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethods : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrefix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPostfix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTranspiler : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyILManipulator : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyFinalizer : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)]
	public class HarmonyArgument : Attribute
	{
		public string OriginalName { get; private set; }

		public int Index { get; private set; }

		public string NewName { get; private set; }

		public HarmonyArgument(string originalName)
			: this(originalName, null)
		{
		}

		public HarmonyArgument(int index)
			: this(index, null)
		{
		}

		public HarmonyArgument(string originalName, string newName)
		{
			OriginalName = originalName;
			Index = -1;
			NewName = newName;
		}

		public HarmonyArgument(int index, string name)
		{
			OriginalName = null;
			Index = index;
			NewName = name;
		}
	}
	public class CodeInstruction
	{
		public OpCode opcode;

		public object operand;

		public List<Label> labels = new List<Label>();

		public List<ExceptionBlock> blocks = new List<ExceptionBlock>();

		internal CodeInstruction()
		{
		}

		public CodeInstruction(OpCode opcode, object operand = null)
		{
			this.opcode = opcode;
			this.operand = operand;
		}

		public CodeInstruction(CodeInstruction instruction)
		{
			opcode = instruction.opcode;
			operand = instruction.operand;
			labels = instruction.labels.ToList();
			blocks = instruction.blocks.ToList();
		}

		public CodeInstruction Clone()
		{
			return new CodeInstruction(this)
			{
				labels = new List<Label>(),
				blocks = new List<ExceptionBlock>()
			};
		}

		public CodeInstruction Clone(OpCode opcode)
		{
			CodeInstruction codeInstruction = Clone();
			codeInstruction.opcode = opcode;
			return codeInstruction;
		}

		public CodeInstruction Clone(object operand)
		{
			CodeInstruction codeInstruction = Clone();
			codeInstruction.operand = operand;
			return codeInstruction;
		}

		public static CodeInstruction Call(Type type, string name, Type[] parameters = null, Type[] generics = null)
		{
			MethodInfo methodInfo = AccessTools.Method(type, name, parameters, generics);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException($"No method found for type={type}, name={name}, parameters={parameters.Description()}, generics={generics.Description()}");
			}
			return new CodeInstruction(OpCodes.Call, methodInfo);
		}

		public static CodeInstruction Call(string typeColonMethodname, Type[] parameters = null, Type[] generics = null)
		{
			MethodInfo methodInfo = AccessTools.Method(typeColonMethodname, parameters, generics);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException("No method found for " + typeColonMethodname + ", parameters=" + parameters.Description() + ", generics=" + generics.Description());
			}
			return new CodeInstruction(OpCodes.Call, methodInfo);
		}

		public static CodeInstruction Call(Expression<Action> expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction Call<T>(Expression<Action<T>> expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction Call<T, TResult>(Expression<Func<T, TResult>> expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction Call(LambdaExpression expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction CallClosure<T>(T closure) where T : Delegate
		{
			return Transpilers.EmitDelegate(closure);
		}

		public static CodeInstruction LoadField(Type type, string name, bool useAddress = false)
		{
			FieldInfo fieldInfo = AccessTools.Field(type, name);
			if ((object)fieldInfo == null)
			{
				throw new ArgumentException($"No field found for {type} and {name}");
			}
			return new CodeInstruction((!useAddress) ? (fieldInfo.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld) : (fieldInfo.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda), fieldInfo);
		}

		public static CodeInstruction StoreField(Type type, string name)
		{
			FieldInfo fieldInfo = AccessTools.Field(type, name);
			if ((object)fieldInfo == null)
			{
				throw new ArgumentException($"No field found for {type} and {name}");
			}
			return new CodeInstruction(fieldInfo.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, fieldInfo);
		}

		public override string ToString()
		{
			List<string> list = new List<string>();
			foreach (Label label in labels)
			{
				list.Add($"Label{label.GetHashCode()}");
			}
			foreach (ExceptionBlock block in blocks)
			{
				list.Add("EX_" + block.blockType.ToString().Replace("Block", ""));
			}
			string text = ((list.Count > 0) ? (" [" + string.Join(", ", list.ToArray()) + "]") : "");
			string text2 = FormatArgument(operand);
			if (text2.Length > 0)
			{
				text2 = " " + text2;
			}
			OpCode opCode = opcode;
			return opCode.ToString() + text2 + text;
		}

		internal static string FormatArgument(object argument, string extra = null)
		{
			if (argument == null)
			{
				return "NULL";
			}
			Type type = argument.GetType();
			if (argument is MethodBase member)
			{
				return member.FullDescription() + ((extra != null) ? (" " + extra) : "");
			}
			if (argument is FieldInfo fieldInfo)
			{
				return fieldInfo.FieldType.FullDescription() + " " + fieldInfo.DeclaringType.FullDescription() + "::" + fieldInfo.Name;
			}
			if ((object)type == typeof(Label))
			{
				return $"Label{((Label)argument).GetHashCode()}";
			}
			if ((object)type == typeof(Label[]))
			{
				return "Labels" + string.Join(",", ((Label[])argument).Select((Label l) => l.GetHashCode().ToString()).ToArray());
			}
			if ((object)type == typeof(LocalBuilder))
			{
				return $"{((LocalBuilder)argument).LocalIndex} ({((LocalBuilder)argument).LocalType})";
			}
			if ((object)type == typeof(string))
			{
				return argument.ToString().ToLiteral();
			}
			return argument.ToString().Trim();
		}
	}
	public enum ExceptionBlockType
	{
		BeginExceptionBlock,
		BeginCatchBlock,
		BeginExceptFilterBlock,
		BeginFaultBlock,
		BeginFinallyBlock,
		EndExceptionBlock
	}
	public class ExceptionBlock
	{
		public ExceptionBlockType blockType;

		public Type catchType;

		public ExceptionBlock(ExceptionBlockType blockType, Type catchType = null)
		{
			this.blockType = blockType;
			this.catchType = catchType ?? typeof(object);
		}
	}
	public class InvalidHarmonyPatchArgumentException : Exception
	{
		public MethodBase Original { get; }

		public MethodInfo Patch { get; }

		public override string Message => "(" + Patch.FullDescription() + "): " + base.Message;

		public InvalidHarmonyPatchArgumentException(string message, MethodBase original, MethodInfo patch)
			: base(message)
		{
			Original = original;
			Patch = patch;
		}
	}
	public class MemberNotFoundException : Exception
	{
		public MemberNotFoundException(string message)
			: base(message)
		{
		}
	}
	public class Harmony : IDisposable
	{
		[Obsolete("Use HarmonyFileLog.Enabled instead")]
		public static bool DEBUG;

		public string Id { get; }

		static Harmony()
		{
			StackTraceFixes.Install();
		}

		public Harmony(string id)
		{
			if (string.IsNullOrEmpty(id))
			{
				throw new ArgumentException("id cannot be null or empty");
			}
			try
			{
				string environmentVariable = Environment.GetEnvironmentVariable("HARMONY_DEBUG");
				if (environmentVariable != null && environmentVariable.Length > 0)
				{
					environmentVariable = environmentVariable.Trim();
					DEBUG = environmentVariable == "1" || bool.Parse(environmentVariable);
				}
			}
			catch
			{
			}
			if (DEBUG)
			{
				HarmonyFileLog.Enabled = true;
			}
			MethodBase callingMethod = (Logger.IsEnabledFor(Logger.LogChannel.Info) ? AccessTools.GetOutsideCaller() : null);
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
				StringBuilder stringBuilder = new StringBuilder();
				Assembly assembly = typeof(Harmony).Assembly;
				Version version = assembly.GetName().Version;
				string text = assembly.Location;
				string text2 = Environment.Version.ToString();
				string text3 = Environment.OSVersion.Platform.ToString();
				if (string.IsNullOrEmpty(text))
				{
					text = new Uri(assembly.CodeBase).LocalPath;
				}
				int size = IntPtr.Size;
				Platform current = PlatformHelper.Current;
				stringBuilder.AppendLine($"### Harmony id={id}, version={version}, location={text}, env/clr={text2}, platform={text3}, ptrsize:runtime/env={size}/{current}");
				if ((object)callingMethod?.DeclaringType != null)
				{
					Assembly assembly2 = callingMethod.DeclaringType.Assembly;
					text = assembly2.Location;
					if (string.IsNullOrEmpty(text))
					{
						text = new Uri(assembly2.CodeBase).LocalPath;
					}
					stringBuilder.AppendLine("### Started from " + callingMethod.FullDescription() + ", location " + text);
					stringBuilder.Append($"### At {DateTime.Now:yyyy-MM-dd hh.mm.ss}");
				}
				return stringBuilder.ToString();
			});
			Id = id;
		}

		public void PatchAll()
		{
			Assembly assembly = new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly;
			PatchAll(assembly);
		}

		public PatchProcessor CreateProcessor(MethodBase original)
		{
			return new PatchProcessor(this, original);
		}

		public PatchClassProcessor CreateClassProcessor(Type type)
		{
			return new PatchClassProcessor(this, type);
		}

		public PatchClassProcessor CreateClassProcessor(Type type, bool allowUnannotatedType)
		{
			return new PatchClassProcessor(this, type, allowUnannotatedType);
		}

		public ReversePatcher CreateReversePatcher(MethodBase original, HarmonyMethod standin)
		{
			return new ReversePatcher(this, original, standin);
		}

		public void PatchAll(Assembly assembly)
		{
			AccessTools.GetTypesFromAssembly(assembly).Do(delegate(Type type)
			{
				CreateClassProcessor(type).Patch();
			});
		}

		public void PatchAll(Type type)
		{
			CreateClassProcessor(type, allowUnannotatedType: true).Patch();
		}

		public MethodInfo Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null, HarmonyMethod ilmanipulator = null)
		{
			PatchProcessor patchProcessor = CreateProcessor(original);
			patchProcessor.AddPrefix(prefix);
			patchProcessor.AddPostfix(postfix);
			patchProcessor.AddTranspiler(transpiler);
			patchProcessor.AddFinalizer(finalizer);
			patchProcessor.AddILManipulator(ilmanipulator);
			return patchProcessor.Patch();
		}

		[Obsolete("Use newer Patch() instead", true)]
		public MethodInfo Patch(MethodBase original, HarmonyMethod prefix, HarmonyMethod postfix, HarmonyMethod transpiler, HarmonyMethod finalizer)
		{
			return Patch(original, prefix, postfix, transpiler, finalizer, null);
		}

		public static MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler = null, MethodInfo ilmanipulator = null)
		{
			return PatchFunctions.ReversePatch(standin, original, transpiler, ilmanipulator);
		}

		[Obsolete("Use newer ReversePatch() instead", true)]
		public static MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler)
		{
			return PatchFunctions.ReversePatch(standin, original, transpiler, null);
		}

		public static void UnpatchID(string harmonyID)
		{
			if (string.IsNullOrEmpty(harmonyID))
			{
				throw new ArgumentNullException("harmonyID", "UnpatchID was called with a null or empty harmonyID.");
			}
			PatchFunctions.UnpatchConditional((Patch patchInfo) => patchInfo.owner == harmonyID);
		}

		void IDisposable.Dispose()
		{
			UnpatchSelf();
		}

		public void UnpatchSelf()
		{
			UnpatchID(Id);
		}

		public static void UnpatchAll()
		{
			Logger.Log(Logger.LogChannel.Warn, () => "UnpatchAll has been called - This will remove ALL HARMONY PATCHES.");
			PatchFunctions.UnpatchConditional((Patch _) => true);
		}

		[Obsolete("Use UnpatchSelf() to unpatch the current instance. The functionality to unpatch either other ids or EVERYTHING has been moved the static methods UnpatchID() and UnpatchAll() respectively", true)]
		public void UnpatchAll(string harmonyID = null)
		{
			if (harmonyID == null)
			{
				if (HarmonyGlobalSettings.DisallowLegacyGlobalUnpatchAll)
				{
					Logger.Log(Logger.LogChannel.Warn, () => "Legacy UnpatchAll has been called AND DisallowLegacyGlobalUnpatchAll=true. Skipping execution of UnpatchAll");
				}
				else
				{
					UnpatchAll();
				}
			}
			else if (harmonyID.Length == 0)
			{
				Logger.Log(Logger.LogChannel.Warn, () => "Legacy UnpatchAll was called with harmonyID=\"\" which is an invalid id. Skipping execution of UnpatchAll");
			}
			else
			{
				UnpatchID(harmonyID);
			}
		}

		public void Unpatch(MethodBase original, HarmonyPatchType type, string harmonyID = null)
		{
			CreateProcessor(original).Unpatch(type, harmonyID);
		}

		public void Unpatch(MethodBase original, MethodInfo patch)
		{
			CreateProcessor(original).Unpatch(patch);
		}

		public static bool HasAnyPatches(string harmonyID)
		{
			return (from original in GetAllPatchedMethods()
				select GetPatchInfo(original)).Any((Patches info) => info.Owners.Contains(harmonyID));
		}

		public static Patches GetPatchInfo(MethodBase method)
		{
			return PatchProcessor.GetPatchInfo(method);
		}

		public IEnumerable<MethodBase> GetPatchedMethods()
		{
			return from original in GetAllPatchedMethods()
				where GetPatchInfo(original).Owners.Contains(Id)
				select original;
		}

		public static IEnumerable<MethodBase> GetAllPatchedMethods()
		{
			return PatchProcessor.GetAllPatchedMethods();
		}

		public static MethodBase GetOriginalMethod(MethodInfo replacement)
		{
			if ((object)replacement == null)
			{
				throw new ArgumentNullException("replacement");
			}
			return PatchManager.GetOriginal(replacement);
		}

		public static MethodBase GetMethodFromStackframe(StackFrame frame)
		{
			if (frame == null)
			{
				throw new ArgumentNullException("frame");
			}
			return PatchManager.FindReplacement(frame) ?? frame.GetMethod();
		}

		public static Dictionary<string, Version> VersionInfo(out Version currentVersion)
		{
			return PatchProcessor.VersionInfo(out currentVersion);
		}

		public static Harmony CreateAndPatchAll(Type type, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(type);
			return harmony;
		}

		public static Harmony CreateAndPatchAll(Assembly assembly, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(assembly);
			return harmony;
		}
	}
	[Serializable]
	public class HarmonyException : Exception
	{
		private Dictionary<int, CodeInstruction> instructions;

		private int errorOffset;

		internal HarmonyException()
		{
		}

		internal HarmonyException(string message)
			: base(message)
		{
		}

		internal HarmonyException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		protected HarmonyException(SerializationInfo serializationInfo, StreamingContext streamingContext)
		{
			throw new NotImplementedException();
		}

		internal HarmonyException(Exception innerException, Dictionary<int, CodeInstruction> instructions, int errorOffset)
			: base("IL Compile Error", innerException)
		{
			this.instructions = instructions;
			this.errorOffset = errorOffset;
		}

		internal static Exception Create(Exception ex, MethodBody body)
		{
			Match match = Regex.Match(ex.Message.TrimEnd(new char[0]), "Reason: Invalid IL code in.+: IL_(\\d{4}): (.+)$");
			if (!match.Success)
			{
				return new HarmonyException("IL Compile Error (unknown location)", ex);
			}
			Dictionary<int, CodeInstruction> dictionary = ILManipulator.GetInstructions(body) ?? new Dictionary<int, CodeInstruction>();
			int num = int.Parse(match.Groups[1].Value, NumberStyles.HexNumber);
			Regex.Replace(match.Groups[2].Value, " {2,}", " ");
			if (ex is HarmonyException ex2)
			{
				if (dictionary.Count != 0)
				{
					ex2.instructions = dictionary;
					ex2.errorOffset = num;
				}
				return ex2;
			}
			return new HarmonyException(ex, dictionary, num);
		}

		public List<KeyValuePair<int, CodeInstruction>> GetInstructionsWithOffsets()
		{
			return instructions.OrderBy((KeyValuePair<int, CodeInstruction> ins) => ins.Key).ToList();
		}

		public List<CodeInstruction> GetInstructions()
		{
			return (from ins in instructions
				orderby ins.Key
				select ins.Value).ToList();
		}

		public int GetErrorOffset()
		{
			return errorOffset;
		}

		public int GetErrorIndex()
		{
			if (instructions.TryGetValue(errorOffset, out var value))
			{
				return GetInstructions().IndexOf(value);
			}
			return -1;
		}
	}
	public static class HarmonyGlobalSettings
	{
		public static bool DisallowLegacyGlobalUnpatchAll { get; set; }
	}
	public class HarmonyMethod
	{
		public MethodInfo method;

		public Type declaringType;

		public string methodName;

		public MethodType? methodType;

		public Type[] argumentTypes;

		public int priority = -1;

		public string[] before;

		public string[] after;

		public HarmonyReversePatchType? reversePatchType;

		public bool? debug;

		public string debugEmitPath;

		public bool nonVirtualDelegate;

		public bool? wrapTryCatch;

		internal string assemblyQualifiedDeclaringTypeName;

		public HarmonyMethod()
		{
		}

		private void ImportMethod(MethodInfo theMethod)
		{
			method = theMethod;
			if ((object)method != null)
			{
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(method);
				if (fromMethod != null)
				{
					Merge(fromMethod).CopyTo(this);
				}
			}
		}

		public HarmonyMethod(MethodInfo method)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			ImportMethod(method);
		}

		public HarmonyMethod(MethodInfo method, int priority = -1, string[] before = null, string[] after = null, bool? debug = null)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			ImportMethod(method);
			this.priority = priority;
			this.before = before;
			this.after = after;
			this.debug = debug;
		}

		public HarmonyMethod(Type methodType, string methodName, Type[] argumentTypes = null)
		{
			MethodInfo methodInfo = AccessTools.Method(methodType, methodName, argumentTypes);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException($"Cannot not find method for type {methodType} and name {methodName} and parameters {argumentTypes?.Description()}");
			}
			ImportMethod(methodInfo);
		}

		public static List<string> HarmonyFields()
		{
			return (from s in AccessTools.GetFieldNames(typeof(HarmonyMethod))
				where s != "method"
				select s).ToList();
		}

		public static HarmonyMethod Merge(List<HarmonyMethod> attributes)
		{
			return Merge((IEnumerable<HarmonyMethod>)attributes);
		}

		internal static HarmonyMethod Merge(IEnumerable<HarmonyMethod> attributes)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			if (attributes == null)
			{
				return harmonyMethod;
			}
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			attributes.Do(delegate(HarmonyMethod attribute)
			{
				Traverse trv = Traverse.Create(attribute);
				HarmonyFields().ForEach(delegate(string f)
				{
					object value = trv.Field(f).GetValue();
					if (value != null && (f != "priority" || (int)value != -1))
					{
						HarmonyMethodExtensions.SetValue(resultTrv, f, value);
					}
				});
			});
			return harmonyMethod;
		}

		public override string ToString()
		{
			string result = "";
			Traverse trv = Traverse.Create(this);
			HarmonyFields().ForEach(delegate(string f)
			{
				if (result.Length > 0)
				{
					result += ", ";
				}
				result += $"{f}={trv.Field(f).GetValue()}";
			});
			return "HarmonyMethod[" + result + "]";
		}

		internal string Description()
		{
			string text = (((object)declaringType != null) ? declaringType.FullName : ((assemblyQualifiedDeclaringTypeName != null) ? assemblyQualifiedDeclaringTypeName : "undefined"));
			string text2 = methodName ?? "undefined";
			string text3 = (methodType.HasValue ? methodType.Value.ToString() : "undefined");
			string text4 = ((argumentTypes != null) ? argumentTypes.Description() : "undefined");
			return "(class=" + text + ", methodname=" + text2 + ", type=" + text3 + ", args=" + text4 + ")";
		}

		internal Type GetDeclaringType()
		{
			if ((object)declaringType == null && assemblyQualifiedDeclaringTypeName != null)
			{
				declaringType = Type.GetType(assemblyQualifiedDeclaringTypeName, throwOnError: true);
			}
			return declaringType;
		}

		internal Type[] GetArgumentList()
		{
			return argumentTypes ?? EmptyType.NoArgs;
		}
	}
	internal static class EmptyType
	{
		internal static readonly Type[] NoArgs = new Type[0];
	}
	public static class HarmonyMethodExtensions
	{
		internal static void SetValue(Traverse trv, string name, object val)
		{
			if (val != null)
			{
				Traverse traverse = trv.Field(name);
				if (name == "methodType" || name == "reversePatchType")
				{
					val = Enum.ToObject(Nullable.GetUnderlyingType(traverse.GetValueType()), (int)val);
				}
				traverse.SetValue(val);
			}
		}

		public static void CopyTo(this HarmonyMethod from, HarmonyMethod to)
		{
			if (to == null)
			{
				return;
			}
			Traverse fromTrv = Traverse.Create(from);
			Traverse toTrv = Traverse.Create(to);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = fromTrv.Field(f).GetValue();
				if (value != null)
				{
					SetValue(toTrv, f, value);
				}
			});
		}

		public static HarmonyMethod Clone(this HarmonyMethod original)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			original.CopyTo(harmonyMethod);
			return harmonyMethod;
		}

		public static HarmonyMethod Merge(this HarmonyMethod master, HarmonyMethod detail)
		{
			if (detail == null)
			{
				return master;
			}
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			Traverse masterTrv = Traverse.Create(master);
			Traverse detailTrv = Traverse.Create(detail);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = masterTrv.Field(f).GetValue();
				object value2 = detailTrv.Field(f).GetValue();
				if (f != "priority" || (int)value2 != -1)
				{
					SetValue(resultTrv, f, value2 ?? value);
				}
			});
			return harmonyMethod;
		}

		private static HarmonyMethod GetHarmonyMethodInfo(object attribute)
		{
			FieldInfo field = attribute.GetType().GetField("info", AccessTools.all);
			if ((object)field == null)
			{
				return null;
			}
			if (field.FieldType.FullName != typeof(HarmonyMethod).FullName)
			{
				return null;
			}
			return AccessTools.MakeDeepCopy<HarmonyMethod>(field.GetValue(attribute));
		}

		public static List<HarmonyMethod> GetFromType(Type type)
		{
			return (from attr in type.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}

		public static HarmonyMethod GetMergedFromType(Type type)
		{
			return HarmonyMethod.Merge(GetFromType(type));
		}

		public static List<HarmonyMethod> GetFromMethod(MethodBase method)
		{
			return (from attr in method.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}

		public static HarmonyMethod GetMergedFromMethod(MethodBase method)
		{
			return HarmonyMethod.Merge(GetFromMethod(method));
		}
	}
	public class InlineSignature : ICallSiteGenerator
	{
		public class ModifierType
		{
			public bool IsOptional;

			public Type Modifier;

			public object Type;

			public override string ToString()
			{
				return ((Type is Type type) ? type.FullDescription() : Type?.ToString()) + " mod" + (IsOptional ? "opt" : "req") + "(" + Modifier?.FullDescription() + ")";
			}

			internal TypeReference ToTypeReference(ModuleDefinition module)
			{
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0044: Expected O, but got Unknown
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Expected O, but got Unknown
				if (!IsOptional)
				{
					return (TypeReference)new RequiredModifierType(module.ImportReference(Modifier), GetTypeReference(module, Type));
				}
				return (TypeReference)new OptionalModifierType(module.ImportReference(Modifier), GetTypeReference(module, Type));
			}
		}

		public bool HasThis { get; set; }

		public bool ExplicitThis { get; set; }

		public CallingConvention CallingConvention { get; set; } = CallingConvention.Winapi;


		public List<object> Parameters { get; set; } = new List<object>();


		public object ReturnType { get; set; } = typeof(void);


		public override string ToString()
		{
			return ((ReturnType is Type type) ? type.FullDescription() : ReturnType?.ToString()) + " (" + Parameters.Join((object p) => (!(p is Type type2)) ? p?.ToString() : type2.FullDescription()) + ")";
		}

		internal static TypeReference GetTypeReference(ModuleDefinition module, object param)
		{
			if (!(param is Type type))
			{
				if (!(param is InlineSignature inlineSignature))
				{
					if (param is ModifierType modifierType)
					{
						return modifierType.ToTypeReference(module);
					}
					throw new NotSupportedException($"Unsupported inline signature parameter type: {param} ({param?.GetType().FullDescription()})");
				}
				return (TypeReference)(object)inlineSignature.ToFunctionPointer(module);
			}
			return module.ImportReference(type);
		}

		CallSite ICallSiteGenerator.ToCallSite(ModuleDefinition module)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_003a: 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
			CallSite val = new CallSite(GetTypeReference(module, ReturnType))
			{
				HasThis = HasThis,
				ExplicitThis = ExplicitThis,
				CallingConvention = (MethodCallingConvention)(byte)((byte)CallingConvention - 1)
			};
			foreach (object parameter in Parameters)
			{
				val.Parameters.Add(new ParameterDefinition(GetTypeReference(module, parameter)));
			}
			return val;
		}

		private FunctionPointerType ToFunctionPointer(ModuleDefinition module)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			FunctionPointerType val = new FunctionPointerType
			{
				ReturnType = GetTypeReference(module, ReturnType),
				HasThis = HasThis,
				ExplicitThis = ExplicitThis,
				CallingConvention = (MethodCallingConvention)(byte)((byte)CallingConvention - 1)
			};
			foreach (object parameter in Parameters)
			{
				val.Parameters.Add(new ParameterDefinition(GetTypeReference(module, parameter)));
			}
			return val;
		}
	}
	internal static class PatchInfoSerialization
	{
		private class Binder : SerializationBinder
		{
			public override Type BindToType(string assemblyName, string typeName)
			{
				Type[] array = new Type[3]
				{
					typeof(PatchInfo),
					typeof(Patch[]),
					typeof(Patch)
				};
				foreach (Type type in array)
				{
					if (typeName == type.FullName)
					{
						return type;
					}
				}
				return Type.GetType($"{typeName}, {assemblyName}");
			}
		}

		internal static byte[] Serialize(this PatchInfo patchInfo)
		{
			using MemoryStream memoryStream = new MemoryStream();
			new BinaryFormatter().Serialize(memoryStream, patchInfo);
			return memoryStream.GetBuffer();
		}

		internal static PatchInfo Deserialize(byte[] bytes)
		{
			BinaryFormatter obj = new BinaryFormatter
			{
				Binder = new Binder()
			};
			MemoryStream serializationStream = new MemoryStream(bytes);
			return (PatchInfo)obj.Deserialize(serializationStream);
		}

		internal static int PriorityComparer(object obj, int index, int priority)
		{
			Traverse traverse = Traverse.Create(obj);
			int value = traverse.Field("priority").GetValue<int>();
			int value2 = traverse.Field("index").GetValue<int>();
			if (priority != value)
			{
				return -priority.CompareTo(value);
			}
			return index.CompareTo(value2);
		}
	}
	[Serializable]
	public class PatchInfo
	{
		public Patch[] prefixes = new Patch[0];

		public Patch[] postfixes = new Patch[0];

		public Patch[] transpilers = new Patch[0];

		public Patch[] finalizers = new Patch[0];

		public Patch[] ilmanipulators = new Patch[0];

		public bool Debugging
		{
			get
			{
				if (!prefixes.Any((Patch p) => p.debug) && !postfixes.Any((Patch p) => p.debug) && !transpilers.Any((Patch p) => p.debug) && !finalizers.Any((Patch p) => p.debug))
				{
					return ilmanipulators.Any((Patch p) => p.debug);
				}
				return true;
			}
		}

		public string[] DebugEmitPaths => (from p in prefixes.Concat(postfixes).Concat(transpilers).Concat(finalizers)
				.Concat(ilmanipulators)
			select p.debugEmitPath into p
			where p != null
			select p).ToArray();

		internal void AddPrefixes(string owner, params HarmonyMethod[] methods)
		{
			prefixes = Add(owner, methods, prefixes);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddPrefix(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddPrefixes(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemovePrefix(string owner)
		{
			prefixes = Remove(owner, prefixes);
		}

		internal void AddPostfixes(string owner, params HarmonyMethod[] methods)
		{
			postfixes = Add(owner, methods, postfixes);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddPostfix(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddPostfixes(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemovePostfix(string owner)
		{
			postfixes = Remove(owner, postfixes);
		}

		internal void AddTranspilers(string owner, params HarmonyMethod[] methods)
		{
			transpilers = Add(owner, methods, transpilers);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddTranspiler(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddTranspilers(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemoveTranspiler(string owner)
		{
			transpilers = Remove(owner, transpilers);
		}

		internal void AddFinalizers(string owner, params HarmonyMethod[] methods)
		{
			finalizers = Add(owner, methods, finalizers);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddFinalizer(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddFinalizers(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemoveFinalizer(string owner)
		{
			finalizers = Remove(owner, finalizers);
		}

		internal void AddILManipulators(string owner, params HarmonyMethod[] methods)
		{
			ilmanipulators = Add(owner, methods, ilmanipulators);
		}

		public void RemoveILManipulator(string owner)
		{
			ilmanipulators = Remove(owner, ilmanipulators);
		}

		public void RemovePatch(MethodInfo patch)
		{
			prefixes = prefixes.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			postfixes = postfixes.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			transpilers = transpilers.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			finalizers = finalizers.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			ilmanipulators = ilmanipulators.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
		}

		private static Patch[] Add(string owner, HarmonyMethod[] add, Patch[] current)
		{
			if (add.Length == 0)
			{
				return current;
			}
			int initialIndex = current.Length;
			return current.Concat(add.Where((HarmonyMethod method) => method != null).Select((HarmonyMethod method, int i) => new Patch(method, i + initialIndex, owner))).ToArray();
		}

		private static Patch[] Remove(string owner, Patch[] current)
		{
			if (!(owner == "*"))
			{
				return current.Where((Patch patch) => patch.owner != owner).ToArray();
			}
			return new Patch[0];
		}
	}
	[Serializable]
	public class Patch : IComparable
	{
		public readonly int index;

		public readonly string owner;

		public readonly int priority;

		public readonly string[] before;

		public readonly string[] after;

		public readonly bool debug;

		public readonly string debugEmitPath;

		public readonly bool wrapTryCatch;

		[NonSerialized]
		private MethodInfo patchMethod;

		private int methodToken;

		private string moduleGUID;

		public MethodInfo PatchMethod
		{
			get
			{
				if ((object)patchMethod == null)
				{
					Module module = (from a in AppDomain.CurrentDomain.GetAssemblies()
						where !a.FullName.StartsWith("Microsoft.VisualStudio")
						select a).SelectMany((Assembly a) => a.GetLoadedModules()).First((Module m) => m.ModuleVersionId.ToString() == moduleGUID);
					patchMethod = (MethodInfo)module.ResolveMethod(methodToken);
				}
				return patchMethod;
			}
			set
			{
				patchMethod = value;
				methodToken = patchMethod.MetadataToken;
				moduleGUID = patchMethod.Module.ModuleVersionId.ToString();
			}
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug)
		{
			if (patch is DynamicMethod)
			{
				throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method.");
			}
			this.index = index;
			this.owner = owner;
			this.priority = ((priority == -1) ? 400 : priority);
			this.before = before ?? new string[0];
			this.after = after ?? new string[0];
			this.debug = debug;
			PatchMethod = patch;
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug, bool wrapTryCatch)
		{
			if (patch is DynamicMethod)
			{
				throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method.");
			}
			this.index = index;
			this.owner = owner;
			this.priority = ((priority == -1) ? 400 : priority);
			this.before = before ?? new string[0];
			this.after = after ?? new string[0];
			this.debug = debug;
			this.wrapTryCatch = wrapTryCatch;
			PatchMethod = patch;
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug, bool wrapTryCatch, string debugEmitPath)
		{
			if (patch is DynamicMethod)
			{
				throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method.");
			}
			this.index = index;
			this.owner = owner;
			this.priority = ((priority == -1) ? 400 : priority);
			this.before = before ?? new string[0];
			this.after = after ?? new string[0];
			this.debug = debug;
			this.debugEmitPath = debugEmitPath;
			this.wrapTryCatch = wrapTryCatch;
			PatchMethod = patch;
		}

		public Patch(HarmonyMethod method, int index, string owner)
			: this(method.method, index, owner, method.priority, method.before, method.after, method.debug.GetValueOrDefault(), method.wrapTryCatch.GetValueOrDefault(), method.debugEmitPath)
		{
		}

		public MethodInfo GetMethod(MethodBase original)
		{
			MethodInfo methodInfo = PatchMethod;
			if ((object)methodInfo.ReturnType != typeof(DynamicMethod) && (object)methodInfo.ReturnType != typeof(MethodInfo))
			{
				return methodInfo;
			}
			if (!methodInfo.IsStatic)
			{
				return methodInfo;
			}
			ParameterInfo[] parameters = methodInfo.GetParameters();
			if (parameters.Length != 1)
			{
				return methodInfo;
			}
			if ((object)parameters[0].ParameterType != typeof(MethodBase))
			{
				return methodInfo;
			}
			return methodInfo.Invoke(null, new object[1] { original }) as MethodInfo;
		}

		public override bool Equals(object obj)
		{
			if (obj != null && obj is Patch)
			{
				return (object)PatchMethod == ((Patch)obj).PatchMethod;
			}
			return false;
		}

		public int CompareTo(object obj)
		{
			return PatchInfoSerialization.PriorityComparer(obj, index, priority);
		}

		public override int GetHashCode()
		{
			return PatchMethod.GetHashCode();
		}
	}
	public class PatchClassProcessor
	{
		private readonly Harmony instance;

		private readonly Type containerType;

		private readonly HarmonyMethod containerAttributes;

		private readonly Dictionary<Type, MethodInfo> auxilaryMethods;

		private readonly List<AttributePatch> patchMethods;

		private static readonly List<Type> auxilaryTypes = new List<Type>
		{
			typeof(HarmonyPrepare),
			typeof(HarmonyCleanup),
			typeof(HarmonyTargetMethod),
			typeof(HarmonyTargetMethods)
		};

		public PatchClassProcessor(Harmony instance, Type type)
			: this(instance, type, allowUnannotatedType: false)
		{
		}

		public PatchClassProcessor(Harmony instance, Type type, bool allowUnannotatedType)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			this.instance = instance;
			containerType = type;
			List<HarmonyMethod> fromType = HarmonyMethodExtensions.GetFromType(type);
			if (!allowUnannotatedType && (fromType == null || fromType.Count == 0))
			{
				return;
			}
			containerAttributes = HarmonyMethod.Merge(fromType);
			MethodType? methodType = containerAttributes.methodType;
			if (!methodType.HasValue)
			{
				containerAttributes.methodType = MethodType.Normal;
			}
			auxilaryMethods = new Dictionary<Type, MethodInfo>();
			foreach (Type auxilaryType in auxilaryTypes)
			{
				MethodInfo patchMethod = PatchTools.GetPatchMethod(containerType, auxilaryType.FullName);
				if ((object)patchMethod != null)
				{
					auxilaryMethods[auxilaryType] = patchMethod;
				}
			}
			patchMethods = PatchTools.GetPatchMethods(containerType, (object)containerAttributes.GetDeclaringType() != null);
			foreach (AttributePatch patchMethod2 in patchMethods)
			{
				MethodInfo method = patchMethod2.info.method;
				patchMethod2.info = containerAttributes.Merge(patchMethod2.info);
				patchMethod2.info.method = method;
			}
		}

		public List<MethodInfo> Patch()
		{
			if (containerAttributes == null)
			{
				return null;
			}
			Exception exception = null;
			if (!RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, defaultIfFailing: false, null, new object[0]))
			{
				RunMethod<HarmonyCleanup>(ref exception, new object[0]);
				ReportException(exception, null);
				return new List<MethodInfo>();
			}
			List<MethodInfo> result = new List<MethodInfo>();
			MethodBase lastOriginal = null;
			try
			{
				List<MethodBase> bulkMethods = GetBulkMethods();
				if (bulkMethods.Count == 1)
				{
					lastOriginal = bulkMethods[0];
				}
				ReversePatch(ref lastOriginal);
				result = ((bulkMethods.Count > 0) ? BulkPatch(bulkMethods, ref lastOriginal) : PatchWithAttributes(ref lastOriginal));
			}
			catch (Exception ex)
			{
				exception = ex;
			}
			RunMethod<HarmonyCleanup>(ref exception, new object[1] { exception });
			ReportException(exception, lastOriginal);
			return result;
		}

		private void ReversePatch(ref MethodBase lastOriginal)
		{
			for (int i = 0; i < patchMethods.Count; i++)
			{
				AttributePatch attributePatch = patchMethods[i];
				if (attributePatch.type == HarmonyPatchType.ReversePatch)
				{
					MethodBase originalMethod = attributePatch.info.GetOriginalMethod();
					if ((object)originalMethod != null)
					{
						lastOriginal = originalMethod;
					}
					ReversePatcher reversePatcher = instance.CreateReversePatcher(lastOriginal, attributePatch.info);
					lock (PatchProcessor.locker)
					{
						reversePatcher.Patch();
					}
				}
			}
		}

		private List<MethodInfo> BulkPatch(List<MethodBase> originals, ref MethodBase lastOriginal)
		{
			PatchJobs<MethodInfo> patchJobs = new PatchJobs<MethodInfo>();
			for (int i = 0; i < originals.Count; i++)
			{
				lastOriginal = originals[i];
				PatchJobs<MethodInfo>.Job job = patchJobs.GetJob(lastOriginal);
				foreach (AttributePatch patchMethod in patchMethods)
				{
					string text = "You cannot combine TargetMethod, TargetMethods or [HarmonyPatchAll] with individual annotations";
					HarmonyMethod info = patchMethod.info;
					if (info.methodName != null)
					{
						throw new ArgumentException(text + " [" + info.methodName + "]");
					}
					if (info.methodType.HasValue && info.methodType.Value != 0)
					{
						throw new ArgumentException($"{text} [{info.methodType}]");
					}
					if (info.argumentTypes != null)
					{
						throw new ArgumentException(text + " [" + info.argumentTypes.Description() + "]");
					}
					job.AddPatch(patchMethod);
				}
			}
			foreach (PatchJobs<MethodInfo>.Job job2 in patchJobs.GetJobs())
			{
				lastOriginal = job2.original;
				ProcessPatchJob(job2);
			}
			return patchJobs.GetReplacements();
		}

		private List<MethodInfo> PatchWithAttributes(ref MethodBase lastOriginal)
		{
			PatchJobs<MethodInfo> patchJobs = new PatchJobs<MethodInfo>();
			foreach (AttributePatch patchMethod in patchMethods)
			{
				lastOriginal = patchMethod.info.GetOriginalMethod();
				if ((object)lastOriginal == null)
				{
					throw new ArgumentException("Undefined target method for patch method " + patchMethod.info.method.FullDescription());
				}
				patchJobs.GetJob(lastOriginal).AddPatch(patchMethod);
			}
			foreach (PatchJob

BooBoo Building/BepInEx/core/0Harmony20.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using HarmonyLib.Internal;
using HarmonyLib.Internal.Patching;
using HarmonyLib.Internal.Util;
using HarmonyLib.Tools;
using HarmonyXInterop;
using JetBrains.Annotations;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using MonoMod.Utils;
using MonoMod.Utils.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("HarmonyX2Interop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HarmonyX2Interop")]
[assembly: AssemblyCopyright("Copyright ©  2020")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("69F6541D-A0F5-419D-B0EE-F5017F1D34F3")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.0.0")]
[module: UnverifiableCode]
namespace JetBrains.Annotations
{
	[AttributeUsage(AttributeTargets.All)]
	internal sealed class UsedImplicitlyAttribute : Attribute
	{
		public ImplicitUseKindFlags UseKindFlags { get; }

		public ImplicitUseTargetFlags TargetFlags { get; }

		public UsedImplicitlyAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter | AttributeTargets.GenericParameter)]
	internal sealed class MeansImplicitUseAttribute : Attribute
	{
		[UsedImplicitly]
		public ImplicitUseKindFlags UseKindFlags { get; }

		[UsedImplicitly]
		public ImplicitUseTargetFlags TargetFlags { get; }

		public MeansImplicitUseAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[Flags]
	internal enum ImplicitUseKindFlags
	{
		Default = 7,
		Access = 1,
		Assign = 2,
		InstantiatedWithFixedConstructorSignature = 4,
		InstantiatedNoFixedConstructorSignature = 8
	}
	[Flags]
	internal enum ImplicitUseTargetFlags
	{
		Default = 1,
		Itself = 1,
		Members = 2,
		WithInheritors = 4,
		WithMembers = 3
	}
}
namespace HarmonyLib
{
	public static class Priority
	{
		public const int Last = 0;

		public const int VeryLow = 100;

		public const int Low = 200;

		public const int LowerThanNormal = 300;

		public const int Normal = 400;

		public const int HigherThanNormal = 500;

		public const int High = 600;

		public const int VeryHigh = 700;

		public const int First = 800;
	}
	public enum MethodType
	{
		Normal,
		Getter,
		Setter,
		Constructor,
		StaticConstructor
	}
	public enum ArgumentType
	{
		Normal,
		Ref,
		Out,
		Pointer
	}
	public enum HarmonyPatchType
	{
		All,
		Prefix,
		Postfix,
		Transpiler,
		Finalizer,
		ReversePatch
	}
	public enum HarmonyReversePatchType
	{
		Original,
		Snapshot
	}
	[MeansImplicitUse]
	public class HarmonyAttribute : Attribute
	{
		public HarmonyMethod info = new HarmonyMethod();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
	public class HarmonyPatch : HarmonyAttribute
	{
		public HarmonyPatch()
		{
		}

		public HarmonyPatch(Type declaringType)
		{
			info.declaringType = declaringType;
		}

		public HarmonyPatch(Type declaringType, Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
		}

		public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type declaringType, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type declaringType, string methodName, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(string methodName)
		{
			info.methodName = methodName;
		}

		public HarmonyPatch(string methodName, params Type[] argumentTypes)
		{
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(string methodName, MethodType methodType)
		{
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType)
		{
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType, params Type[] argumentTypes)
		{
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type[] argumentTypes)
		{
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		private void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			if (argumentVariations == null || argumentVariations.Length == 0)
			{
				info.argumentTypes = argumentTypes;
				return;
			}
			if (argumentTypes.Length < argumentVariations.Length)
			{
				throw new ArgumentException("argumentVariations contains more elements than argumentTypes", "argumentVariations");
			}
			List<Type> list = new List<Type>();
			for (int i = 0; i < argumentTypes.Length; i++)
			{
				Type type = argumentTypes[i];
				switch (argumentVariations[i])
				{
				case ArgumentType.Ref:
				case ArgumentType.Out:
					type = type.MakeByRefType();
					break;
				case ArgumentType.Pointer:
					type = type.MakePointerType();
					break;
				}
				list.Add(type);
			}
			info.argumentTypes = list.ToArray();
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
	public class HarmonyReversePatch : HarmonyAttribute
	{
		public HarmonyReversePatch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
		{
			info.reversePatchType = type;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	public class HarmonyPatchAll : HarmonyAttribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyPriority : HarmonyAttribute
	{
		public HarmonyPriority(int priority)
		{
			info.priority = priority;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyBefore : HarmonyAttribute
	{
		public HarmonyBefore(params string[] before)
		{
			info.before = before;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyAfter : HarmonyAttribute
	{
		public HarmonyAfter(params string[] after)
		{
			info.after = after;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrepare : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyCleanup : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethod : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethods : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrefix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPostfix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTranspiler : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyFinalizer : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)]
	public class HarmonyArgument : Attribute
	{
		public string OriginalName { get; private set; }

		public int Index { get; private set; }

		public string NewName { get; private set; }

		public HarmonyArgument(string originalName)
			: this(originalName, null)
		{
		}

		public HarmonyArgument(int index)
			: this(index, null)
		{
		}

		public HarmonyArgument(string originalName, string newName)
		{
			OriginalName = originalName;
			Index = -1;
			NewName = newName;
		}

		public HarmonyArgument(int index, string name)
		{
			OriginalName = null;
			Index = index;
			NewName = name;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class ParameterByRefAttribute : Attribute
	{
		public int[] ParameterIndices { get; }

		public ParameterByRefAttribute(params int[] parameterIndices)
		{
			ParameterIndices = parameterIndices;
		}
	}
	public class InvalidHarmonyPatchArgumentException : Exception
	{
		public MethodBase Original { get; }

		public MethodInfo Patch { get; }

		public override string Message => "(" + Extensions.GetID((MethodBase)Patch, (string)null, (string)null, true, false, false) + "): " + base.Message;

		public InvalidHarmonyPatchArgumentException(string message, MethodBase original, MethodInfo patch)
			: base(message)
		{
			Original = original;
			Patch = patch;
		}
	}
	public class MemberNotFoundException : Exception
	{
		public MemberNotFoundException(string message)
			: base(message)
		{
		}
	}
	public class Harmony
	{
		[Obsolete("No longer used, subscribe to Logger.LogChannel.Info")]
		public static bool DEBUG;

		[Obsolete("Not supported by HarmonyX", true)]
		public static bool SELF_PATCHING;

		public string Id { get; private set; }

		public Harmony(string id)
		{
			if (string.IsNullOrEmpty(id))
			{
				throw new ArgumentException("id cannot be null or empty");
			}
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				Assembly assembly = typeof(Harmony).Assembly;
				Version version = assembly.GetName().Version;
				string text = assembly.Location;
				if (string.IsNullOrEmpty(text))
				{
					text = new Uri(assembly.CodeBase).LocalPath;
				}
				MethodBase outsideCaller = AccessTools.GetOutsideCaller();
				Assembly assembly2 = outsideCaller.DeclaringType?.Assembly;
				string text2 = assembly2?.Location;
				if (string.IsNullOrEmpty(text2))
				{
					text2 = (((object)assembly2 != null) ? new Uri(assembly2.CodeBase).LocalPath : string.Empty);
				}
				return $"Created Harmony instance id={id}, version={version}, location={text} - Started from {Extensions.GetID(outsideCaller, (string)null, (string)null, true, false, false)} location={text2}";
			});
			Id = id;
		}

		public void PatchAll()
		{
			Assembly assembly = new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly;
			PatchAll(assembly);
		}

		public PatchProcessor ProcessorForAnnotatedClass(Type type)
		{
			List<HarmonyMethod> fromType = HarmonyMethodExtensions.GetFromType(type);
			if (fromType != null && fromType.Any())
			{
				HarmonyMethod attributes = HarmonyMethod.Merge(fromType);
				return new PatchProcessor(this, type, attributes);
			}
			return null;
		}

		public void PatchAll(Assembly assembly)
		{
			if ((object)assembly == null)
			{
				throw new ArgumentNullException("assembly");
			}
			List<PatchProcessor> list = (from x in assembly.GetTypes().Select(ProcessorForAnnotatedClass)
				where x != null
				select x).ToList();
			foreach (PatchProcessor item in list)
			{
				item.Patch();
			}
			if (list.Count == 0)
			{
				Logger.Log(Logger.LogChannel.Warn, () => "Could not find any valid Harmony patches inside of assembly " + assembly.FullName);
			}
		}

		public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null)
		{
			PatchProcessor patchProcessor = new PatchProcessor(this, original);
			patchProcessor.AddPrefix(prefix);
			patchProcessor.AddPostfix(postfix);
			patchProcessor.AddTranspiler(transpiler);
			patchProcessor.AddFinalizer(finalizer);
			return patchProcessor.Patch().FirstOrDefault();
		}

		public MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler = null)
		{
			return null;
		}

		public ReversePatcher CreateReversePatcher(MethodBase original, MethodInfo standin)
		{
			return new ReversePatcher(this, original, standin);
		}

		public void UnpatchAll(string harmonyID = null)
		{
			foreach (MethodBase item in GetAllPatchedMethods().ToList())
			{
				Patches patchInfo = GetPatchInfo(item);
				UnpatchAllId(item, patchInfo.Prefixes);
				UnpatchAllId(item, patchInfo.Postfixes);
				UnpatchAllId(item, patchInfo.Transpilers);
				UnpatchAllId(item, patchInfo.Finalizers);
			}
			void UnpatchAllId(MethodBase original, IEnumerable<Patch> patches)
			{
				foreach (Patch patch in patches)
				{
					if (harmonyID == null || patch.owner == harmonyID)
					{
						Unpatch(original, patch.patch);
					}
				}
			}
		}

		public void Unpatch(MethodBase original, HarmonyPatchType type, string harmonyID = null)
		{
			new PatchProcessor(this, original).Unpatch(type, harmonyID);
		}

		public void Unpatch(MethodBase original, MethodInfo patch)
		{
			new PatchProcessor(this, original).Unpatch(patch);
		}

		public static bool HasAnyPatches(string harmonyID)
		{
			return GetAllPatchedMethods().Select(GetPatchInfo).Any((Patches info) => info.Owners.Contains(harmonyID));
		}

		public static Patches GetPatchInfo(MethodBase method)
		{
			return PatchProcessor.GetPatchInfo(method);
		}

		public IEnumerable<MethodBase> GetPatchedMethods()
		{
			return from original in GetAllPatchedMethods()
				where GetPatchInfo(original).Owners.Contains(Id)
				select original;
		}

		public static IEnumerable<MethodBase> GetAllPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		public static Dictionary<string, Version> VersionInfo(out Version currentVersion)
		{
			return PatchProcessor.VersionInfo(out currentVersion);
		}

		public void PatchAll(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(methodInfo);
				if (fromMethod != null && fromMethod.Any())
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(inherit: true);
					HarmonyMethod combinedInfo = HarmonyMethod.Merge(fromMethod);
					List<HarmonyMethod> list = fromMethod.Where(IsMethodComplete).ToList();
					if (fromMethod.All((HarmonyMethod x) => (object)x.declaringType != combinedInfo.declaringType && x.methodName != combinedInfo.methodName))
					{
						list.Add(combinedInfo);
					}
					List<MethodBase> list2 = new List<MethodBase>();
					foreach (HarmonyMethod item in list)
					{
						foreach (int item2 in customAttributes.OfType<ParameterByRefAttribute>().SelectMany((ParameterByRefAttribute x) => x.ParameterIndices))
						{
							if (!item.argumentTypes[item2].IsByRef)
							{
								item.argumentTypes[item2] = item.argumentTypes[item2].MakeByRefType();
							}
						}
						if (!item.methodType.HasValue)
						{
							item.methodType = MethodType.Normal;
						}
						if ((object)item.method == null)
						{
							item.method = methodInfo;
						}
						MethodBase originalMethod = PatchProcessor.GetOriginalMethod(item);
						if ((object)originalMethod != null)
						{
							list2.Add(originalMethod);
						}
					}
					PatchProcessor patchProcessor = new PatchProcessor(this);
					foreach (MethodBase item3 in list2)
					{
						patchProcessor.AddOriginal(item3);
					}
					if (customAttributes.Any((object x) => x is HarmonyPrefix))
					{
						patchProcessor.AddPrefix(new HarmonyMethod(methodInfo));
					}
					if (customAttributes.Any((object x) => x is HarmonyTranspiler))
					{
						patchProcessor.AddTranspiler(new HarmonyMethod(methodInfo));
					}
					if (customAttributes.Any((object x) => x is HarmonyPostfix))
					{
						patchProcessor.AddPostfix(new HarmonyMethod(methodInfo));
					}
					if (customAttributes.Any((object x) => x is HarmonyFinalizer))
					{
						patchProcessor.AddFinalizer(new HarmonyMethod(methodInfo));
					}
					patchProcessor.Patch();
				}
				else if ((Logger.ChannelFilter & Logger.LogChannel.Warn) != 0 && methodInfo.GetCustomAttributes(typeof(HarmonyAttribute), inherit: true).Any())
				{
					Logger.LogText(Logger.LogChannel.Warn, "Method " + methodInfo.FullDescription() + " has an invalid combination of Harmony attributes and will be ignored");
				}
			}
			static bool IsMethodComplete(HarmonyMethod m)
			{
				if ((object)m.declaringType != null)
				{
					if (m.methodName == null && m.methodType != MethodType.Constructor)
					{
						return m.methodType == MethodType.StaticConstructor;
					}
					return true;
				}
				return false;
			}
		}

		public static Harmony CreateAndPatchAll(Type type, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(type);
			return harmony;
		}

		public static Harmony CreateAndPatchAll(Assembly assembly, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(assembly);
			return harmony;
		}
	}
	public class HarmonyMethod
	{
		public MethodInfo method;

		public Type declaringType;

		public string methodName;

		public MethodType? methodType;

		public Type[] argumentTypes;

		public int priority = -1;

		public string[] before;

		public string[] after;

		public HarmonyReversePatchType? reversePatchType;

		public HarmonyMethod()
		{
		}

		private void ImportMethod(MethodInfo theMethod)
		{
			method = theMethod;
			if ((object)method != null)
			{
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(method);
				if (fromMethod != null)
				{
					Merge(fromMethod).CopyTo(this);
				}
			}
		}

		public HarmonyMethod(MethodInfo method)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			ImportMethod(method);
		}

		public HarmonyMethod(Type type, string name, Type[] parameters = null)
		{
			MethodInfo methodInfo = AccessTools.Method(type, name, parameters);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException($"Cannot not find method for type {type} and name {name} and parameters {parameters?.Description()}");
			}
			ImportMethod(methodInfo);
		}

		public static List<string> HarmonyFields()
		{
			return (from s in AccessTools.GetFieldNames(typeof(HarmonyMethod))
				where s != "method"
				select s).ToList();
		}

		public static HarmonyMethod Merge(List<HarmonyMethod> attributes)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			if (attributes == null)
			{
				return harmonyMethod;
			}
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			attributes.ForEach(delegate(HarmonyMethod attribute)
			{
				Traverse trv = Traverse.Create(attribute);
				HarmonyFields().ForEach(delegate(string f)
				{
					object value = trv.Field(f).GetValue();
					if (value != null)
					{
						HarmonyMethodExtensions.SetValue(resultTrv, f, value);
					}
				});
			});
			return harmonyMethod;
		}

		public override string ToString()
		{
			string result = "HarmonyMethod[";
			Traverse trv = Traverse.Create(this);
			HarmonyFields().ForEach(delegate(string f)
			{
				result += $"{f}{'='}{trv.Field(f).GetValue()}";
			});
			return result + "]";
		}
	}
	public static class HarmonyMethodExtensions
	{
		internal static void SetValue(Traverse trv, string name, object val)
		{
			if (val != null)
			{
				Traverse traverse = trv.Field(name);
				if (name == "methodType" || name == "reversePatchType")
				{
					val = Enum.ToObject(Nullable.GetUnderlyingType(traverse.GetValueType()), (int)val);
				}
				traverse.SetValue(val);
			}
		}

		public static void CopyTo(this HarmonyMethod from, HarmonyMethod to)
		{
			if (to == null)
			{
				return;
			}
			Traverse fromTrv = Traverse.Create(from);
			Traverse toTrv = Traverse.Create(to);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = fromTrv.Field(f).GetValue();
				if (value != null)
				{
					SetValue(toTrv, f, value);
				}
			});
		}

		public static HarmonyMethod Clone(this HarmonyMethod original)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			original.CopyTo(harmonyMethod);
			return harmonyMethod;
		}

		public static HarmonyMethod Merge(this HarmonyMethod master, HarmonyMethod detail)
		{
			if (detail == null)
			{
				return master;
			}
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			Traverse masterTrv = Traverse.Create(master);
			Traverse detailTrv = Traverse.Create(detail);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = masterTrv.Field(f).GetValue();
				object value2 = detailTrv.Field(f).GetValue();
				SetValue(resultTrv, f, value2 ?? value);
			});
			return harmonyMethod;
		}

		private static HarmonyMethod GetHarmonyMethodInfo(object attribute)
		{
			FieldInfo field = attribute.GetType().GetField("info", AccessTools.all);
			if ((object)field == null)
			{
				return null;
			}
			if (field.FieldType.Name != "HarmonyMethod")
			{
				return null;
			}
			return AccessTools.MakeDeepCopy<HarmonyMethod>(field.GetValue(attribute));
		}

		public static List<HarmonyMethod> GetFromType(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from attr in type.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}

		public static HarmonyMethod GetMergedFromType(Type type)
		{
			return HarmonyMethod.Merge(GetFromType(type));
		}

		public static HarmonyMethod GetMergedFromMethod(MethodBase method)
		{
			return HarmonyMethod.Merge(GetFromMethod(method));
		}

		public static List<HarmonyMethod> GetFromMethod(MethodBase method)
		{
			return (from attr in method.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}
	}
	[Obsolete("Exists for legacy support", true)]
	internal static class HarmonySharedState
	{
		[Obsolete("Exists for legacy support", true)]
		public static PatchInfo GetPatchInfo(MethodBase method)
		{
			return method.ToPatchInfo();
		}

		[Obsolete("Exists for legacy support", true)]
		public static IEnumerable<MethodBase> GetPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		[Obsolete("Exists for legacy support", true)]
		public static void UpdatePatchInfo(MethodBase methodBase, PatchInfo patchInfo)
		{
		}
	}
	[Obsolete("Exists for legacy support", true)]
	internal static class PatchFunctions
	{
		[Obsolete("Exists for legacy support", true)]
		public static DynamicMethod UpdateWrapper(MethodBase original, PatchInfo info, string id)
		{
			original.GetMethodPatcher().Apply();
			return null;
		}
	}
	public class PatchInfo
	{
		public Patch[] prefixes;

		public Patch[] postfixes;

		public Patch[] transpilers;

		public Patch[] finalizers;

		public PatchInfo()
		{
			prefixes = new Patch[0];
			postfixes = new Patch[0];
			transpilers = new Patch[0];
			finalizers = new Patch[0];
		}

		private void AddPatch(ref Patch[] list, string owner, HarmonyMethod info)
		{
			if ((object)info?.method != null)
			{
				int priority = ((info.priority == -1) ? 400 : info.priority);
				string[] before = info.before ?? new string[0];
				string[] after = info.after ?? new string[0];
				AddPatch(ref list, info.method, owner, priority, before, after);
			}
		}

		private void AddPatch(ref Patch[] list, MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			List<Patch> list2 = list.ToList();
			list2.Add(new Patch(patch, prefixes.Count() + 1, owner, priority, before, after));
			list = list2.ToArray();
		}

		private void RemovePatch(ref Patch[] list, string owner)
		{
			if (owner == "*")
			{
				list = new Patch[0];
				return;
			}
			list = list.Where((Patch patch) => patch.owner != owner).ToArray();
		}

		public void AddPrefix(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref prefixes, patch, owner, priority, before, after);
		}

		public void AddPrefix(string owner, HarmonyMethod info)
		{
			AddPatch(ref prefixes, owner, info);
		}

		public void RemovePrefix(string owner)
		{
			RemovePatch(ref prefixes, owner);
		}

		public void AddPostfix(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref postfixes, patch, owner, priority, before, after);
		}

		public void AddPostfix(string owner, HarmonyMethod info)
		{
			AddPatch(ref postfixes, owner, info);
		}

		public void RemovePostfix(string owner)
		{
			RemovePatch(ref postfixes, owner);
		}

		public void AddTranspiler(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref transpilers, patch, owner, priority, before, after);
		}

		public void AddTranspiler(string owner, HarmonyMethod info)
		{
			AddPatch(ref transpilers, owner, info);
		}

		public void RemoveTranspiler(string owner)
		{
			RemovePatch(ref transpilers, owner);
		}

		public void AddFinalizer(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref finalizers, patch, owner, priority, before, after);
		}

		public void AddFinalizer(string owner, HarmonyMethod info)
		{
			AddPatch(ref finalizers, owner, info);
		}

		public void RemoveFinalizer(string owner)
		{
			RemovePatch(ref finalizers, owner);
		}

		public void RemovePatch(MethodInfo patch)
		{
			lock (this)
			{
				prefixes = prefixes.Where((Patch p) => (object)p.patch != patch).ToArray();
				postfixes = postfixes.Where((Patch p) => (object)p.patch != patch).ToArray();
				transpilers = transpilers.Where((Patch p) => (object)p.patch != patch).ToArray();
				finalizers = finalizers.Where((Patch p) => (object)p.patch != patch).ToArray();
			}
		}
	}
	public class Patch : IComparable
	{
		public readonly int index;

		public readonly string owner;

		public readonly int priority;

		public readonly string[] before;

		public readonly string[] after;

		public MethodInfo patch;

		public MethodInfo PatchMethod
		{
			get
			{
				return patch;
			}
			set
			{
				patch = value;
			}
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after)
		{
			if (patch is DynamicMethod)
			{
				throw new ArgumentException("Cannot directly reference dynamic method \"" + Extensions.GetID((MethodBase)patch, (string)null, (string)null, true, false, false) + "\" in Harmony. Use a factory method instead that will return the dynamic method.", "patch");
			}
			this.index = index;
			this.owner = owner;
			this.priority = priority;
			this.before = before;
			this.after = after;
			this.patch = patch;
		}

		public MethodInfo GetMethod(MethodBase original)
		{
			if ((object)patch.ReturnType != typeof(DynamicMethod) && (object)patch.ReturnType != typeof(MethodInfo))
			{
				return patch;
			}
			if (!patch.IsStatic)
			{
				return patch;
			}
			ParameterInfo[] parameters = patch.GetParameters();
			if (parameters.Count() != 1)
			{
				return patch;
			}
			if ((object)parameters[0].ParameterType != typeof(MethodBase))
			{
				return patch;
			}
			return patch.Invoke(null, new object[1] { original }) as MethodInfo;
		}

		public override bool Equals(object obj)
		{
			if (obj is Patch patch)
			{
				return (object)this.patch == patch.patch;
			}
			return false;
		}

		public int CompareTo(object obj)
		{
			if (!(obj is Patch patch))
			{
				return 0;
			}
			int num;
			if (patch.priority != priority)
			{
				num = priority;
				return -num.CompareTo(patch.priority);
			}
			num = index;
			return num.CompareTo(patch.index);
		}

		public override int GetHashCode()
		{
			return patch.GetHashCode();
		}
	}
	public class Patches
	{
		public readonly ReadOnlyCollection<Patch> Prefixes;

		public readonly ReadOnlyCollection<Patch> Postfixes;

		public readonly ReadOnlyCollection<Patch> Transpilers;

		public readonly ReadOnlyCollection<Patch> Finalizers;

		public ReadOnlyCollection<string> Owners
		{
			get
			{
				HashSet<string> hashSet = new HashSet<string>();
				hashSet.UnionWith(Prefixes.Select((Patch p) => p.owner));
				hashSet.UnionWith(Postfixes.Select((Patch p) => p.owner));
				hashSet.UnionWith(Transpilers.Select((Patch p) => p.owner));
				hashSet.UnionWith(Finalizers.Select((Patch p) => p.owner));
				return hashSet.ToList().AsReadOnly();
			}
		}

		public Patches(Patch[] prefixes, Patch[] postfixes, Patch[] transpilers, Patch[] finalizers)
		{
			if (prefixes == null)
			{
				prefixes = new Patch[0];
			}
			if (postfixes == null)
			{
				postfixes = new Patch[0];
			}
			if (transpilers == null)
			{
				transpilers = new Patch[0];
			}
			if (finalizers == null)
			{
				finalizers = new Patch[0];
			}
			Prefixes = prefixes.ToList().AsReadOnly();
			Postfixes = postfixes.ToList().AsReadOnly();
			Transpilers = transpilers.ToList().AsReadOnly();
			Finalizers = finalizers.ToList().AsReadOnly();
		}
	}
	public class PatchProcessor
	{
		private readonly Harmony instance;

		private readonly Type container;

		private readonly HarmonyMethod containerAttributes;

		private readonly List<MethodBase> originals = new List<MethodBase>();

		private HarmonyMethod prefix;

		private HarmonyMethod postfix;

		private HarmonyMethod transpiler;

		private HarmonyMethod finalizer;

		public PatchProcessor(Harmony instance, MethodBase original = null)
		{
			this.instance = instance;
			if ((object)original != null)
			{
				originals.Add(original);
			}
		}

		public PatchProcessor(Harmony instance, Type type, HarmonyMethod attributes)
		{
			this.instance = instance;
			container = type;
			containerAttributes = attributes ?? new HarmonyMethod();
			prefix = containerAttributes.Clone();
			postfix = containerAttributes.Clone();
			transpiler = containerAttributes.Clone();
			finalizer = containerAttributes.Clone();
			PrepareType();
		}

		[Obsolete("Use other constructors and Add* methods")]
		public PatchProcessor(Harmony instance, List<MethodBase> originals, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null)
		{
			this.instance = instance;
			this.originals = originals;
			this.prefix = prefix;
			this.postfix = postfix;
			this.transpiler = transpiler;
			this.finalizer = finalizer;
		}

		public PatchProcessor AddOriginal(MethodBase original)
		{
			if (!originals.Contains(original))
			{
				originals.Add(original);
			}
			return this;
		}

		public PatchProcessor SetOriginals(List<MethodBase> originals)
		{
			this.originals.Clear();
			this.originals.AddRange(originals);
			return this;
		}

		public PatchProcessor AddPrefix(HarmonyMethod prefix)
		{
			this.prefix = prefix;
			return this;
		}

		public PatchProcessor AddPrefix(MethodInfo fixMethod)
		{
			prefix = new HarmonyMethod(fixMethod);
			return this;
		}

		public PatchProcessor AddPostfix(HarmonyMethod postfix)
		{
			this.postfix = postfix;
			return this;
		}

		public PatchProcessor AddPostfix(MethodInfo fixMethod)
		{
			postfix = new HarmonyMethod(fixMethod);
			return this;
		}

		public PatchProcessor AddTranspiler(HarmonyMethod transpiler)
		{
			this.transpiler = transpiler;
			return this;
		}

		public PatchProcessor AddTranspiler(MethodInfo fixMethod)
		{
			transpiler = new HarmonyMethod(fixMethod);
			return this;
		}

		public PatchProcessor AddFinalizer(HarmonyMethod finalizer)
		{
			this.finalizer = finalizer;
			return this;
		}

		public PatchProcessor AddFinalizer(MethodInfo fixMethod)
		{
			finalizer = new HarmonyMethod(fixMethod);
			return this;
		}

		public static Patches GetPatchInfo(MethodBase method)
		{
			PatchInfo patchInfo = method.GetPatchInfo();
			if (patchInfo == null)
			{
				return null;
			}
			lock (patchInfo)
			{
				return new Patches(patchInfo.prefixes, patchInfo.postfixes, patchInfo.transpilers, patchInfo.finalizers);
			}
		}

		public static Dictionary<string, Version> VersionInfo(out Version currentVersion)
		{
			currentVersion = typeof(Harmony).Assembly.GetName().Version;
			Dictionary<string, Assembly> assemblies = new Dictionary<string, Assembly>();
			foreach (MethodBase allPatchedMethod in GetAllPatchedMethods())
			{
				Patches patchInfo = GetPatchInfo(allPatchedMethod);
				AddAssemblies(patchInfo.Prefixes);
				AddAssemblies(patchInfo.Postfixes);
				AddAssemblies(patchInfo.Transpilers);
				AddAssemblies(patchInfo.Finalizers);
			}
			Dictionary<string, Version> dictionary = new Dictionary<string, Version>();
			foreach (KeyValuePair<string, Assembly> item in assemblies)
			{
				AssemblyName assemblyName = item.Value.GetReferencedAssemblies().FirstOrDefault((AssemblyName a) => a.FullName.StartsWith("0Harmony, Version", StringComparison.Ordinal));
				if (assemblyName != null)
				{
					dictionary[item.Key] = assemblyName.Version;
				}
			}
			return dictionary;
			void AddAssemblies(IEnumerable<Patch> patches)
			{
				foreach (Patch patch in patches)
				{
					assemblies[patch.owner] = patch.patch.DeclaringType?.Assembly;
				}
			}
		}

		public static List<CodeInstruction> GetOriginalInstructions(MethodBase original, ILGenerator generator = null)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			DynamicMethodDefinition val = new DynamicMethodDefinition(original);
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body);
			ILGenerator il = generator ?? ((ILGeneratorShim)new CecilILGenerator(val.GetILProcessor())).GetProxy();
			return iLManipulator.GetInstructions(il);
		}

		public static List<CodeInstruction> GetOriginalInstructions(MethodBase original, out ILGenerator generator)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			DynamicMethodDefinition val = new DynamicMethodDefinition(original);
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body);
			generator = ((ILGeneratorShim)new CecilILGenerator(val.GetILProcessor())).GetProxy();
			return iLManipulator.GetInstructions(generator);
		}

		[Obsolete("Use GetAllPatchedMethods instead")]
		public static IEnumerable<MethodBase> AllPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		public static IEnumerable<MethodBase> GetAllPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		public List<DynamicMethod> Patch()
		{
			Stopwatch sw = null;
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				sw = Stopwatch.StartNew();
				return "Patching " + instance.Id + "...";
			});
			List<DynamicMethod> result = new List<DynamicMethod>();
			foreach (MethodBase original in originals)
			{
				if ((object)original == null)
				{
					throw new NullReferenceException("Null method for " + instance.Id);
				}
				Logger.Log(Logger.LogChannel.Info, () => "Patching " + Extensions.GetID(original, (string)null, (string)null, true, false, false));
				bool individualPrepareResult = RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, new object[1] { original });
				Logger.Log(Logger.LogChannel.Info, () => $"HarmonyPrepare result: {individualPrepareResult}");
				if (individualPrepareResult)
				{
					PatchInfo patchInfo = original.ToPatchInfo();
					lock (patchInfo)
					{
						patchInfo.AddPrefix(instance.Id, prefix);
						patchInfo.AddPostfix(instance.Id, postfix);
						patchInfo.AddTranspiler(instance.Id, transpiler);
						patchInfo.AddFinalizer(instance.Id, finalizer);
					}
					original.GetMethodPatcher().Apply();
					RunMethod<HarmonyCleanup>(new object[1] { original });
				}
			}
			Logger.Log(Logger.LogChannel.Info, () => $"Patching {instance.Id} took {sw.ElapsedMilliseconds}ms");
			return result;
		}

		public PatchProcessor Unpatch(HarmonyPatchType type, string harmonyID)
		{
			foreach (MethodBase original in originals)
			{
				PatchInfo patchInfo = original.ToPatchInfo();
				lock (patchInfo)
				{
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Prefix)
					{
						patchInfo.RemovePrefix(harmonyID);
					}
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Postfix)
					{
						patchInfo.RemovePostfix(harmonyID);
					}
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Transpiler)
					{
						patchInfo.RemoveTranspiler(harmonyID);
					}
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Finalizer)
					{
						patchInfo.RemoveFinalizer(harmonyID);
					}
				}
				original.GetMethodPatcher().Apply();
			}
			return this;
		}

		public PatchProcessor Unpatch(MethodInfo patch)
		{
			foreach (MethodBase original in originals)
			{
				original.ToPatchInfo().RemovePatch(patch);
				original.GetMethodPatcher().Apply();
			}
			return this;
		}

		private void PrepareType()
		{
			if (!RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, new object[0]))
			{
				return;
			}
			MethodType? methodType = containerAttributes.methodType;
			if (!containerAttributes.methodType.HasValue)
			{
				containerAttributes.methodType = MethodType.Normal;
			}
			string reversePatchAttr = typeof(HarmonyReversePatch).FullName;
			foreach (MethodInfo item in (from m in container.GetMethods(AccessTools.all)
				where m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == reversePatchAttr)
				select m).ToList())
			{
				MethodBase originalMethod = GetOriginalMethod(containerAttributes.Merge(new HarmonyMethod(item)));
				instance.CreateReversePatcher(originalMethod, item).Patch();
			}
			IEnumerable<MethodBase> enumerable = RunMethod<HarmonyTargetMethods, IEnumerable<MethodBase>>(null, new object[0]);
			if (enumerable != null)
			{
				originals.Clear();
				originals.AddRange(enumerable);
			}
			else if (container.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == typeof(HarmonyPatchAll).FullName))
			{
				Type declaringType = containerAttributes.declaringType;
				originals.AddRange(AccessTools.GetDeclaredConstructors(declaringType).Cast<MethodBase>());
				originals.AddRange(AccessTools.GetDeclaredMethods(declaringType).Cast<MethodBase>());
				List<PropertyInfo> declaredProperties = AccessTools.GetDeclaredProperties(declaringType);
				originals.AddRange((from prop in declaredProperties
					select prop.GetGetMethod(nonPublic: true) into method
					where (object)method != null
					select method).Cast<MethodBase>());
				originals.AddRange((from prop in declaredProperties
					select prop.GetSetMethod(nonPublic: true) into method
					where (object)method != null
					select method).Cast<MethodBase>());
			}
			else
			{
				MethodBase methodBase = RunMethod<HarmonyTargetMethod, MethodBase>(null, new object[0]) ?? GetOriginalMethod(containerAttributes);
				if ((object)methodBase == null)
				{
					string text = "(";
					text += $"declaringType={containerAttributes.declaringType}, ";
					text = text + "methodName =" + containerAttributes.methodName + ", ";
					text += $"methodType={methodType}, ";
					text = text + "argumentTypes=" + containerAttributes.argumentTypes.Description();
					text += ")";
					throw new ArgumentException("No target method specified for class " + container.FullName + " " + text);
				}
				originals.Add(methodBase);
			}
			GetPatches(container, out var methodInfo, out var methodInfo2, out var methodInfo3, out var methodInfo4);
			if (prefix != null)
			{
				prefix.method = methodInfo;
			}
			if (postfix != null)
			{
				postfix.method = methodInfo2;
			}
			if (transpiler != null)
			{
				transpiler.method = methodInfo3;
			}
			if (finalizer != null)
			{
				finalizer.method = methodInfo4;
			}
			if ((object)methodInfo != null)
			{
				if (!methodInfo.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(methodInfo);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod)).CopyTo(prefix);
			}
			if ((object)methodInfo2 != null)
			{
				if (!methodInfo2.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo2, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod2 = HarmonyMethodExtensions.GetFromMethod(methodInfo2);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod2)).CopyTo(postfix);
			}
			if ((object)methodInfo3 != null)
			{
				if (!methodInfo3.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo3, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod3 = HarmonyMethodExtensions.GetFromMethod(methodInfo3);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod3)).CopyTo(transpiler);
			}
			if ((object)methodInfo4 != null)
			{
				if (!methodInfo4.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo4, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod4 = HarmonyMethodExtensions.GetFromMethod(methodInfo4);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod4)).CopyTo(finalizer);
			}
		}

		internal static MethodBase GetOriginalMethod(HarmonyMethod attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			if ((object)attribute.declaringType == null)
			{
				return MakeFailure("declaringType cannot be null");
			}
			switch (attribute.methodType)
			{
			case MethodType.Normal:
			{
				if (string.IsNullOrEmpty(attribute.methodName))
				{
					return MakeFailure("methodName can't be empty");
				}
				if (attribute.methodName == ".ctor")
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.Constructor should be used instead of setting methodName to .ctor");
					goto case MethodType.Constructor;
				}
				if (attribute.methodName == ".cctor")
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.StaticConstructor should be used instead of setting methodName to .cctor");
					goto case MethodType.StaticConstructor;
				}
				if (attribute.methodName.StartsWith("get_") || attribute.methodName.StartsWith("set_"))
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.Getter and MethodType.Setter should be used instead adding get_ and set_ to property names");
				}
				MethodInfo methodInfo = AccessTools.DeclaredMethod(attribute.declaringType, attribute.methodName, attribute.argumentTypes);
				if ((object)methodInfo != null)
				{
					return methodInfo;
				}
				methodInfo = AccessTools.Method(attribute.declaringType, attribute.methodName, attribute.argumentTypes);
				if ((object)methodInfo != null)
				{
					string text = GetPatchName();
					object[] obj = new object[4] { attribute.methodName, null, null, null };
					Type[] argumentTypes = attribute.argumentTypes;
					obj[1] = ((argumentTypes != null) ? argumentTypes.Length : 0);
					obj[2] = attribute.declaringType.FullDescription();
					obj[3] = methodInfo.DeclaringType.FullDescription();
					Logger.LogText(Logger.LogChannel.Warn, text + string.Format(" - Could not find method {0} with {1} parameters in type {2}, but it was found in base class of this type {3}", obj));
					return methodInfo;
				}
				return MakeFailure("Could not find method " + attribute.methodName + " with " + attribute.argumentTypes.Description() + " parameters in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.Getter:
			{
				if (string.IsNullOrEmpty(attribute.methodName))
				{
					return MakeFailure("methodName can't be empty");
				}
				PropertyInfo propertyInfo2 = AccessTools.DeclaredProperty(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo2 != null)
				{
					MethodInfo getMethod = propertyInfo2.GetGetMethod(nonPublic: true);
					if ((object)getMethod == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Getter");
					}
					return getMethod;
				}
				propertyInfo2 = AccessTools.Property(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo2 != null)
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription() + ", but it was found in base class of this type: " + propertyInfo2.DeclaringType.FullDescription());
					MethodInfo getMethod2 = propertyInfo2.GetGetMethod(nonPublic: true);
					if ((object)getMethod2 == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Getter");
					}
					return getMethod2;
				}
				return MakeFailure("Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.Setter:
			{
				if (string.IsNullOrEmpty(attribute.methodName))
				{
					return MakeFailure("methodName can't be empty");
				}
				PropertyInfo propertyInfo = AccessTools.DeclaredProperty(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo != null)
				{
					MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
					if ((object)setMethod == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Setter");
					}
					return setMethod;
				}
				propertyInfo = AccessTools.Property(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo != null)
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription() + ", but it was found in base class of this type: " + propertyInfo.DeclaringType.FullDescription());
					MethodInfo setMethod2 = propertyInfo.GetSetMethod(nonPublic: true);
					if ((object)setMethod2 == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Setter");
					}
					return setMethod2;
				}
				return MakeFailure("Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.Constructor:
			{
				ConstructorInfo constructorInfo2 = AccessTools.DeclaredConstructor(attribute.declaringType, attribute.argumentTypes);
				if ((object)constructorInfo2 != null)
				{
					return constructorInfo2;
				}
				return MakeFailure("Could not find constructor with " + attribute.argumentTypes.Description() + " parameters in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.StaticConstructor:
			{
				ConstructorInfo constructorInfo = AccessTools.GetDeclaredConstructors(attribute.declaringType).FirstOrDefault((ConstructorInfo c) => c.IsStatic);
				if ((object)constructorInfo != null)
				{
					return constructorInfo;
				}
				return MakeFailure("Could not find static constructor in type " + attribute.declaringType.FullDescription());
			}
			default:
				throw new ArgumentOutOfRangeException("methodType", attribute.methodType, "Unknown method type");
			}
			string GetPatchName()
			{
				return attribute.method?.FullDescription() ?? "Unknown patch";
			}
			MethodBase MakeFailure(string reason)
			{
				Logger.Log(Logger.LogChannel.Error, () => "Failed to process patch " + GetPatchName() + " - " + reason);
				return null;
			}
		}

		private T RunMethod<S, T>(T defaultIfNotExisting, params object[] parameters)
		{
			if ((object)container == null)
			{
				return defaultIfNotExisting;
			}
			string name = typeof(S).Name.Replace("Harmony", "");
			MethodInfo patchMethod = GetPatchMethod<S>(container, name);
			if ((object)patchMethod != null)
			{
				if (typeof(T).IsAssignableFrom(patchMethod.ReturnType))
				{
					object[] emptyTypes = Type.EmptyTypes;
					return (T)patchMethod.Invoke(null, emptyTypes);
				}
				object[] inputs = (parameters ?? new object[0]).Union(new object[1] { instance }).ToArray();
				object[] parameters2 = AccessTools.ActualParameters(patchMethod, inputs);
				patchMethod.Invoke(null, parameters2);
				return defaultIfNotExisting;
			}
			return defaultIfNotExisting;
		}

		private void RunMethod<S>(params object[] parameters)
		{
			if ((object)container != null)
			{
				string name = typeof(S).Name.Replace("Harmony", "");
				MethodInfo patchMethod = GetPatchMethod<S>(container, name);
				if ((object)patchMethod != null)
				{
					object[] inputs = (parameters ?? new object[0]).Union(new object[1] { instance }).ToArray();
					object[] parameters2 = AccessTools.ActualParameters(patchMethod, inputs);
					patchMethod.Invoke(null, parameters2);
				}
			}
		}

		private MethodInfo GetPatchMethod<T>(Type patchType, string name)
		{
			string attributeType = typeof(T).FullName;
			MethodInfo methodInfo = patchType.GetMethods(AccessTools.all).FirstOrDefault((MethodInfo m) => m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == attributeType));
			if ((object)methodInfo == null)
			{
				methodInfo = patchType.GetMethod(name, AccessTools.all);
			}
			return methodInfo;
		}

		private void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler, out MethodInfo finalizer)
		{
			prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix");
			postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix");
			transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler");
			finalizer = GetPatchMethod<HarmonyFinalizer>(patchType, "Finalizer");
		}
	}
	public class ReversePatcher
	{
		private readonly Harmony instance;

		private readonly MethodBase original;

		private readonly MethodInfo standin;

		private readonly ILHook ilHook;

		public ReversePatcher(Harmony instance, MethodBase original, MethodInfo standin)
		{
			//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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			this.instance = instance;
			this.original = original;
			this.standin = standin;
			ilHook = new ILHook((MethodBase)standin, new Manipulator(ApplyReversePatch), new ILHookConfig
			{
				ManualApply = true
			});
		}

		private void ApplyReversePatch(ILContext ctx)
		{
			//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_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			DynamicMethodDefinition val = new DynamicMethodDefinition(original);
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body);
			ctx.Body.Variables.Clear();
			Enumerator<VariableDefinition> enumerator = val.Definition.Body.Variables.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					VariableDefinition current = enumerator.Current;
					ctx.Body.Variables.Add(new VariableDefinition(ctx.Module.ImportReference(((VariableReference)current).VariableType)));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodInfo transpiler = GetTranspiler(standin);
			if ((object)transpiler != null)
			{
				iLManipulator.AddTranspiler(transpiler);
			}
			iLManipulator.WriteTo(ctx.Body, standin);
			ctx.IL.Emit(OpCodes.Ret);
		}

		public void Patch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
		{
			if ((object)original == null)
			{
				throw new NullReferenceException("Null method for " + instance.Id);
			}
			ilHook.Apply();
		}

		private MethodInfo GetTranspiler(MethodInfo method)
		{
			string methodName = method.Name;
			List<MethodInfo> declaredMethods = AccessTools.GetDeclaredMethods(method.DeclaringType);
			Type ici = typeof(IEnumerable<CodeInstruction>);
			return declaredMethods.FirstOrDefault((MethodInfo m) => (object)m.ReturnType == ici && m.Name.StartsWith("<" + methodName + ">"));
		}
	}
	public class CodeMatch
	{
		public string name;

		public List<OpCode> opcodes = new List<OpCode>();

		public List<object> operands = new List<object>();

		public List<Label> labels = new List<Label>();

		public List<ExceptionBlock> blocks = new List<ExceptionBlock>();

		public List<int> jumpsFrom = new List<int>();

		public List<int> jumpsTo = new List<int>();

		public Func<CodeInstruction, bool> predicate;

		public CodeMatch(OpCode? opcode = null, object operand = null, string name = null)
		{
			if (opcode.HasValue)
			{
				OpCode valueOrDefault = opcode.GetValueOrDefault();
				opcodes.Add(valueOrDefault);
			}
			if (operand != null)
			{
				operands.Add(operand);
			}
			this.name = name;
		}

		public CodeMatch(CodeInstruction instruction, string name = null)
			: this(instruction.opcode, instruction.operand, name)
		{
		}

		public CodeMatch(Func<CodeInstruction, bool> predicate, string name = null)
		{
			this.predicate = predicate;
			this.name = name;
		}

		internal bool Matches(List<CodeInstruction> codes, CodeInstruction instruction)
		{
			if (predicate != null)
			{
				return predicate(instruction);
			}
			if (opcodes.Count > 0 && !opcodes.Contains(instruction.opcode))
			{
				return false;
			}
			if (operands.Count > 0 && !operands.Contains(instruction.operand))
			{
				return false;
			}
			if (labels.Count > 0 && !labels.Intersect(instruction.labels).Any())
			{
				return false;
			}
			if (blocks.Count > 0 && !blocks.Intersect(instruction.blocks).Any())
			{
				return false;
			}
			if (jumpsFrom.Count > 0 && !jumpsFrom.Select((int index) => codes[index].operand).OfType<Label>().Intersect(instruction.labels)
				.Any())
			{
				return false;
			}
			if (jumpsTo.Count > 0)
			{
				object operand = instruction.operand;
				if (operand == null || (object)operand.GetType() != typeof(Label))
				{
					return false;
				}
				Label label = (Label)operand;
				IEnumerable<int> second = from idx in Enumerable.Range(0, codes.Count)
					where codes[idx].labels.Contains(label)
					select idx;
				if (!jumpsTo.Intersect(second).Any())
				{
					return false;
				}
			}
			return true;
		}

		public override string ToString()
		{
			string text = "[";
			if (name != null)
			{
				text = text + name + ": ";
			}
			if (opcodes.Count > 0)
			{
				text = text + "opcodes=" + opcodes.Join() + " ";
			}
			if (operands.Count > 0)
			{
				text = text + "operands=" + operands.Join() + " ";
			}
			if (labels.Count > 0)
			{
				text = text + "labels=" + labels.Join() + " ";
			}
			if (blocks.Count > 0)
			{
				text = text + "blocks=" + blocks.Join() + " ";
			}
			if (jumpsFrom.Count > 0)
			{
				text = text + "jumpsFrom=" + jumpsFrom.Join() + " ";
			}
			if (jumpsTo.Count > 0)
			{
				text = text + "jumpsTo=" + jumpsTo.Join() + " ";
			}
			if (predicate != null)
			{
				text += "predicate=yes ";
			}
			return text.TrimEnd(new char[0]) + "]";
		}
	}
	public class CodeMatcher
	{
		private readonly ILGenerator generator;

		private readonly List<CodeInstruction> codes = new List<CodeInstruction>();

		private Dictionary<string, CodeInstruction> lastMatches = new Dictionary<string, CodeInstruction>();

		private string lastError;

		private bool lastUseEnd;

		private CodeMatch[] lastCodeMatches;

		public int Pos { get; private set; } = -1;


		public int Length => codes.Count;

		public bool IsValid
		{
			get
			{
				if (Pos >= 0)
				{
					return Pos < Length;
				}
				return false;
			}
		}

		public bool IsInvalid
		{
			get
			{
				if (Pos >= 0)
				{
					return Pos >= Length;
				}
				return true;
			}
		}

		public int Remaining => Length - Math.Max(0, Pos);

		public ref OpCode Opcode => ref codes[Pos].opcode;

		public ref object Operand => ref codes[Pos].operand;

		public ref List<Label> Labels => ref codes[Pos].labels;

		public ref List<ExceptionBlock> Blocks => ref codes[Pos].blocks;

		public CodeInstruction Instruction => codes[Pos];

		private void FixStart()
		{
			Pos = Math.Max(0, Pos);
		}

		private void SetOutOfBounds(int direction)
		{
			Pos = ((direction > 0) ? Length : (-1));
		}

		public CodeMatcher()
		{
		}

		public CodeMatcher(IEnumerable<CodeInstruction> instructions, ILGenerator generator = null)
		{
			this.generator = generator;
			codes = instructions.Select((CodeInstruction c) => new CodeInstruction(c)).ToList();
		}

		public CodeMatcher Clone()
		{
			return new CodeMatcher(codes, generator)
			{
				Pos = Pos,
				lastMatches = lastMatches,
				lastError = lastError,
				lastUseEnd = lastUseEnd,
				lastCodeMatches = lastCodeMatches
			};
		}

		public CodeInstruction InstructionAt(int offset)
		{
			return codes[Pos + offset];
		}

		public List<CodeInstruction> Instructions()
		{
			return codes;
		}

		public IEnumerable<CodeInstruction> InstructionEnumeration()
		{
			return codes.AsEnumerable();
		}

		public List<CodeInstruction> Instructions(int count)
		{
			return (from c in codes.GetRange(Pos, count)
				select new CodeInstruction(c)).ToList();
		}

		public List<CodeInstruction> InstructionsInRange(int start, int end)
		{
			List<CodeInstruction> list = codes;
			if (start > end)
			{
				int num = start;
				start = end;
				end = num;
			}
			return (from c in list.GetRange(start, end - start + 1)
				select new CodeInstruction(c)).ToList();
		}

		public List<CodeInstruction> InstructionsWithOffsets(int startOffset, int endOffset)
		{
			return InstructionsInRange(Pos + startOffset, Pos + endOffset);
		}

		public List<Label> DistinctLabels(IEnumerable<CodeInstruction> instructions)
		{
			return instructions.SelectMany((CodeInstruction instruction) => instruction.labels).Distinct().ToList();
		}

		public bool ReportFailure(MethodBase method, Action<string> logger)
		{
			if (IsValid)
			{
				return false;
			}
			string arg = lastError ?? "Unexpected code";
			logger($"{arg} in {method}");
			return true;
		}

		public CodeMatcher SetInstruction(CodeInstruction instruction)
		{
			codes[Pos] = instruction;
			return this;
		}

		public CodeMatcher SetInstructionAndAdvance(CodeInstruction instruction)
		{
			SetInstruction(instruction);
			Pos++;
			return this;
		}

		public CodeMatcher Set(OpCode opcode, object operand)
		{
			Opcode = opcode;
			Operand = operand;
			return this;
		}

		public CodeMatcher SetAndAdvance(OpCode opcode, object operand)
		{
			Set(opcode, operand);
			Pos++;
			return this;
		}

		public CodeMatcher SetOpcodeAndAdvance(OpCode opcode)
		{
			Opcode = opcode;
			Pos++;
			return this;
		}

		public CodeMatcher SetOperandAndAdvance(object operand)
		{
			Operand = operand;
			Pos++;
			return this;
		}

		public CodeMatcher CreateLabel(out Label label)
		{
			label = generator.DefineLabel();
			Labels.Add(label);
			return this;
		}

		public CodeMatcher CreateLabelAt(int position, out Label label)
		{
			label = generator.DefineLabel();
			AddLabelsAt(position, new Label[1] { label });
			return this;
		}

		public CodeMatcher AddLabels(IEnumerable<Label> labels)
		{
			Labels.AddRange(labels);
			return this;
		}

		public CodeMatcher AddLabelsAt(int position, IEnumerable<Label> labels)
		{
			codes[position].labels.AddRange(labels);
			return this;
		}

		public CodeMatcher SetJumpTo(OpCode opcode, int destination, out Label label)
		{
			CreateLabelAt(destination, out label);
			Set(opcode, label);
			return this;
		}

		public CodeMatcher Insert(params CodeInstruction[] instructions)
		{
			codes.InsertRange(Pos, instructions);
			return this;
		}

		public CodeMatcher Insert(IEnumerable<CodeInstruction> instructions)
		{
			codes.InsertRange(Pos, instructions);
			return this;
		}

		public CodeMatcher InsertBranch(OpCode opcode, int destination)
		{
			CreateLabelAt(destination, out var label);
			codes.Insert(Pos, new CodeInstruction(opcode, label));
			return this;
		}

		public CodeMatcher InsertAndAdvance(params CodeInstruction[] instructions)
		{
			foreach (CodeInstruction codeInstruction in instructions)
			{
				Insert(codeInstruction);
				Pos++;
			}
			return this;
		}

		public CodeMatcher InsertAndAdvance(IEnumerable<CodeInstruction> instructions)
		{
			foreach (CodeInstruction instruction in instructions)
			{
				InsertAndAdvance(instruction);
			}
			return this;
		}

		public CodeMatcher InsertBranchAndAdvance(OpCode opcode, int destination)
		{
			InsertBranch(opcode, destination);
			Pos++;
			return this;
		}

		public CodeMatcher RemoveInstruction()
		{
			codes.RemoveAt(Pos);
			return this;
		}

		public CodeMatcher RemoveInstructions(int count)
		{
			codes.RemoveRange(Pos, count);
			return this;
		}

		public CodeMatcher RemoveInstructionsInRange(int start, int end)
		{
			if (start > end)
			{
				int num = start;
				start = end;
				end = num;
			}
			codes.RemoveRange(start, end - start + 1);
			return this;
		}

		public CodeMatcher RemoveInstructionsWithOffsets(int startOffset, int endOffset)
		{
			RemoveInstructionsInRange(Pos + startOffset, Pos + endOffset);
			return this;
		}

		public CodeMatcher Advance(int offset)
		{
			Pos += offset;
			if (!IsValid)
			{
				SetOutOfBounds(offset);
			}
			return this;
		}

		public CodeMatcher Start()
		{
			Pos = 0;
			return this;
		}

		public CodeMatcher End()
		{
			Pos = Length - 1;
			return this;
		}

		public CodeMatcher SearchForward(Func<CodeInstruction, bool> predicate)
		{
			return Search(predicate, 1);
		}

		public CodeMatcher SearchBack(Func<CodeInstruction, bool> predicate)
		{
			return Search(predicate, -1);
		}

		private CodeMatcher Search(Func<CodeInstruction, bool> predicate, int direction)
		{
			FixStart();
			while (IsValid && !predicate(Instruction))
			{
				Pos += direction;
			}
			lastError = (IsInvalid ? $"Cannot find {predicate}" : null);
			return this;
		}

		public CodeMatcher MatchForward(bool useEnd, params CodeMatch[] matches)
		{
			return Match(matches, 1, useEnd);
		}

		public CodeMatcher MatchBack(bool useEnd, params CodeMatch[] matches)
		{
			return Match(matches, -1, useEnd);
		}

		private CodeMatcher Match(CodeMatch[] matches, int direction, bool useEnd)
		{
			FixStart();
			while (IsValid)
			{
				lastUseEnd = useEnd;
				lastCodeMatches = matches;
				if (MatchSequence(Pos, matches))
				{
					if (useEnd)
					{
						Pos += matches.Count() - 1;
					}
					break;
				}
				Pos += direction;
			}
			lastError = (IsInvalid ? ("Cannot find " + matches.Join()) : null);
			return this;
		}

		public CodeMatcher Repeat(Action<CodeMatcher> matchAction, Action<string> notFoundAction = null)
		{
			int num = 0;
			if (lastCodeMatches == null)
			{
				throw new InvalidOperationException("No previous Match operation - cannot repeat");
			}
			while (IsValid)
			{
				matchAction(this);
				MatchForward(lastUseEnd, lastCodeMatches);
				num++;
			}
			lastCodeMatches = null;
			if (num == 0)
			{
				notFoundAction?.Invoke(lastError);
			}
			return this;
		}

		public CodeInstruction NamedMatch(string name)
		{
			return lastMatches[name];
		}

		private bool MatchSequence(int start, CodeMatch[] matches)
		{
			if (start < 0)
			{
				return false;
			}
			lastMatches = new Dictionary<string, CodeInstruction>();
			foreach (CodeMatch codeMatch in matches)
			{
				if (start >= Length || !codeMatch.Matches(codes, codes[start]))
				{
					return false;
				}
				if (codeMatch.name != null)
				{
					lastMatches.Add(codeMatch.name, codes[start]);
				}
				start++;
			}
			return true;
		}
	}
	public static class CodeInstructionExtensions
	{
		private static readonly HashSet<OpCode> LoadVarCodes = new HashSet<OpCode>
		{
			OpCodes.Ldloc_0,
			OpCodes.Ldloc_1,
			OpCodes.Ldloc_2,
			OpCodes.Ldloc_3,
			OpCodes.Ldloc,
			OpCodes.Ldloca,
			OpCodes.Ldloc_S,
			OpCodes.Ldloca_S
		};

		private static readonly HashSet<OpCode> StoreVarCodes = new HashSet<OpCode>
		{
			OpCodes.Stloc_0,
			OpCodes.Stloc_1,
			OpCodes.Stloc_2,
			OpCodes.Stloc_3,
			OpCodes.Stloc,
			OpCodes.Stloc_S
		};

		private static readonly HashSet<OpCode> BranchCodes = new HashSet<OpCode>
		{
			OpCodes.Br_S,
			OpCodes.Brfalse_S,
			OpCodes.Brtrue_S,
			OpCodes.Beq_S,
			OpCodes.Bge_S,
			OpCodes.Bgt_S,
			OpCodes.Ble_S,
			OpCodes.Blt_S,
			OpCodes.Bne_Un_S,
			OpCodes.Bge_Un_S,
			OpCodes.Bgt_Un_S,
			OpCodes.Ble_Un_S,
			OpCodes.Blt_Un_S,
			OpCodes.Br,
			OpCodes.Brfalse,
			OpCodes.Brtrue,
			OpCodes.Beq,
			OpCodes.Bge,
			OpCodes.Bgt,
			OpCodes.Ble,
			OpCodes.Blt,
			OpCodes.Bne_Un,
			OpCodes.Bge_Un,
			OpCodes.Bgt_Un,
			OpCodes.Ble_Un,
			OpCodes.Blt_Un
		};

		private static readonly HashSet<OpCode> ConstantLoadingCodes = new HashSet<OpCode>
		{
			OpCodes.Ldc_I4_M1,
			OpCodes.Ldc_I4_0,
			OpCodes.Ldc_I4_1,
			OpCodes.Ldc_I4_2,
			OpCodes.Ldc_I4_3,
			OpCodes.Ldc_I4_4,
			OpCodes.Ldc_I4_5,
			OpCodes.Ldc_I4_6,
			OpCodes.Ldc_I4_7,
			OpCodes.Ldc_I4_8,
			OpCodes.Ldc_I4,
			OpCodes.Ldc_I4_S,
			OpCodes.Ldc_I8,
			OpCodes.Ldc_R4,
			OpCodes.Ldc_R8
		};

		public static bool OperandIs(this CodeInstruction code, object value)
		{
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			if (code.operand == null)
			{
				return false;
			}
			Type type = value.GetType();
			Type type2 = code.operand.GetType();
			if (AccessTools.IsInteger(type) && AccessTools.IsNumber(type2))
			{
				return Convert.ToInt64(code.operand) == Convert.ToInt64(value);
			}
			if (AccessTools.IsFloatingPoint(type) && AccessTools.IsNumber(type2))
			{
				return Convert.ToDouble(code.operand) == Convert.ToDouble(value);
			}
			return object.Equals(code.operand, value);
		}

		public static bool Is(this CodeInstruction code, OpCode opcode, object operand)
		{
			if (code.opcode == opcode)
			{
				return code.OperandIs(operand);
			}
			return false;
		}

		public static bool IsLdarg(this CodeInstruction code, int? n = null)
		{
			if ((!n.HasValue || n.Value == 0) && code.opcode == OpCodes.Ldarg_0)
			{
				return true;
			}
			if ((!n.HasValue || n.Value == 1) && code.opcode == OpCodes.Ldarg_1)
			{
				return true;
			}
			if ((!n.HasValue || n.Value == 2) && code.opcode == OpCodes.Ldarg_2)
			{
				return true;
			}
			if ((!n.HasValue || n.Value == 3) && code.opcode == OpCodes.Ldarg_3)
			{
				return true;
			}
			if (code.opcode == OpCodes.Ldarg && (!n.HasValue || n.Value == Convert.ToInt32(code.operand)))
			{
				return true;
			}
			if (code.opcode == OpCodes.Ldarg_S && (!n.HasValue || n.Value == Convert.ToInt32(code.operand)))
			{
				return true;
			}
			return false;
		}

		public static bool IsLdarga(this CodeInstruction code, int? n = null)
		{
			if (code.opcode != OpCodes.Ldarga && code.opcode != OpCodes.Ldarga_S)
			{
				return false;
			}
			if (n.HasValue)
			{
				return n.Value == Convert.ToInt32(code.operand);
			}
			return true;
		}

		public static bool IsStarg(this CodeInstruction code, int? n = null)
		{
			if (code.opcode != OpCodes.Starg && code.opcode != OpCodes.Starg_S)
			{
				return false;
			}
			if (n.HasValue)
			{
				return n.Value == Convert.ToInt32(code.operand);
			}
			return true;
		}

		public static bool IsLdloc(this CodeInstruction code, LocalBuilder variable = null)
		{
			if (!LoadVarCodes.Contains(code.opcode))
			{
				return false;
			}
			if (variable != null)
			{
				return object.Equals(variable, code.operand);
			}
			return true;
		}

		public static bool IsStloc(this CodeInstruction code, LocalBuilder variable = null)
		{
			if (!StoreVarCodes.Contains(code.opcode))
			{
				return false;
			}
			if (variable != null)
			{
				return object.Equals(variable, code.operand);
			}
			return true;
		}

		public static bool Branches(this CodeInstruction code, out Label? label)
		{
			if (BranchCodes.Contains(code.opcode))
			{
				label = (Label)code.operand;
				return true;
			}
			label = null;
			return false;
		}

		public static bool Calls(this CodeInstruction code, MethodInfo method)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			if (code.opcode != OpCodes.Call && code.opcode != OpCodes.Callvirt)
			{
				return false;
			}
			return object.Equals(code.operand, method);
		}

		public static bool LoadsConstant(this CodeInstruction code)
		{
			return ConstantLoadingCodes.Contains(code.opcode);
		}

		public static bool LoadsConstant(this CodeInstruction code, long number)
		{
			OpCode opcode = code.opcode;
			if (number == -1 && opcode == OpCodes.Ldc_I4_M1)
			{
				return true;
			}
			if (number == 0L && opcode == OpCodes.Ldc_I4_0)
			{
				return true;
			}
			if (number == 1 && opcode == OpCodes.Ldc_I4_1)
			{
				return true;
			}
			if (number == 2 && opcode == OpCodes.Ldc_I4_2)
			{
				return true;
			}
			if (number == 3 && opcode == OpCodes.Ldc_I4_3)
			{
				return true;
			}
			if (number == 4 && opcode == OpCodes.Ldc_I4_4)
			{
				return true;
			}
			if (number == 5 && opcode == OpCodes.Ldc_I4_5)
			{
				return true;
			}
			if (number == 6 && opcode == OpCodes.Ldc_I4_6)
			{
				return true;
			}
			if (number == 7 && opcode == OpCodes.Ldc_I4_7)
			{
				return true;
			}
			if (number == 8 && opcode == OpCodes.Ldc_I4_8)
			{
				return true;
			}
			if (opcode != OpCodes.Ldc_I4 && opcode != OpCodes.Ldc_I4_S && opcode != OpCodes.Ldc_I8)
			{
				return false;
			}
			return Convert.ToInt64(code.operand) == number;
		}

		public static bool LoadsConstant(this CodeInstruction code, double number)
		{
			if (code.opcode != OpCodes.Ldc_R4 && code.opcode != OpCodes.Ldc_R8)
			{
				return false;
			}
			return Convert.ToDouble(code.operand) == number;
		}

		public static bool LoadsConstant(this CodeInstruction code, Enum e)
		{
			return code.LoadsConstant(Convert.ToInt64(e));
		}

		public static bool LoadsField(this CodeInstruction code, FieldInfo field, bool byAddress = false)
		{
			if ((object)field == null)
			{
				throw new ArgumentNullException("field");
			}
			OpCode opCode = (field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld);
			if (!byAddress && code.opcode == opCode && object.Equals(code.operand, field))
			{
				return true;
			}
			OpCode opCode2 = (field.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda);
			if (byAddress && code.opcode == opCode2 && object.Equals(code.operand, field))
			{
				return true;
			}
			return false;
		}

		public static bool StoresField(this CodeInstruction code, FieldInfo field)
		{
			if ((object)field == null)
			{
				throw new ArgumentNullException("field");
			}
			OpCode opCode = (field.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld);
			if (code.opcode == opCode)
			{
				return object.Equals(code.operand, field);
			}
			return false;
		}

		public static CodeInstruction WithLabels(this CodeInstruction code, params Label[] labels)
		{
			code.labels.AddRange(labels);
			return code;
		}

		public static CodeInstruction WithLabels(this CodeInstruction code, IEnumerable<Label> labels)
		{
			code.labels.AddRange(labels);
			return code;
		}

		public static List<Label> ExtractLabels(this CodeInstruction code)
		{
			List<Label> result = new List<Label>(code.labels);
			code.labels.Clear();
			return result;
		}

		public static CodeInstruction MoveLabelsTo(this CodeInstruction code, CodeInstruction other)
		{
			other.WithLabels(code.ExtractLabels());
			return code;
		}

		public static CodeInstruction MoveLabelsFrom(this CodeInstruction code, CodeInstruction other)
		{
			return code.WithLabels(other.ExtractLabels());
		}

		public static CodeInstruction WithBlocks(this CodeInstruction code, params ExceptionBlock[] blocks)
		{
			code.blocks.AddRange(blocks);
			return code;
		}

		public static CodeInstruction WithBlocks(this CodeInstruction code, IEnumerable<ExceptionBlock> blocks)
		{
			code.blocks.AddRange(blocks);
			return code;
		}

		public static List<ExceptionBlock> ExtractBlocks(this CodeInstruction code)
		{
			List<ExceptionBlock> result = new List<ExceptionBlock>(code.blocks);
			code.blocks.Clear();
			return result;
		}

		public static CodeInstruction MoveBlocksTo(this CodeInstruction code, CodeInstruction other)
		{
			other.WithBlocks(code.ExtractBlocks());
			return code;
		}

		public static CodeInstruction MoveBlocksFrom(this CodeInstruction code, CodeInstruction other)
		{
			return code.WithBlocks(other.ExtractBlocks());
		}
	}
	public static class CollectionExtensions
	{
		public static void Do<T>(this IEnumerable<T> sequence, Action<T> action)
		{
			if (sequence != null)
			{
				IEnumerator<T> enumerator = sequence.GetEnumerator();
				while (enumerator.MoveNext())
				{
					action(enumerator.Current);
				}
			}
		}

		public static void DoIf<T>(this IEnumerable<T> sequence, Func<T, bool> condition, Action<T> action)
		{
			sequence.Where(condition).Do(action);
		}

		public static IEnumerable<T> AddItem<T>(this IEnumerable<T> sequence, T item)
		{
			return (sequence ?? Enumerable.Empty<T>()).Concat(new T[1] { item });
		}

		public static T[] AddToArray<T>(this T[] sequence, T item)
		{
			return sequence.AddItem(item).ToArray();
		}

		public static T[] AddRangeToArray<T>(this T[] sequence, T[] items)
		{
			return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray();
		}
	}
	public static class GeneralExtensions
	{
		public static string Join<T>(this IEnumerable<T> enumeration, Func<T, string> converter = null, string delimiter = ", ")
		{
			if (converter == null)
			{
				converter = (T t) => t.ToString();
			}
			return enumeration.Aggregate("", (string prev, T curr) => prev + ((prev != "") ? delimiter : "") + converter(curr));
		}

		public static string Description(this Type[] parameters)
		{
			if (parameters == null)
			{
				return "NULL";
			}
			return "(" + parameters.Join((Type p) => p.FullDescription()) + ")";
		}

		public static string FullDescription(this Type type)
		{
			if ((object)type == null)
			{
				return "null";
			}
			string text = type.Namespace;
			if (!string.IsNullOrEmpty(text))
			{
				text += ".";
			}
			string text2 = text + type.Name;
			if (type.IsGenericType)
			{
				text2 += "<";
				Type[] genericArguments = type.GetGenericArguments();
				for (int i = 0; i < genericArguments.Length; i++)
				{
					if (!text2.EndsWith("<", StringComparison.Ordinal))
					{
						text2 += ", ";
					}
					text2 += genericArguments[i].FullDescription();
				}
				text2 += ">";
			}
			return text2;
		}

		public static string FullDescription(this MethodBase method)
		{
			if ((object)method == null)
			{
				return "null";
			}
			Type[] parameters = (from p in method.GetParameters()
				select p.ParameterType).ToArray();
			Type returnedType = AccessTools.GetReturnedType(method);
			return returnedType.FullDescription() + " " + method.DeclaringType.FullDescription() + "." + method.Name + parameters.Description();
		}

		public static Type[] Types(this ParameterInfo[] pinfo)
		{
			return pinfo.Select((ParameterInfo pi) => pi.ParameterType).ToArray();
		}

		public static T GetValueSafe<S, T>(this Dictionary<S, T> dictionary, S key)
		{
			if (dictionary.TryGetValue(key, out var value))
			{
				return value;
			}
			return default(T);
		}

		public static T GetTypedValue<T>(this Dictionary<string, object> dictionary, string key)
		{
			if (dictionary.TryGetValue(key, out var value) && value is T)
			{
				return (T)value;
			}
			return default(T);
		}
	}
	public static class SymbolExtensions
	{
		public static MethodInfo GetMethodInfo(Expression<Action> expression)
		{
			return GetMethodInfo((LambdaExpression)expression);
		}

		public static MethodInfo GetMethodInfo<T>(Expression<Action<T>> expression)
		{
			return GetMethodInfo((LambdaExpression)expression);
		}

		public static MethodInfo GetMethodInfo<T, TResult>(Expression<Func<T, TResult>> expression)
		{
			return GetMethodInfo((LambdaExpression)expression);
		}

		public static MethodInfo GetMethodInfo(LambdaExpression expression)
		{
			return ((expression.Body as MethodCallExpression) ?? throw new ArgumentException("Invalid Expression. Expression should consist of a Method call only.")).Method ?? throw new MemberNotFoundException($"Cannot find method for expression {expression}");
		}
	}
	[Obsolete("Use HarmonyFileLog instead", true)]
	public static class FileLog
	{
		public static string logPath;

		public static char indentChar;

		public static int indentLevel;

		private static List<string> buffer;

		static FileLog()
		{
			indentChar = '\t';
			buffer = new List<string>();
			logPath = $"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}{Path.DirectorySeparatorChar}harmony.log.txt";
		}

		private static string IndentString()
		{
			return new string(indentChar, indentLevel);
		}

		public static void ChangeIndent(int delta)
		{
			indentLevel = Math.Max(0, indentLevel + delta);
		}

		public static void LogBuffered(string str)
		{
			lock (logPath)
			{
				buffer.Add(IndentString() + str);
			}
		}

		public static void LogBuffered(List<string> strings)
		{
			lock (logPath)
			{
				buffer.AddRange(strings);
			}
		}

		public static List<string> GetBuffer(bool clear)
		{
			lock (logPath)
			{
				List<string> result = buffer;
				if (clear)
				{
					buffer = new List<string>();
				}
				return result;
			}
		}

		public static void SetBuffer(List<string> buffer)
		{
			lock (logPath)
			{
				FileLog.buffer = buffer;
			}
		}

		public static void FlushBuffer()
		{
			lock (logPath)
			{
				if (buffer.Count <= 0)
				{
					return;
				}
				using (StreamWriter streamWriter = File.AppendText(logPath))
				{
					foreach (string item in buffer)
					{
						streamWriter.WriteLine(item);
					}
				}
				buffer.Clear();
			}
		}

		public static void Log(string str)
		{
			lock (logPath)
			{
				using StreamWriter streamWriter = File.AppendText(logPath);
				streamWriter.WriteLine(IndentString() + str);
			}
		}

		public static void Reset()
		{
			lock (logPath)
			{
				File.Delete($"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}{Path.DirectorySeparatorChar}harmony.log.txt");
			}
		}

		public unsafe static void LogBytes(long ptr, int len)
		{
			lock (logPath)
			{
				byte* ptr2 = (byte*)ptr;
				string text = "";
				for (int i = 1; i <= len; i++)
				{
					if (text == "")
					{
						text = "#  ";
					}
					text = $"{text}{*ptr2:X2} ";
					if (i > 1 || len == 1)
					{
						if (i % 8 == 0 || i == len)
						{
							Log(text);
							text = "";
						}
						else if (i % 4 == 0)
						{
							text += " ";
						}
					}
					ptr2++;
				}
				byte[] destination = new byte[len];
				Marshal.Copy((IntPtr)ptr, destination, 0, len);
				byte[] array = MD5.Create().ComputeHash(destination);
				StringBuilder stringBuilder = new StringBuilder();
				for (int j = 0; j < array.Length; j++)
				{
					stringBuilder.Append(array[j].ToString("X2"));
				}
				Log($"HASH: {stringBuilder}");
			}
		}
	}
	public static class AccessTools
	{
		public delegate ref U FieldRef<T, U>(T obj = default(T));

		public delegate ref F FieldRef<F>();

		public static BindingFlags all = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty;

		public static BindingFlags allDeclared = all | BindingFlags.DeclaredOnly;

		private static readonly MethodInfo m_PrepForRemoting = Method(typeof(Exception), "PrepForRemoting") ?? Method(typeof(Exception), "FixRemotingException");

		private static readonly FastInvokeHandler PrepForRemoting = MethodInvoker.GetHandler(m_PrepForRemoting);

		public static bool IsMonoRuntime { get; } = (object)Type.GetType("Mono.Runtime") != null;


		public static Type TypeByName(string name)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			Type type = Type.GetType(name, throwOnError: false);
			if ((object)type == null)
			{
				type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
					select assembly.GetType(name)).FirstOrDefault((Type t) => (object)t != null);
			}
			if ((object)type == null)
			{
				type = AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly x) => x.GetTypes()).FirstOrDefault((Type x) => x.Name == name);
			}
			if ((object)type == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => "AccessTools.TypeByName: Could not find type named " + name);
			}
			return type;
		}

		public static T FindIncludingBaseTypes<T>(Type type, Func<Type, T> func) where T : class
		{
			while (true)
			{
				T val = func(type);
				if (val != null)
				{
					return val;
				}
				if ((object)type == typeof(object))
				{
					break;
				}
				type = type.BaseType;
			}
			return null;
		}

		public static T FindIncludingInnerTypes<T>(Type type, Func<Type, T> func) where T : class
		{
			T val = func(type);
			if (val != null)
			{
				return val;
			}
			Type[] nestedTypes = type.GetNestedTypes(all);
			for (int i = 0; i < nestedTypes.Length; i++)
			{
				val = FindIncludingInnerTypes(nestedTypes[i], func);
				if (val != null)
				{
					break;
				}
			}
			return val;
		}

		public static FieldInfo DeclaredField(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			FieldInfo? field = type.GetField(name, allDeclared);
			if ((object)field == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredField: Could not find field for type {type} and name {name}");
			}
			return field;
		}

		public static FieldInfo Field(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			FieldInfo? fieldInfo = FindIncludingBaseTypes(type, (Type t) => t.GetField(name, all));
			if ((object)fieldInfo == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Field: Could not find field for type {type} and name {name}");
			}
			return fieldInfo;
		}

		public static FieldInfo DeclaredField(Type type, int idx)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			FieldInfo? fieldInfo = GetDeclaredFields(type).ElementAtOrDefault(idx);
			if ((object)fieldInfo == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredField: Could not find field for type {type} and idx {idx}");
			}
			return fieldInfo;
		}

		public static PropertyInfo DeclaredProperty(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			try
			{
				PropertyInfo? property = type.GetProperty(name, allDeclared);
				if ((object)property == null)
				{
					Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredProperty: Could not find property for type {type} and name {name}");
				}
				return property;
			}
			catch (AmbiguousMatchException inner)
			{
				throw new AmbiguousMatchException($"Ambiguous match for property {type}::{name}", inner);
			}
		}

		public static MethodInfo DeclaredPropertyGetter(Type type, string name)
		{
			return DeclaredProperty(type, name)?.GetGetMethod(nonPublic: true);
		}

		public static MethodInfo DeclaredPropertySetter(Type type, string name)
		{
			return DeclaredProperty(type, name)?.GetSetMethod(nonPublic: true);
		}

		public static PropertyInfo Property(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			PropertyInfo? propertyInfo = FindIncludingBaseTypes(type, (Type t) => t.GetProperty(name, all));
			if ((object)propertyInfo == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Property: Could not find property for type {type} and name {name}");
			}
			return propertyInfo;
		}

		public static MethodInfo PropertyGetter(Type type, string name)
		{
			return Property(type, name)?.GetGetMethod(nonPublic: true);
		}

		public static MethodInfo PropertySetter(Type type, string name)
		{
			return Property(type, name)?.GetSetMethod(nonPublic: true);
		}

		public static MethodInfo DeclaredMethod(Type type, string name, Type[] parameters = null, Type[] generics = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			ParameterModifier[] modifiers = new ParameterModifier[0];
			try
			{
				MethodInfo methodInfo = ((parameters != null) ? type.GetMethod(name, allDeclared, null, parameters, modifiers) : type.GetMethod(name, allDeclared));
				if ((object)methodInfo == null)
				{
					Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredMethod: Could not find method for type {type} and name {name} and parameters {parameters?.Description()}");
					return null;
				}
				if (generics != null)
				{
					methodInfo = methodInfo.MakeGenericMethod(generics);
				}
				return methodInfo;
			}
			catch (AmbiguousMatchException inner)
			{
				string text = "";
				if (generics != null)
				{
					text = "<" + string.Join(", ", generics.Select((Type g) => g.FullName).ToArray()) + ">";
				}
				string text2 = "";
				if (parameters != null)
				{
					text2 = string.Join(", ", parameters.Select((Type p) => p.FullName).ToArray());
				}
				throw new AmbiguousMatchException($"Ambiguous match for {type}::{name}{text}(${text2})", inner);
			}
		}

		public static MethodInfo Method(Type type, string name, Type[] parameters = null, Type[] generics = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			try
			{
				ParameterModifier[] modifiers = new ParameterModifier[0];
				MethodInfo methodInfo;
				if (parameters == null)
				{
					try
					{
						methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all));
					}
					catch (AmbiguousMatchException inner)
					{
						methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all, null, new Type[0], modifiers));
						if ((object)methodInfo == null)
						{
							throw new AmbiguousMatchException($"Ambiguous match for {type}:{name}", inner);
						}
					}
				}
				else
				{
					methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all, null, parameters, modifiers));
				}
				if ((object)methodInfo == null)
				{
					Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Method: Could not find method for type {type} and name {name} and parameters {parameters?.Description()}");
					return null;
				}
				if (generics != null)
				{
					methodInfo = methodInfo.MakeGenericMethod(generics);
				}
				return methodInfo;
			}
			catch (AmbiguousMatchException inner2)
			{
				string text = "";
				if (generics != null)
				{
					text = "<" + string.Join(", ", generics.Select((Type g) => g.FullName).ToArray()) + ">";
				}
				string text2 = "";
				if (parameters != null)
				{
					text2 = string.Join(", ", parameters.Select((Type p) => p.FullName).ToArray());
				}
				throw new AmbiguousMatchException($"Ambiguous match for {type}::{name}{text}(${text2})", inner2);
			}
		}

		public static MethodInfo Method(string typeColonMethodname, Type[] parameters = null, Type[] generics = null)
		{
			if (typeColonMethodname == null)
			{
				throw new ArgumentNullException("typeColonMethodname");
			}
			string[] array = typeColonMethodname.Split(new char[1] { ':' });
			if (array.Length != 2)
			{
				throw new ArgumentException("Method must be specified as 'Namespace.Type1.Type2:MethodName", "typeColonMethodname");
			}
			return Method(TypeByName(array[0]), array[1], parameters, generics);
		}

		public static List<string> GetMethodNames(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from m in GetDeclaredMethods(type)
				select m.Name).ToList();
		}

		public static List<string> GetMethodNames(object instance)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			return GetMethodNames(instance.GetType());
		}

		public static List<string> GetFieldNames(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from f in GetDeclaredFields(type)
				select f.Name).ToList();
		}

		public static List<string> GetFieldNames(object instance)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			return GetFieldNames(instance.GetType());
		}

		public static List<string> GetPropertyNames(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from f in GetDeclaredProperties(type)
				select f.Name).ToList();
		}

		public static List<string> GetPropertyNames(object instance)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			return GetPropertyNames(instance.GetType());
		}

		public static Type GetUnderlyingType(this MemberInfo member)
		{
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			return member.MemberType switch
			{
				MemberTypes.Event => ((EventInfo)member).EventHandlerType, 
				MemberTypes.Field => ((FieldInfo)member).FieldType, 
				MemberTypes.Method => ((MethodInfo)member).ReturnType, 
				MemberTypes.Property => ((PropertyInfo)member).PropertyType, 
				_ => throw new ArgumentException("Member must be of type EventInfo, FieldInfo, MethodInfo, or PropertyInfo"), 
			};
		}

		public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			return type.GetConstructor(allDeclared, null, parameters, new ParameterModifier[0]);
		}

		public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters, bool searchForStatic)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			BindingFlags bindingFlags = (searchForStatic ? BindingFlags.Instance : BindingFlags.Static);
			return type.GetConstructor(allDeclared & ~bindingFlags, null, parameters, new ParameterModifier[0]);
		}

		public static ConstructorInfo Constructor(Type type, Type[] parameters = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			return FindIncludingBaseTypes(type, (Type t) => t.GetConstructor(all, null, parameters, new ParameterModifier[0]));
		}

		public static ConstructorInfo Constructor(Type type, Type[] parameters, bool searchForStatic)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			BindingFlags exclude = (searchForStatic ? BindingFlags.Instance : BindingFlags.Static);
			return FindIncludingBaseTypes(type, (Type t) => t.GetConstructor(all & ~exclude, null, parameters, new ParameterModifier[0]));
		}

		public static List<ConstructorInfo> GetDeclaredConstructors(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from method in type.GetConstructors(allDeclared)
				where (object)method.DeclaringType == type
				select method).ToList();
		}

		public static List<ConstructorInfo> GetDeclaredConstructors(Type type, bool? searchForStatic)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			BindingFlags bindingFlags = BindingFlags.Default;
			if (searchForStatic.HasValue)
			{
				bindingFlags = (searchForStatic.Value ? BindingFlags.Instance : BindingFlags.Static);
			}
			return (from method in type.GetConstructors(allDeclared & ~bindingFlags)
				where (object)method.DeclaringType == type
				select method).ToList();
		}

		public static List<MethodInfo> GetDeclaredMethods(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return type.GetMethods(allDeclared).ToList();
		}

		public static List<PropertyInfo> GetDeclaredProperties(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return type.GetProperties(allDeclared).ToList();
		}

		public static List<FieldInfo> GetDeclaredFields(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return type.GetFields(allDeclared).ToList();
		}

		public static Type GetReturnedType(MethodBase methodOrConstructor)
		{
			if ((object)methodOrConstructor == null)
			{
				throw new ArgumentNullException("methodOrConstructor");
			}
			if (methodOrConstructor is ConstructorInfo)
			{
				return typeof(void);
			}
			return ((MethodInfo)methodOrConstructor).ReturnType;
		}

		public static Type Inner(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			return FindIncludingBaseTypes(type, (Type t) => t.GetNestedType(name, all));
		}

		public static Type FirstInner(Type type, Func<Type, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetNestedTypes(all).FirstOrDefault(predicate);
		}

		public static MethodInfo FirstMethod(Type type, Func<MethodInfo, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetMethods(allDeclared).FirstOrDefault(predicate);
		}

		public static ConstructorInfo FirstConstructor(Type type, Func<ConstructorInfo, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetConstructors(allDeclared).FirstOrDefault(predicate);
		}

		public static PropertyInfo FirstProperty(Type type, Func<PropertyInfo, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetProperties(allDeclared).FirstOrDefault(predicate);
		}

		public static Type[] GetTypes(object[] parameters)
		{
			if (parameters == null)
			{
				return new Type[0];
			}
			return parameters.Select((object p) => (p != null) ? p.GetType() : typeof(object)).ToArray();
		}

		public static object[] ActualParameters(MethodBase method, object[] inputs)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			if (inputs == null)
			{
				throw new ArgumentNullException("inputs");
			}
			List<Type> inputTypes = inputs.Select((object obj) => obj?.GetType()).ToList();
			return (from p in method.GetParameters()
				select p.ParameterType).Select(delegate(Type pType)
			{
				int num = inputTypes.FindIndex((Type inType) => inputTypes != null && pType.IsAssignableFrom(inType));
				return (num >= 0) ? inputs[num] : GetDefaultValue(pType);
			}).ToArray();
		}

		public static FieldRef<T, U> FieldRefAccess<T, U>(string fieldName)
		{
			return FieldRefAccess<T, U>(typeof(T).GetField(fieldName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic));
		}

		public static FieldRef<T, U> FieldRefAccess<T, U>(FieldInfo fieldInfo)
		{
			//IL_00c6: 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)
			if ((object)fieldInfo == null)
			{
				throw new ArgumentNullException("fieldInfo");
			}
			if (!typeof(U).IsAssignableFrom(fieldInfo.FieldType))
			{
				throw new ArgumentException("FieldInfo type does not match FieldRefAccess return type.");
			}
			if ((object)typeof(T) != typeof(object) && ((object)fieldInfo.DeclaringType == null || !fieldInfo.DeclaringType.IsAssignableFrom(typeof(T))))
			{
				throw new MissingFieldException(typeof(T).Name, fieldInfo.Name);
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition("__refget_" + typeof(T).Name + "_fi_" + fieldInfo.Name, typeof(U).MakeByRefType(), new Type[1] { typeof(T) });
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldflda, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return Extensions.CreateDelegate<FieldRef<T, U>>((MethodBase)val.Generate());
		}

		public static ref U FieldRefAccess<T, U>(T instance, string fieldName)
		{
			return ref FieldRefAccess<T, U>(fieldName)(instance);
		}

		public static FieldRef<object, F> FieldRefAccess<F>(Type type, string fieldName)
		{
			return FieldRefAccess<object, F>(Field(type, fieldName));
		}

		public static ref F StaticFieldRefAccess<T, F>(string fieldName)
		{
			return ref StaticFieldRefAccess<F>(typeof(T), fieldName);
		}

		public static ref F StaticFieldRefAccess<T, F>(FieldInfo fieldInfo)
		{
			return ref StaticFieldRefAccess<F>(fieldInfo)();
		}

		public static FieldRef<F> StaticFieldRefAccess<F>(FieldInfo fieldInfo)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if ((object)fieldInfo == null)
			{
				throw new ArgumentNullException("fieldInfo");
			}
			Type declaringType = fieldInfo.DeclaringType;
			DynamicMethodDefinition val = new DynamicMethodDefinition("__refget_" + declaringType.Name + "_static_fi_" + fieldInfo.Name, typeof(F).MakeByRefType(), new Type[0]);
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldsflda, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return Extensions.CreateDelegate<FieldRef<F>>((MethodBase)val.Generate());
		}

		public static ref F StaticFieldRefAccess<F>(Type type, string fieldName)
		{
			return ref StaticFieldRefAccess<F>(type.GetField(fieldName, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic))();
		}

		public static MethodBase GetOutsideCaller()
		{
			StackFrame[] frames = new StackTrace(fNeedFileInfo: true).GetFrames();
			for (int i = 0; i < frames.Length; i++)
			{
				Met

BooBoo Building/BepInEx/core/BepInEx.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.ConsoleUtil;
using BepInEx.Logging;
using BepInEx.Unix;
using HarmonyLib;
using HarmonyLib.Tools;
using Microsoft.Win32.SafeHandles;
using Mono.Cecil;
using MonoMod.Utils;
using UnityEngine;
using UnityInjector.ConsoleUtil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("BepInEx")]
[assembly: AssemblyDescription("Unity plugin injection framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BepInEx")]
[assembly: AssemblyCopyright("Copyright © Bepis 2018")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4ffba620-f5ed-47f9-b90c-dad1316fd9b9")]
[assembly: InternalsVisibleTo("BepInEx.Preloader")]
[assembly: InternalsVisibleTo("BepInExTests")]
[assembly: AssemblyFileVersion("5.4.21.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("5.4.21.0")]
[module: UnverifiableCode]
namespace UnityEngine
{
	internal sealed class UnityLogWriter
	{
		[MethodImpl(MethodImplOptions.InternalCall)]
		public static extern void WriteStringToUnityLogImpl(string s);

		[MethodImpl(MethodImplOptions.InternalCall)]
		public static extern void WriteStringToUnityLog(string s);
	}
}
namespace UnityInjector.ConsoleUtil
{
	internal class ConsoleEncoding : Encoding
	{
		private byte[] _byteBuffer = new byte[256];

		private char[] _charBuffer = new char[256];

		private byte[] _zeroByte = new byte[0];

		private char[] _zeroChar = new char[0];

		private readonly uint _codePage;

		public override int CodePage => (int)_codePage;

		public static Encoding OutputEncoding => new ConsoleEncoding(ConsoleCodePage);

		public static uint ConsoleCodePage
		{
			get
			{
				return GetConsoleOutputCP();
			}
			set
			{
				SetConsoleOutputCP(value);
			}
		}

		private void ExpandByteBuffer(int count)
		{
			if (_byteBuffer.Length < count)
			{
				_byteBuffer = new byte[count];
			}
		}

		private void ExpandCharBuffer(int count)
		{
			if (_charBuffer.Length < count)
			{
				_charBuffer = new char[count];
			}
		}

		private void ReadByteBuffer(byte[] bytes, int index, int count)
		{
			for (int i = 0; i < count; i++)
			{
				bytes[index + i] = _byteBuffer[i];
			}
		}

		private void ReadCharBuffer(char[] chars, int index, int count)
		{
			for (int i = 0; i < count; i++)
			{
				chars[index + i] = _charBuffer[i];
			}
		}

		private void WriteByteBuffer(byte[] bytes, int index, int count)
		{
			ExpandByteBuffer(count);
			for (int i = 0; i < count; i++)
			{
				_byteBuffer[i] = bytes[index + i];
			}
		}

		private void WriteCharBuffer(char[] chars, int index, int count)
		{
			ExpandCharBuffer(count);
			for (int i = 0; i < count; i++)
			{
				_charBuffer[i] = chars[index + i];
			}
		}

		public static uint GetActiveCodePage()
		{
			return GetACP();
		}

		private ConsoleEncoding(uint codePage)
		{
			_codePage = codePage;
		}

		public static ConsoleEncoding GetEncoding(uint codePage)
		{
			return new ConsoleEncoding(codePage);
		}

		public override int GetByteCount(char[] chars, int index, int count)
		{
			WriteCharBuffer(chars, index, count);
			return WideCharToMultiByte(_codePage, 0u, _charBuffer, count, _zeroByte, 0, IntPtr.Zero, IntPtr.Zero);
		}

		public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
		{
			int byteCount = GetByteCount(chars, charIndex, charCount);
			WriteCharBuffer(chars, charIndex, charCount);
			ExpandByteBuffer(byteCount);
			int result = WideCharToMultiByte(_codePage, 0u, chars, charCount, _byteBuffer, byteCount, IntPtr.Zero, IntPtr.Zero);
			ReadByteBuffer(bytes, byteIndex, byteCount);
			return result;
		}

		public override int GetCharCount(byte[] bytes, int index, int count)
		{
			WriteByteBuffer(bytes, index, count);
			return MultiByteToWideChar(_codePage, 0u, bytes, count, _zeroChar, 0);
		}

		public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
		{
			int charCount = GetCharCount(bytes, byteIndex, byteCount);
			WriteByteBuffer(bytes, byteIndex, byteCount);
			ExpandCharBuffer(charCount);
			int result = MultiByteToWideChar(_codePage, 0u, bytes, byteCount, _charBuffer, charCount);
			ReadCharBuffer(chars, charIndex, charCount);
			return result;
		}

		public override int GetMaxByteCount(int charCount)
		{
			return charCount * 2;
		}

		public override int GetMaxCharCount(int byteCount)
		{
			return byteCount;
		}

		[DllImport("kernel32.dll")]
		private static extern uint GetConsoleOutputCP();

		[DllImport("kernel32.dll")]
		private static extern uint GetACP();

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern int MultiByteToWideChar(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, [Out][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar);

		[DllImport("kernel32.dll")]
		private static extern IntPtr SetConsoleOutputCP(uint codepage);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern int WideCharToMultiByte(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar);
	}
	internal class ConsoleWindow
	{
		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private delegate bool SetForegroundWindowDelegate(IntPtr hWnd);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		private delegate IntPtr GetForegroundWindowDelegate();

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		private delegate IntPtr GetSystemMenuDelegate(IntPtr hwnd, bool bRevert);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		private delegate bool DeleteMenuDelegate(IntPtr hMenu, uint uPosition, uint uFlags);

		private const uint SC_CLOSE = 61536u;

		private const uint MF_BYCOMMAND = 0u;

		private const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 2048u;

		public static IntPtr ConsoleOutHandle;

		public static IntPtr OriginalStdoutHandle;

		private static bool methodsInited;

		private static SetForegroundWindowDelegate setForeground;

		private static GetForegroundWindowDelegate getForeground;

		private static GetSystemMenuDelegate getSystemMenu;

		private static DeleteMenuDelegate deleteMenu;

		public static bool IsAttached { get; private set; }

		public static string Title
		{
			set
			{
				if (IsAttached)
				{
					if (value == null)
					{
						throw new ArgumentNullException("value");
					}
					if (value.Length > 24500)
					{
						throw new InvalidOperationException("Console title too long");
					}
					if (!SetConsoleTitle(value))
					{
						throw new InvalidOperationException("Console title invalid");
					}
				}
			}
		}

		public static void Attach()
		{
			if (!IsAttached)
			{
				Initialize();
				if (OriginalStdoutHandle == IntPtr.Zero)
				{
					OriginalStdoutHandle = GetStdHandle(-11);
				}
				IntPtr hWnd = getForeground();
				GetConsoleWindow();
				if (GetConsoleWindow() == IntPtr.Zero && !AllocConsole())
				{
					throw new Exception("AllocConsole() failed");
				}
				setForeground(hWnd);
				ConsoleOutHandle = CreateFile("CONOUT$", 3221225472u, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
				Kon.conOut = ConsoleOutHandle;
				if (!SetStdHandle(-11, ConsoleOutHandle))
				{
					throw new Exception("SetStdHandle() failed");
				}
				if (OriginalStdoutHandle != IntPtr.Zero && ConsoleManager.ConfigConsoleOutRedirectType.Value == ConsoleManager.ConsoleOutRedirectType.ConsoleOut)
				{
					CloseHandle(OriginalStdoutHandle);
				}
				IsAttached = true;
			}
		}

		public static void PreventClose()
		{
			if (IsAttached)
			{
				Initialize();
				IntPtr consoleWindow = GetConsoleWindow();
				IntPtr intPtr = getSystemMenu(consoleWindow, bRevert: false);
				if (intPtr != IntPtr.Zero)
				{
					deleteMenu(intPtr, 61536u, 0u);
				}
			}
		}

		public static void Detach()
		{
			if (IsAttached)
			{
				if (!CloseHandle(ConsoleOutHandle))
				{
					throw new Exception("CloseHandle() failed");
				}
				ConsoleOutHandle = IntPtr.Zero;
				if (!FreeConsole())
				{
					throw new Exception("FreeConsole() failed");
				}
				if (!SetStdHandle(-11, OriginalStdoutHandle))
				{
					throw new Exception("SetStdHandle() failed");
				}
				IsAttached = false;
			}
		}

		private static void Initialize()
		{
			if (!methodsInited)
			{
				methodsInited = true;
				IntPtr hModule = LoadLibraryEx("user32.dll", IntPtr.Zero, 2048u);
				setForeground = DynDll.AsDelegate<SetForegroundWindowDelegate>(GetProcAddress(hModule, "SetForegroundWindow"));
				getForeground = DynDll.AsDelegate<GetForegroundWindowDelegate>(GetProcAddress(hModule, "GetForegroundWindow"));
				getSystemMenu = DynDll.AsDelegate<GetSystemMenuDelegate>(GetProcAddress(hModule, "GetSystemMenu"));
				deleteMenu = DynDll.AsDelegate<DeleteMenuDelegate>(GetProcAddress(hModule, "DeleteMenu"));
			}
		}

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool AllocConsole();

		[DllImport("kernel32.dll")]
		private static extern IntPtr GetConsoleWindow();

		[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
		private static extern bool CloseHandle(IntPtr handle);

		[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		private static extern IntPtr CreateFile(string fileName, uint desiredAccess, int shareMode, IntPtr securityAttributes, int creationDisposition, int flagsAndAttributes, IntPtr templateFile);

		[DllImport("kernel32.dll")]
		private static extern bool FreeConsole();

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr GetStdHandle(int nStdHandle);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool SetStdHandle(int nStdHandle, IntPtr hConsoleOutput);

		[DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Auto, SetLastError = true)]
		private static extern bool SetConsoleTitle(string title);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr LoadLibraryEx(string lpLibFileName, IntPtr hFile, uint dwFlags);
	}
	internal static class SafeConsole
	{
		private delegate ConsoleColor GetColorDelegate();

		private delegate void SetColorDelegate(ConsoleColor value);

		private delegate string GetStringDelegate();

		private delegate void SetStringDelegate(string value);

		private static GetColorDelegate _getBackgroundColor;

		private static SetColorDelegate _setBackgroundColor;

		private static GetColorDelegate _getForegroundColor;

		private static SetColorDelegate _setForegroundColor;

		private static GetStringDelegate _getTitle;

		private static SetStringDelegate _setTitle;

		public static bool BackgroundColorExists { get; private set; }

		public static ConsoleColor BackgroundColor
		{
			get
			{
				return _getBackgroundColor();
			}
			set
			{
				_setBackgroundColor(value);
			}
		}

		public static bool ForegroundColorExists { get; private set; }

		public static ConsoleColor ForegroundColor
		{
			get
			{
				return _getForegroundColor();
			}
			set
			{
				_setForegroundColor(value);
			}
		}

		public static bool TitleExists { get; private set; }

		public static string Title
		{
			get
			{
				return _getTitle();
			}
			set
			{
				_setTitle(value);
			}
		}

		static SafeConsole()
		{
			InitColors(typeof(Console));
		}

		private static void InitColors(Type tConsole)
		{
			MethodInfo method = tConsole.GetMethod("get_ForegroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method2 = tConsole.GetMethod("set_ForegroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method3 = tConsole.GetMethod("get_BackgroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method4 = tConsole.GetMethod("set_BackgroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method5 = tConsole.GetMethod("get_Title", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method6 = tConsole.GetMethod("set_Title", BindingFlags.Static | BindingFlags.Public);
			_setForegroundColor = (((object)method2 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method2)) : ((SetColorDelegate)delegate
			{
			}));
			_setBackgroundColor = (((object)method4 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method4)) : ((SetColorDelegate)delegate
			{
			}));
			_getForegroundColor = (((object)method != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method)) : ((GetColorDelegate)(() => ConsoleColor.Gray)));
			_getBackgroundColor = (((object)method3 != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method3)) : ((GetColorDelegate)(() => ConsoleColor.Black)));
			_getTitle = (((object)method5 != null) ? ((GetStringDelegate)Delegate.CreateDelegate(typeof(GetStringDelegate), method5)) : ((GetStringDelegate)(() => string.Empty)));
			_setTitle = (((object)method6 != null) ? ((SetStringDelegate)Delegate.CreateDelegate(typeof(SetStringDelegate), method6)) : ((SetStringDelegate)delegate
			{
			}));
			BackgroundColorExists = _setBackgroundColor != null && _getBackgroundColor != null;
			ForegroundColorExists = _setForegroundColor != null && _getForegroundColor != null;
			TitleExists = _setTitle != null && _getTitle != null;
		}
	}
}
namespace BepInEx
{
	public static class UnityInput
	{
		private static IInputSystem _current;

		public static IInputSystem Current
		{
			get
			{
				if (_current != null)
				{
					return _current;
				}
				try
				{
					try
					{
						Input.GetKeyDown((KeyCode)97);
						_current = new LegacyInputSystem();
						Logger.LogDebug("[UnityInput] Using LegacyInputSystem");
					}
					catch (InvalidOperationException)
					{
						_current = new NewInputSystem();
						Logger.LogDebug("[UnityInput] Using NewInputSystem");
					}
				}
				catch (Exception arg)
				{
					Logger.LogWarning($"[UnityInput] Failed to detect available input systems - {arg}");
					_current = new NullInputSystem();
				}
				return _current;
			}
		}

		public static bool LegacyInputSystemAvailable => Current is LegacyInputSystem;
	}
	public interface IInputSystem
	{
		Vector3 mousePosition { get; }

		Vector2 mouseScrollDelta { get; }

		bool mousePresent { get; }

		bool anyKey { get; }

		bool anyKeyDown { get; }

		IEnumerable<KeyCode> SupportedKeyCodes { get; }

		bool GetKey(string name);

		bool GetKey(KeyCode key);

		bool GetKeyDown(string name);

		bool GetKeyDown(KeyCode key);

		bool GetKeyUp(string name);

		bool GetKeyUp(KeyCode key);

		bool GetMouseButton(int button);

		bool GetMouseButtonDown(int button);

		bool GetMouseButtonUp(int button);

		void ResetInputAxes();
	}
	internal class NewInputSystem : IInputSystem
	{
		private delegate bool GetButtonDelegate(KeyCode key);

		private delegate Vector2 GetMouseVectorDelegate();

		private delegate bool GetMouseStateDelegate();

		private static bool initialized;

		private static readonly Dictionary<KeyCode, int> keyCodeToIndex = new Dictionary<KeyCode, int>();

		private static readonly Dictionary<string, string> keyToKeyCodeNameRemap = new Dictionary<string, string>
		{
			["LeftCtrl"] = "LeftControl",
			["RightCtrl"] = "RightControl",
			["LeftMeta"] = "LeftApple",
			["RightMeta"] = "RightApple",
			["ContextMenu"] = "Menu",
			["PrintScreen"] = "Print",
			["Enter"] = "Return"
		};

		private static GetButtonDelegate _getKey;

		private static GetButtonDelegate _getKeyDown;

		private static GetButtonDelegate _getKeyUp;

		private static GetButtonDelegate _getMouseButton;

		private static GetButtonDelegate _getMouseButtonDown;

		private static GetButtonDelegate _getMouseButtonUp;

		private static GetMouseVectorDelegate _getMousePosition;

		private static GetMouseVectorDelegate _getMouseScrollDelta;

		private static GetMouseStateDelegate _getMousePresent;

		private static GetMouseStateDelegate _getKeyboardAnyKeyIsPressed;

		private static GetMouseStateDelegate _getKeyboardAnyKeyWasPressedThisFrame;

		public Vector3 mousePosition => Vector2.op_Implicit(_getMousePosition());

		public Vector2 mouseScrollDelta => _getMouseScrollDelta();

		public bool mousePresent => _getMousePresent();

		public bool anyKey
		{
			get
			{
				if (_getKeyboardAnyKeyIsPressed())
				{
					return true;
				}
				if (!GetMouseButton(0) && !GetMouseButton(1) && !GetMouseButton(2) && !GetMouseButton(3))
				{
					return GetMouseButton(4);
				}
				return true;
			}
		}

		public bool anyKeyDown
		{
			get
			{
				if (_getKeyboardAnyKeyWasPressedThisFrame())
				{
					return true;
				}
				if (!GetMouseButtonDown(0) && !GetMouseButtonDown(1) && !GetMouseButtonDown(2) && !GetMouseButtonDown(3))
				{
					return GetMouseButtonDown(4);
				}
				return true;
			}
		}

		public IEnumerable<KeyCode> SupportedKeyCodes => keyCodeToIndex.Keys.ToArray();

		public NewInputSystem()
		{
			Init();
		}

		private static void Init()
		{
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			if (initialized)
			{
				return;
			}
			Assembly assembly = Assembly.Load("Unity.InputSystem");
			Type type = assembly.GetType("UnityEngine.InputSystem.Key");
			foreach (object value3 in Enum.GetValues(type))
			{
				string text = value3.ToString();
				int value = (int)value3;
				string value2;
				if (text.StartsWith("Numpad"))
				{
					text = text.Replace("Numpad", "Keypad");
				}
				else if (text.StartsWith("Digit"))
				{
					text = text.Replace("Digit", "Alpha");
				}
				else if (keyToKeyCodeNameRemap.TryGetValue(text, out value2))
				{
					text = value2;
				}
				if (TryEnumParse<KeyCode>(text, out var val))
				{
					keyCodeToIndex[val] = value;
				}
				else
				{
					Logger.LogDebug("[UnityInput] Unknown key name: " + text + ", skipping remapping");
				}
			}
			FieldInfo keyCodeToIndexField = AccessTools.Field(typeof(NewInputSystem), "keyCodeToIndex");
			MethodInfo tryGetValueMethod = AccessTools.Method(typeof(Dictionary<KeyCode, int>), "TryGetValue", (Type[])null, (Type[])null);
			Type type2 = assembly.GetType("UnityEngine.InputSystem.Keyboard");
			MethodInfo currentProperty = AccessTools.PropertyGetter(type2, "current");
			MethodInfo indexer = AccessTools.Method(type2, "get_Item", new Type[1] { type }, (Type[])null);
			Type buttonControlType = assembly.GetType("UnityEngine.InputSystem.Controls.ButtonControl");
			_getKey = GenerateKeyGetter("InputSystemGetKey", "isPressed");
			_getKeyDown = GenerateKeyGetter("InputSystemGetKeyDown", "wasPressedThisFrame");
			_getKeyUp = GenerateKeyGetter("InputSystemGetKeyUp", "wasReleasedThisFrame");
			Type mouseType = assembly.GetType("UnityEngine.InputSystem.Mouse");
			MethodInfo mouseCurrentProperty = AccessTools.PropertyGetter(mouseType, "current");
			string[] source = new string[5] { "leftButton", "rightButton", "middleButton", "backButton", "forwardButton" };
			MethodInfo[] buttonPropertyGetters = source.Select((string p) => AccessTools.PropertyGetter(mouseType, p)).ToArray();
			_getMouseButton = GenerateMouseGetter("InputSystemGetMouseButton", "isPressed");
			_getMouseButtonDown = GenerateMouseGetter("InputSystemGetMouseButtonDown", "wasPressedThisFrame");
			_getMouseButtonUp = GenerateMouseGetter("InputSystemGetMouseButtonUp", "wasReleasedThisFrame");
			_getMousePosition = GetPositionDelegate("InputSystemGetMousePosition", "position");
			_getMouseScrollDelta = GetPositionDelegate("InputSystemGetMouseScrollDelta", "scroll");
			DynamicMethodDefinition val2 = new DynamicMethodDefinition("InputSystemGetMouseEnabled", typeof(bool), Type.EmptyTypes);
			ILGenerator iLGenerator = val2.GetILGenerator();
			iLGenerator.Emit(OpCodes.Call, mouseCurrentProperty);
			iLGenerator.Emit(OpCodes.Callvirt, AccessTools.PropertyGetter(mouseType, "enabled"));
			iLGenerator.Emit(OpCodes.Ret);
			_getMousePresent = Extensions.CreateDelegate<GetMouseStateDelegate>((MethodBase)val2.Generate());
			MethodInfo anyKeyProperty = AccessTools.PropertyGetter(type2, "anyKey");
			_getKeyboardAnyKeyIsPressed = GetAnyKeyDelegate("InputSystemGetKeyboardAnyKeyIsPressed", "isPressed");
			_getKeyboardAnyKeyWasPressedThisFrame = GetAnyKeyDelegate("InputSystemGetKeyboardAnyKeyWasPressedThisFrame", "wasPressedThisFrame");
			initialized = true;
			GetButtonDelegate GenerateKeyGetter(string name, string property)
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				MethodInfo meth4 = AccessTools.PropertyGetter(buttonControlType, property);
				DynamicMethodDefinition val6 = new DynamicMethodDefinition(name, typeof(bool), new Type[1] { typeof(KeyCode) });
				ILGenerator iLGenerator4 = val6.GetILGenerator();
				LocalBuilder local = iLGenerator4.DeclareLocal(typeof(int));
				Label label2 = iLGenerator4.DefineLabel();
				iLGenerator4.Emit(OpCodes.Ldsfld, keyCodeToIndexField);
				iLGenerator4.Emit(OpCodes.Ldarg_0);
				iLGenerator4.Emit(OpCodes.Ldloca, local);
				iLGenerator4.Emit(OpCodes.Callvirt, tryGetValueMethod);
				iLGenerator4.Emit(OpCodes.Brfalse, label2);
				iLGenerator4.Emit(OpCodes.Call, currentProperty);
				iLGenerator4.Emit(OpCodes.Ldloc, local);
				iLGenerator4.Emit(OpCodes.Callvirt, indexer);
				iLGenerator4.Emit(OpCodes.Callvirt, meth4);
				iLGenerator4.Emit(OpCodes.Ret);
				iLGenerator4.MarkLabel(label2);
				iLGenerator4.Emit(OpCodes.Ldc_I4_0);
				iLGenerator4.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetButtonDelegate>((MethodBase)val6.Generate());
			}
			GetButtonDelegate GenerateMouseGetter(string name, string property)
			{
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Expected O, but got Unknown
				MethodInfo meth3 = AccessTools.PropertyGetter(buttonControlType, property);
				DynamicMethodDefinition val5 = new DynamicMethodDefinition(name, typeof(bool), new Type[1] { typeof(KeyCode) });
				ILGenerator il = val5.GetILGenerator();
				il.Emit(OpCodes.Ldarg_0);
				il.Emit(OpCodes.Ldc_I4, 323);
				il.Emit(OpCodes.Sub);
				Label[] array = buttonPropertyGetters.Select((MethodInfo _) => il.DefineLabel()).ToArray();
				Label label = il.DefineLabel();
				il.Emit(OpCodes.Switch, array);
				il.Emit(OpCodes.Br, label);
				for (int i = 0; i < array.Length; i++)
				{
					il.MarkLabel(array[i]);
					il.Emit(OpCodes.Call, mouseCurrentProperty);
					il.Emit(OpCodes.Callvirt, buttonPropertyGetters[i]);
					il.Emit(OpCodes.Callvirt, meth3);
					il.Emit(OpCodes.Ret);
				}
				il.MarkLabel(label);
				il.Emit(OpCodes.Ldc_I4_0);
				il.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetButtonDelegate>((MethodBase)val5.Generate());
			}
			GetMouseStateDelegate GetAnyKeyDelegate(string name, string property)
			{
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				MethodInfo meth = AccessTools.PropertyGetter(buttonControlType, property);
				DynamicMethodDefinition val3 = new DynamicMethodDefinition(name, typeof(bool), Type.EmptyTypes);
				ILGenerator iLGenerator2 = val3.GetILGenerator();
				iLGenerator2.Emit(OpCodes.Call, currentProperty);
				iLGenerator2.Emit(OpCodes.Callvirt, anyKeyProperty);
				iLGenerator2.Emit(OpCodes.Callvirt, meth);
				iLGenerator2.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetMouseStateDelegate>((MethodBase)val3.Generate());
			}
			GetMouseVectorDelegate GetPositionDelegate(string name, string property)
			{
				//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)
				MethodInfo methodInfo = AccessTools.PropertyGetter(mouseType, property);
				MethodInfo meth2 = AccessTools.Method(methodInfo.ReturnType, "ReadValue", (Type[])null, (Type[])null);
				DynamicMethodDefinition val4 = new DynamicMethodDefinition(name, typeof(Vector2), Type.EmptyTypes);
				ILGenerator iLGenerator3 = val4.GetILGenerator();
				iLGenerator3.Emit(OpCodes.Call, mouseCurrentProperty);
				iLGenerator3.Emit(OpCodes.Callvirt, methodInfo);
				iLGenerator3.Emit(OpCodes.Callvirt, meth2);
				iLGenerator3.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetMouseVectorDelegate>((MethodBase)val4.Generate());
			}
		}

		public bool GetKey(string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return _getKey(GetKeyCode(name));
		}

		public bool GetKey(KeyCode key)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return _getKey(key);
		}

		public bool GetKeyDown(string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyDown(GetKeyCode(name));
		}

		public bool GetKeyDown(KeyCode key)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyDown(key);
		}

		public bool GetKeyUp(string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyUp(GetKeyCode(name));
		}

		public bool GetKeyUp(KeyCode key)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyUp(key);
		}

		public bool GetMouseButton(int button)
		{
			return _getMouseButton((KeyCode)(323 + button));
		}

		public bool GetMouseButtonDown(int button)
		{
			return _getMouseButtonDown((KeyCode)(323 + button));
		}

		public bool GetMouseButtonUp(int button)
		{
			return _getMouseButtonUp((KeyCode)(323 + button));
		}

		public void ResetInputAxes()
		{
		}

		private static KeyCode GetKeyCode(string name)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			return (KeyCode)Enum.Parse(typeof(KeyCode), name, ignoreCase: true);
		}

		private static bool TryEnumParse<T>(string name, out T val)
		{
			try
			{
				val = (T)Enum.Parse(typeof(T), name, ignoreCase: true);
				return true;
			}
			catch (Exception)
			{
				val = default(T);
				return false;
			}
		}
	}
	internal class LegacyInputSystem : IInputSystem
	{
		public Vector3 mousePosition => Input.mousePosition;

		public Vector2 mouseScrollDelta => Input.mouseScrollDelta;

		public bool mousePresent => Input.mousePresent;

		public bool anyKey => Input.anyKey;

		public bool anyKeyDown => Input.anyKeyDown;

		public IEnumerable<KeyCode> SupportedKeyCodes { get; } = (KeyCode[])Enum.GetValues(typeof(KeyCode));


		public bool GetKey(string name)
		{
			return Input.GetKey(name);
		}

		public bool GetKey(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Input.GetKey(key);
		}

		public bool GetKeyDown(string name)
		{
			return Input.GetKeyDown(name);
		}

		public bool GetKeyDown(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Input.GetKeyDown(key);
		}

		public bool GetKeyUp(string name)
		{
			return Input.GetKeyUp(name);
		}

		public bool GetKeyUp(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Input.GetKeyUp(key);
		}

		public bool GetMouseButton(int button)
		{
			return Input.GetMouseButton(button);
		}

		public bool GetMouseButtonDown(int button)
		{
			return Input.GetMouseButtonDown(button);
		}

		public bool GetMouseButtonUp(int button)
		{
			return Input.GetMouseButtonUp(button);
		}

		public void ResetInputAxes()
		{
			Input.ResetInputAxes();
		}
	}
	internal class NullInputSystem : IInputSystem
	{
		private static readonly KeyCode[] NoKeys = (KeyCode[])(object)new KeyCode[0];

		public Vector3 mousePosition => Vector3.zero;

		public Vector2 mouseScrollDelta => Vector2.zero;

		public bool mousePresent => false;

		public bool anyKey => false;

		public bool anyKeyDown => false;

		public IEnumerable<KeyCode> SupportedKeyCodes => NoKeys;

		public bool GetKey(string name)
		{
			return false;
		}

		public bool GetKey(KeyCode key)
		{
			return false;
		}

		public bool GetKeyDown(string name)
		{
			return false;
		}

		public bool GetKeyDown(KeyCode key)
		{
			return false;
		}

		public bool GetKeyUp(string name)
		{
			return false;
		}

		public bool GetKeyUp(KeyCode key)
		{
			return false;
		}

		public bool GetMouseButton(int button)
		{
			return false;
		}

		public bool GetMouseButtonDown(int button)
		{
			return false;
		}

		public bool GetMouseButtonUp(int button)
		{
			return false;
		}

		public void ResetInputAxes()
		{
		}
	}
	internal static class ConsoleManager
	{
		public enum ConsoleOutRedirectType
		{
			[Description("Auto")]
			Auto,
			[Description("Console Out")]
			ConsoleOut,
			[Description("Standard Out")]
			StandardOut
		}

		private const uint SHIFT_JIS_CP = 932u;

		private static readonly bool? EnableConsoleArgOverride;

		private const string ENABLE_CONSOLE_ARG = "--enable-console";

		public static readonly ConfigEntry<bool> ConfigConsoleEnabled;

		public static readonly ConfigEntry<bool> ConfigPreventClose;

		public static readonly ConfigEntry<bool> ConfigConsoleShiftJis;

		public static readonly ConfigEntry<ConsoleOutRedirectType> ConfigConsoleOutRedirectType;

		internal static IConsoleDriver Driver { get; set; }

		public static bool ConsoleActive => Driver?.ConsoleActive ?? false;

		public static TextWriter StandardOutStream => Driver?.StandardOut;

		public static TextWriter ConsoleStream => Driver?.ConsoleOut;

		public static bool ConsoleEnabled => EnableConsoleArgOverride ?? ConfigConsoleEnabled.Value;

		static ConsoleManager()
		{
			ConfigConsoleEnabled = ConfigFile.CoreConfig.Bind("Logging.Console", "Enabled", defaultValue: false, "Enables showing a console for log output.");
			ConfigPreventClose = ConfigFile.CoreConfig.Bind("Logging.Console", "PreventClose", defaultValue: false, "If enabled, will prevent closing the console (either by deleting the close button or in other platform-specific way).");
			ConfigConsoleShiftJis = ConfigFile.CoreConfig.Bind("Logging.Console", "ShiftJisEncoding", defaultValue: false, "If true, console is set to the Shift-JIS encoding, otherwise UTF-8 encoding.");
			ConfigConsoleOutRedirectType = ConfigFile.CoreConfig.Bind("Logging.Console", "StandardOutType", ConsoleOutRedirectType.Auto, new StringBuilder().AppendLine("Hints console manager on what handle to assign as StandardOut. Possible values:").AppendLine("Auto - lets BepInEx decide how to redirect console output").AppendLine("ConsoleOut - prefer redirecting to console output; if possible, closes original standard output")
				.AppendLine("StandardOut - prefer redirecting to standard output; if possible, closes console out")
				.ToString());
			try
			{
				string[] commandLineArgs = Environment.GetCommandLineArgs();
				for (int i = 0; i < commandLineArgs.Length; i++)
				{
					if (commandLineArgs[i] == "--enable-console" && i + 1 < commandLineArgs.Length && bool.TryParse(commandLineArgs[i + 1], out var result))
					{
						EnableConsoleArgOverride = result;
					}
				}
			}
			catch (Exception)
			{
			}
		}

		public static void Initialize(bool alreadyActive)
		{
			if (PlatformHelper.Is((Platform)8))
			{
				Driver = new LinuxConsoleDriver();
			}
			else if (PlatformHelper.Is((Platform)37))
			{
				Driver = new WindowsConsoleDriver();
			}
			Driver.Initialize(alreadyActive);
		}

		private static void DriverCheck()
		{
			if (Driver == null)
			{
				throw new InvalidOperationException("Driver has not been initialized");
			}
		}

		public static void CreateConsole()
		{
			if (!ConsoleActive)
			{
				DriverCheck();
				uint codepage = (ConfigConsoleShiftJis.Value ? 932u : ((uint)Encoding.UTF8.CodePage));
				Driver.CreateConsole(codepage);
				if (ConfigPreventClose.Value)
				{
					Driver.PreventClose();
				}
			}
		}

		public static void DetachConsole()
		{
			if (ConsoleActive)
			{
				DriverCheck();
				Driver.DetachConsole();
			}
		}

		public static void SetConsoleTitle(string title)
		{
			DriverCheck();
			Driver.SetConsoleTitle(title);
		}

		public static void SetConsoleColor(ConsoleColor color)
		{
			DriverCheck();
			Driver.SetConsoleColor(color);
		}
	}
	internal interface IConsoleDriver
	{
		TextWriter StandardOut { get; }

		TextWriter ConsoleOut { get; }

		bool ConsoleActive { get; }

		bool ConsoleIsExternal { get; }

		void PreventClose();

		void Initialize(bool alreadyActive);

		void CreateConsole(uint codepage);

		void DetachConsole();

		void SetConsoleColor(ConsoleColor color);

		void SetConsoleTitle(string title);
	}
	internal class WindowsConsoleDriver : IConsoleDriver
	{
		private static readonly ConstructorInfo FileStreamCtor = new ConstructorInfo[2]
		{
			AccessTools.Constructor(typeof(FileStream), new Type[2]
			{
				typeof(SafeFileHandle),
				typeof(FileAccess)
			}, false),
			AccessTools.Constructor(typeof(FileStream), new Type[2]
			{
				typeof(IntPtr),
				typeof(FileAccess)
			}, false)
		}.FirstOrDefault((ConstructorInfo m) => (object)m != null);

		public TextWriter StandardOut { get; private set; }

		public TextWriter ConsoleOut { get; private set; }

		public bool ConsoleActive { get; private set; }

		public bool ConsoleIsExternal => true;

		public void PreventClose()
		{
			ConsoleWindow.PreventClose();
		}

		public void Initialize(bool alreadyActive)
		{
			ConsoleActive = alreadyActive;
			StandardOut = Console.Out;
		}

		private static FileStream OpenFileStream(IntPtr handle)
		{
			SafeFileHandle safeFileHandle = new SafeFileHandle(handle, ownsHandle: false);
			object[] args = AccessTools.ActualParameters((MethodBase)FileStreamCtor, new object[3]
			{
				safeFileHandle,
				safeFileHandle.DangerousGetHandle(),
				FileAccess.Write
			});
			return (FileStream)Activator.CreateInstance(typeof(FileStream), args);
		}

		public void CreateConsole(uint codepage)
		{
			ConsoleWindow.Attach();
			ConsoleEncoding.ConsoleCodePage = codepage;
			IntPtr outHandle = GetOutHandle();
			if (outHandle == IntPtr.Zero)
			{
				StandardOut = TextWriter.Null;
				ConsoleOut = TextWriter.Null;
				return;
			}
			FileStream stream = OpenFileStream(outHandle);
			StandardOut = new StreamWriter(stream, Utility.UTF8NoBom)
			{
				AutoFlush = true
			};
			FileStream stream2 = OpenFileStream(ConsoleWindow.ConsoleOutHandle);
			ConsoleOut = new StreamWriter(stream2, ConsoleEncoding.OutputEncoding)
			{
				AutoFlush = true
			};
			ConsoleActive = true;
		}

		private IntPtr GetOutHandle()
		{
			switch (ConsoleManager.ConfigConsoleOutRedirectType.Value)
			{
			case ConsoleManager.ConsoleOutRedirectType.ConsoleOut:
				return ConsoleWindow.ConsoleOutHandle;
			case ConsoleManager.ConsoleOutRedirectType.StandardOut:
				return ConsoleWindow.OriginalStdoutHandle;
			default:
				if (!(ConsoleWindow.OriginalStdoutHandle != IntPtr.Zero))
				{
					return ConsoleWindow.ConsoleOutHandle;
				}
				return ConsoleWindow.OriginalStdoutHandle;
			}
		}

		public void DetachConsole()
		{
			ConsoleWindow.Detach();
			ConsoleOut.Close();
			ConsoleOut = null;
			ConsoleActive = false;
		}

		public void SetConsoleColor(ConsoleColor color)
		{
			SafeConsole.ForegroundColor = color;
			Kon.ForegroundColor = color;
		}

		public void SetConsoleTitle(string title)
		{
			ConsoleWindow.Title = title;
		}
	}
	public class PluginInfo : ICacheable
	{
		public BepInPlugin Metadata { get; internal set; }

		public IEnumerable<BepInProcess> Processes { get; internal set; }

		public IEnumerable<BepInDependency> Dependencies { get; internal set; }

		public IEnumerable<BepInIncompatibility> Incompatibilities { get; internal set; }

		public string Location { get; internal set; }

		public BaseUnityPlugin Instance { get; internal set; }

		internal string TypeName { get; set; }

		internal Version TargettedBepInExVersion { get; set; }

		void ICacheable.Save(BinaryWriter bw)
		{
			bw.Write(TypeName);
			bw.Write(Metadata.GUID);
			bw.Write(Metadata.Name);
			bw.Write(Metadata.Version.ToString());
			List<BepInProcess> list = Processes.ToList();
			bw.Write(list.Count);
			foreach (BepInProcess item in list)
			{
				bw.Write(item.ProcessName);
			}
			List<BepInDependency> list2 = Dependencies.ToList();
			bw.Write(list2.Count);
			foreach (BepInDependency item2 in list2)
			{
				((ICacheable)item2).Save(bw);
			}
			List<BepInIncompatibility> list3 = Incompatibilities.ToList();
			bw.Write(list3.Count);
			foreach (BepInIncompatibility item3 in list3)
			{
				((ICacheable)item3).Save(bw);
			}
			bw.Write(TargettedBepInExVersion.ToString(4));
		}

		void ICacheable.Load(BinaryReader br)
		{
			TypeName = br.ReadString();
			Metadata = new BepInPlugin(br.ReadString(), br.ReadString(), br.ReadString());
			int num = br.ReadInt32();
			List<BepInProcess> list = new List<BepInProcess>(num);
			for (int i = 0; i < num; i++)
			{
				list.Add(new BepInProcess(br.ReadString()));
			}
			Processes = list;
			int num2 = br.ReadInt32();
			List<BepInDependency> list2 = new List<BepInDependency>(num2);
			for (int j = 0; j < num2; j++)
			{
				BepInDependency bepInDependency = new BepInDependency("");
				((ICacheable)bepInDependency).Load(br);
				list2.Add(bepInDependency);
			}
			Dependencies = list2;
			int num3 = br.ReadInt32();
			List<BepInIncompatibility> list3 = new List<BepInIncompatibility>(num3);
			for (int k = 0; k < num3; k++)
			{
				BepInIncompatibility bepInIncompatibility = new BepInIncompatibility("");
				((ICacheable)bepInIncompatibility).Load(br);
				list3.Add(bepInIncompatibility);
			}
			Incompatibilities = list3;
			TargettedBepInExVersion = new Version(br.ReadString());
		}

		public override string ToString()
		{
			return $"{Metadata?.Name} {Metadata?.Version}";
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
	public class BepInPlugin : Attribute
	{
		public string GUID { get; protected set; }

		public string Name { get; protected set; }

		public Version Version { get; protected set; }

		public BepInPlugin(string GUID, string Name, string Version)
		{
			this.GUID = GUID;
			this.Name = Name;
			try
			{
				this.Version = new Version(Version);
			}
			catch
			{
				this.Version = null;
			}
		}

		internal static BepInPlugin FromCecilType(TypeDefinition td)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			CustomAttribute val = MetadataHelper.GetCustomAttributes<BepInPlugin>(td, inherit: false).FirstOrDefault();
			if (val == null)
			{
				return null;
			}
			CustomAttributeArgument val2 = val.ConstructorArguments[0];
			string gUID = (string)((CustomAttributeArgument)(ref val2)).Value;
			val2 = val.ConstructorArguments[1];
			string name = (string)((CustomAttributeArgument)(ref val2)).Value;
			val2 = val.ConstructorArguments[2];
			return new BepInPlugin(gUID, name, (string)((CustomAttributeArgument)(ref val2)).Value);
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	public class BepInDependency : Attribute, ICacheable
	{
		[Flags]
		public enum DependencyFlags
		{
			HardDependency = 1,
			SoftDependency = 2
		}

		public string DependencyGUID { get; protected set; }

		public DependencyFlags Flags { get; protected set; }

		public Version MinimumVersion { get; protected set; }

		public BepInDependency(string DependencyGUID, DependencyFlags Flags = DependencyFlags.HardDependency)
		{
			this.DependencyGUID = DependencyGUID;
			this.Flags = Flags;
			MinimumVersion = new Version();
		}

		public BepInDependency(string DependencyGUID, string MinimumDependencyVersion)
			: this(DependencyGUID)
		{
			MinimumVersion = new Version(MinimumDependencyVersion);
		}

		internal static IEnumerable<BepInDependency> FromCecilType(TypeDefinition td)
		{
			return MetadataHelper.GetCustomAttributes<BepInDependency>(td, inherit: true).Select(delegate(CustomAttribute customAttribute)
			{
				//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_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)
				CustomAttributeArgument val = customAttribute.ConstructorArguments[0];
				string dependencyGUID = (string)((CustomAttributeArgument)(ref val)).Value;
				val = customAttribute.ConstructorArguments[1];
				object value = ((CustomAttributeArgument)(ref val)).Value;
				return (value is string minimumDependencyVersion) ? new BepInDependency(dependencyGUID, minimumDependencyVersion) : new BepInDependency(dependencyGUID, (DependencyFlags)value);
			}).ToList();
		}

		void ICacheable.Save(BinaryWriter bw)
		{
			bw.Write(DependencyGUID);
			bw.Write((int)Flags);
			bw.Write(MinimumVersion.ToString());
		}

		void ICacheable.Load(BinaryReader br)
		{
			DependencyGUID = br.ReadString();
			Flags = (DependencyFlags)br.ReadInt32();
			MinimumVersion = new Version(br.ReadString());
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	public class BepInIncompatibility : Attribute, ICacheable
	{
		public string IncompatibilityGUID { get; protected set; }

		public BepInIncompatibility(string IncompatibilityGUID)
		{
			this.IncompatibilityGUID = IncompatibilityGUID;
		}

		internal static IEnumerable<BepInIncompatibility> FromCecilType(TypeDefinition td)
		{
			return MetadataHelper.GetCustomAttributes<BepInIncompatibility>(td, inherit: true).Select(delegate(CustomAttribute customAttribute)
			{
				//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)
				CustomAttributeArgument val = customAttribute.ConstructorArguments[0];
				return new BepInIncompatibility((string)((CustomAttributeArgument)(ref val)).Value);
			}).ToList();
		}

		void ICacheable.Save(BinaryWriter bw)
		{
			bw.Write(IncompatibilityGUID);
		}

		void ICacheable.Load(BinaryReader br)
		{
			IncompatibilityGUID = br.ReadString();
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	public class BepInProcess : Attribute
	{
		public string ProcessName { get; protected set; }

		public BepInProcess(string ProcessName)
		{
			this.ProcessName = ProcessName;
		}

		internal static List<BepInProcess> FromCecilType(TypeDefinition td)
		{
			return MetadataHelper.GetCustomAttributes<BepInProcess>(td, inherit: true).Select(delegate(CustomAttribute customAttribute)
			{
				//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)
				CustomAttributeArgument val = customAttribute.ConstructorArguments[0];
				return new BepInProcess((string)((CustomAttributeArgument)(ref val)).Value);
			}).ToList();
		}
	}
	public static class MetadataHelper
	{
		internal static IEnumerable<CustomAttribute> GetCustomAttributes<T>(TypeDefinition td, bool inherit) where T : Attribute
		{
			List<CustomAttribute> list = new List<CustomAttribute>();
			Type type = typeof(T);
			TypeDefinition val = td;
			do
			{
				list.AddRange(((IEnumerable<CustomAttribute>)val.CustomAttributes).Where((CustomAttribute ca) => ((MemberReference)ca.AttributeType).FullName == type.FullName));
				TypeReference baseType = val.BaseType;
				val = ((baseType != null) ? baseType.Resolve() : null);
			}
			while (inherit && ((val != null) ? ((MemberReference)val).FullName : null) != "System.Object");
			return list;
		}

		public static BepInPlugin GetMetadata(Type pluginType)
		{
			object[] customAttributes = pluginType.GetCustomAttributes(typeof(BepInPlugin), inherit: false);
			if (customAttributes.Length == 0)
			{
				return null;
			}
			return (BepInPlugin)customAttributes[0];
		}

		public static BepInPlugin GetMetadata(object plugin)
		{
			return GetMetadata(plugin.GetType());
		}

		public static T[] GetAttributes<T>(Type pluginType) where T : Attribute
		{
			return (T[])pluginType.GetCustomAttributes(typeof(T), inherit: true);
		}

		public static IEnumerable<T> GetAttributes<T>(object plugin) where T : Attribute
		{
			return GetAttributes<T>(plugin.GetType());
		}

		public static IEnumerable<BepInDependency> GetDependencies(Type plugin)
		{
			return plugin.GetCustomAttributes(typeof(BepInDependency), inherit: true).Cast<BepInDependency>();
		}
	}
	internal class BuildInfoAttribute : Attribute
	{
		public string Info { get; }

		public BuildInfoAttribute(string info)
		{
			Info = info;
		}
	}
	public abstract class BaseUnityPlugin : MonoBehaviour
	{
		public PluginInfo Info { get; }

		protected ManualLogSource Logger { get; }

		public ConfigFile Config { get; }

		protected BaseUnityPlugin()
		{
			BepInPlugin metadata = MetadataHelper.GetMetadata(this);
			if (metadata == null)
			{
				throw new InvalidOperationException("Can't create an instance of " + ((object)this).GetType().FullName + " because it inherits from BaseUnityPlugin and the BepInPlugin attribute is missing.");
			}
			if (!Chainloader.IsEditor && Chainloader.PluginInfos.TryGetValue(metadata.GUID, out var value))
			{
				Info = value;
			}
			else
			{
				Info = new PluginInfo
				{
					Metadata = metadata,
					Instance = this,
					Dependencies = MetadataHelper.GetDependencies(((object)this).GetType()),
					Processes = MetadataHelper.GetAttributes<BepInProcess>(((object)this).GetType()),
					Location = ((object)this).GetType().Assembly.Location
				};
			}
			Logger = BepInEx.Logging.Logger.CreateLogSource(metadata.Name);
			string text = (Chainloader.IsEditor ? "." : Paths.ConfigPath);
			Config = new ConfigFile(Utility.CombinePaths(text, metadata.GUID + ".cfg"), saveOnInit: false, metadata);
		}
	}
	public static class Paths
	{
		public static string[] DllSearchPaths { get; private set; }

		public static string BepInExAssemblyDirectory { get; private set; }

		public static string BepInExAssemblyPath { get; private set; }

		public static string BepInExRootPath { get; private set; }

		public static string ExecutablePath { get; private set; }

		public static string GameRootPath { get; private set; }

		public static string ManagedPath { get; private set; }

		public static string ConfigPath { get; private set; }

		public static string BepInExConfigPath { get; private set; }

		public static string CachePath { get; private set; }

		public static string PatcherPluginPath { get; private set; }

		public static string PluginPath { get; private set; }

		public static string ProcessName { get; private set; }

		internal static void SetExecutablePath(string executablePath, string bepinRootPath = null, string managedPath = null, string[] dllSearchPath = null)
		{
			ExecutablePath = executablePath;
			ProcessName = Path.GetFileNameWithoutExtension(executablePath);
			GameRootPath = (PlatformHelper.Is((Platform)73) ? Utility.ParentDirectory(executablePath, 4) : Path.GetDirectoryName(executablePath));
			ManagedPath = managedPath ?? Utility.CombinePaths(GameRootPath, ProcessName + "_Data", "Managed");
			BepInExRootPath = bepinRootPath ?? Path.Combine(GameRootPath, "BepInEx");
			ConfigPath = Path.Combine(BepInExRootPath, "config");
			BepInExConfigPath = Path.Combine(ConfigPath, "BepInEx.cfg");
			PluginPath = Path.Combine(BepInExRootPath, "plugins");
			PatcherPluginPath = Path.Combine(BepInExRootPath, "patchers");
			BepInExAssemblyDirectory = Path.Combine(BepInExRootPath, "core");
			BepInExAssemblyPath = Path.Combine(BepInExAssemblyDirectory, Assembly.GetExecutingAssembly().GetName().Name + ".dll");
			CachePath = Path.Combine(BepInExRootPath, "cache");
			DllSearchPaths = (dllSearchPath ?? new string[0]).Concat(new string[1] { ManagedPath }).Distinct().ToArray();
		}

		internal static void SetManagedPath(string managedPath)
		{
			if (managedPath != null)
			{
				ManagedPath = managedPath;
			}
		}

		internal static void SetPluginPath(string pluginPath)
		{
			PluginPath = Utility.CombinePaths(BepInExRootPath, pluginPath);
		}
	}
	public sealed class ThreadingHelper : MonoBehaviour, ISynchronizeInvoke
	{
		private sealed class InvokeResult : IAsyncResult
		{
			internal bool ExceptionThrown;

			public bool IsCompleted { get; private set; }

			public WaitHandle AsyncWaitHandle { get; }

			public object AsyncState { get; private set; }

			public bool CompletedSynchronously { get; private set; }

			public InvokeResult()
			{
				AsyncWaitHandle = new EventWaitHandle(initialState: false, EventResetMode.ManualReset);
			}

			public void Finish(object result, bool completedSynchronously)
			{
				AsyncState = result;
				CompletedSynchronously = completedSynchronously;
				IsCompleted = true;
				((EventWaitHandle)AsyncWaitHandle).Set();
			}
		}

		private readonly object _invokeLock = new object();

		private Action _invokeList;

		private Thread _mainThread;

		public static ThreadingHelper Instance { get; private set; }

		public static ISynchronizeInvoke SynchronizingObject => Instance;

		public bool InvokeRequired
		{
			get
			{
				if (_mainThread != null)
				{
					return _mainThread != Thread.CurrentThread;
				}
				return true;
			}
		}

		internal static void Initialize()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			GameObject val = new GameObject("BepInEx_ThreadingHelper");
			if (Chainloader.ConfigHideBepInExGOs.Value)
			{
				((Object)val).hideFlags = (HideFlags)61;
			}
			Object.DontDestroyOnLoad((Object)(object)val);
			Instance = val.AddComponent<ThreadingHelper>();
		}

		public void StartSyncInvoke(Action action)
		{
			if (action == null)
			{
				throw new ArgumentNullException("action");
			}
			lock (_invokeLock)
			{
				_invokeList = (Action)Delegate.Combine(_invokeList, action);
			}
		}

		private void Update()
		{
			if (_mainThread == null)
			{
				_mainThread = Thread.CurrentThread;
			}
			if (_invokeList == null)
			{
				return;
			}
			Action invokeList;
			lock (_invokeLock)
			{
				invokeList = _invokeList;
				_invokeList = null;
			}
			foreach (Action item in invokeList.GetInvocationList().Cast<Action>())
			{
				try
				{
					item();
				}
				catch (Exception ex)
				{
					LogInvocationException(ex);
				}
			}
		}

		public void StartAsyncInvoke(Func<Action> action)
		{
			if (!ThreadPool.QueueUserWorkItem(DoWork))
			{
				throw new NotSupportedException("Failed to queue the action on ThreadPool");
			}
			void DoWork(object _)
			{
				try
				{
					Action action2 = action();
					if (action2 != null)
					{
						StartSyncInvoke(action2);
					}
				}
				catch (Exception ex)
				{
					LogInvocationException(ex);
				}
			}
		}

		private static void LogInvocationException(Exception ex)
		{
			Logger.Log(LogLevel.Error, ex);
			if (ex.InnerException != null)
			{
				Logger.Log(LogLevel.Error, "INNER: " + ex.InnerException);
			}
		}

		IAsyncResult ISynchronizeInvoke.BeginInvoke(Delegate method, object[] args)
		{
			InvokeResult result = new InvokeResult();
			if (!InvokeRequired)
			{
				result.Finish(Invoke(), completedSynchronously: true);
			}
			else
			{
				StartSyncInvoke(delegate
				{
					result.Finish(Invoke(), completedSynchronously: false);
				});
			}
			return result;
			object Invoke()
			{
				try
				{
					return method.DynamicInvoke(args);
				}
				catch (Exception result2)
				{
					result.ExceptionThrown = true;
					return result2;
				}
			}
		}

		object ISynchronizeInvoke.EndInvoke(IAsyncResult result)
		{
			InvokeResult invokeResult = (InvokeResult)result;
			invokeResult.AsyncWaitHandle.WaitOne();
			if (invokeResult.ExceptionThrown)
			{
				throw (Exception)invokeResult.AsyncState;
			}
			return invokeResult.AsyncState;
		}

		object ISynchronizeInvoke.Invoke(Delegate method, object[] args)
		{
			IAsyncResult result = ((ISynchronizeInvoke)this).BeginInvoke(method, args);
			return ((ISynchronizeInvoke)this).EndInvoke(result);
		}
	}
	public static class ThreadingExtensions
	{
		public static IEnumerable<TOut> RunParallel<TIn, TOut>(this IEnumerable<TIn> data, Func<TIn, TOut> work, int workerCount = -1)
		{
			foreach (TOut item in data.ToList().RunParallel(work))
			{
				yield return item;
			}
		}

		public static IEnumerable<TOut> RunParallel<TIn, TOut>(this IList<TIn> data, Func<TIn, TOut> work, int workerCount = -1)
		{
			if (workerCount < 0)
			{
				workerCount = Mathf.Max(2, Environment.ProcessorCount);
			}
			else if (workerCount == 0)
			{
				throw new ArgumentException("Need at least 1 worker", "workerCount");
			}
			int perThreadCount = Mathf.CeilToInt((float)data.Count / (float)workerCount);
			int doneCount = 0;
			object lockObj = new object();
			ManualResetEvent are = new ManualResetEvent(initialState: false);
			IEnumerable<TOut> doneItems = null;
			Exception exceptionThrown = null;
			for (int i = 0; i < workerCount; i++)
			{
				int first = i * perThreadCount;
				int last = Mathf.Min(first + perThreadCount, data.Count);
				ThreadPool.QueueUserWorkItem(delegate
				{
					List<TOut> list = new List<TOut>(perThreadCount);
					try
					{
						for (int j = first; j < last; j++)
						{
							if (exceptionThrown != null)
							{
								break;
							}
							list.Add(work(data[j]));
						}
					}
					catch (Exception ex)
					{
						exceptionThrown = ex;
					}
					lock (lockObj)
					{
						IEnumerable<TOut> enumerable2;
						if (doneItems != null)
						{
							enumerable2 = list.Concat(doneItems);
						}
						else
						{
							IEnumerable<TOut> enumerable3 = list;
							enumerable2 = enumerable3;
						}
						doneItems = enumerable2;
						int num = doneCount;
						doneCount = num + 1;
						are.Set();
					}
				});
			}
			bool isDone;
			do
			{
				are.WaitOne();
				IEnumerable<TOut> enumerable;
				lock (lockObj)
				{
					enumerable = doneItems;
					doneItems = null;
					isDone = doneCount == workerCount;
				}
				if (enumerable == null)
				{
					continue;
				}
				foreach (TOut item in enumerable)
				{
					yield return item;
				}
			}
			while (!isDone);
			if (exceptionThrown != null)
			{
				throw new TargetInvocationException("An exception was thrown inside one of the threads", exceptionThrown);
			}
		}
	}
	public static class Utility
	{
		private static bool? sreEnabled;

		public static bool CLRSupportsDynamicAssemblies => CheckSRE();

		public static Encoding UTF8NoBom { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);


		private static bool CheckSRE()
		{
			if (sreEnabled.HasValue)
			{
				return sreEnabled.Value;
			}
			try
			{
				new CustomAttributeBuilder(null, new object[0]);
			}
			catch (PlatformNotSupportedException)
			{
				sreEnabled = false;
				return sreEnabled.Value;
			}
			catch (ArgumentNullException)
			{
			}
			sreEnabled = true;
			return sreEnabled.Value;
		}

		public static bool TryDo(Action action, out Exception exception)
		{
			exception = null;
			try
			{
				action();
				return true;
			}
			catch (Exception ex)
			{
				exception = ex;
				return false;
			}
		}

		public static string CombinePaths(params string[] parts)
		{
			return parts.Aggregate(Path.Combine);
		}

		public static string ParentDirectory(string path, int levels = 1)
		{
			for (int i = 0; i < levels; i++)
			{
				path = Path.GetDirectoryName(path);
			}
			return path;
		}

		public static bool SafeParseBool(string input, bool defaultValue = false)
		{
			if (!bool.TryParse(input, out var result))
			{
				return defaultValue;
			}
			return result;
		}

		public static string ConvertToWWWFormat(string path)
		{
			return "file://" + path.Replace('\\', '/');
		}

		public static bool IsNullOrWhiteSpace(this string self)
		{
			return self?.All(char.IsWhiteSpace) ?? true;
		}

		public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector)
		{
			List<TNode> sorted_list = new List<TNode>();
			HashSet<TNode> visited = new HashSet<TNode>();
			HashSet<TNode> sorted = new HashSet<TNode>();
			foreach (TNode node in nodes)
			{
				Stack<TNode> stack2 = new Stack<TNode>();
				if (!Visit(node, stack2))
				{
					throw new Exception("Cyclic Dependency:\r\n" + stack2.Select((TNode x) => $" - {x}").Aggregate((string a, string b) => a + "\r\n" + b));
				}
			}
			return sorted_list;
			bool Visit(TNode node, Stack<TNode> stack)
			{
				if (visited.Contains(node))
				{
					if (!sorted.Contains(node))
					{
						return false;
					}
				}
				else
				{
					visited.Add(node);
					stack.Push(node);
					foreach (TNode item in dependencySelector(node))
					{
						if (!Visit(item, stack))
						{
							return false;
						}
					}
					sorted.Add(node);
					sorted_list.Add(node);
					stack.Pop();
				}
				return true;
			}
		}

		private static bool TryResolveDllAssembly<T>(AssemblyName assemblyName, string directory, Func<string, T> loader, out T assembly) where T : class
		{
			assembly = null;
			List<string> list = new List<string>();
			list.Add(directory);
			list.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories));
			foreach (string item in list)
			{
				string text = Path.Combine(item, assemblyName.Name + ".dll");
				if (File.Exists(text))
				{
					try
					{
						assembly = loader(text);
					}
					catch (Exception)
					{
						continue;
					}
					return true;
				}
			}
			return false;
		}

		public static bool IsSubtypeOf(this TypeDefinition self, Type td)
		{
			if (((MemberReference)self).FullName == td.FullName)
			{
				return true;
			}
			if (((MemberReference)self).FullName != "System.Object")
			{
				TypeReference baseType = self.BaseType;
				return ((baseType == null) ? null : baseType.Resolve()?.IsSubtypeOf(td)).GetValueOrDefault();
			}
			return false;
		}

		public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly)
		{
			return TryResolveDllAssembly(assemblyName, directory, (Func<string, Assembly>)Assembly.LoadFile, out assembly);
		}

		public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly)
		{
			return TryResolveDllAssembly(assemblyName, directory, (Func<string, AssemblyDefinition>)((string s) => AssemblyDefinition.ReadAssembly(s, readerParameters)), out assembly);
		}

		public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read)
		{
			try
			{
				fileStream = new FileStream(path, mode, access, share);
				return true;
			}
			catch (IOException)
			{
				fileStream = null;
				return false;
			}
		}

		public static bool TryParseAssemblyName(string fullName, out AssemblyName assemblyName)
		{
			try
			{
				assemblyName = new AssemblyName(fullName);
				return true;
			}
			catch (Exception)
			{
				assemblyName = null;
				return false;
			}
		}

		public static IEnumerable<string> GetUniqueFilesInDirectories(IEnumerable<string> directories, string pattern = "*")
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
			foreach (string directory in directories)
			{
				string[] files = Directory.GetFiles(directory, pattern);
				foreach (string text in files)
				{
					string fileName = Path.GetFileName(text);
					if (!dictionary.ContainsKey(fileName))
					{
						dictionary[fileName] = text;
					}
				}
			}
			return dictionary.Values;
		}
	}
}
namespace BepInEx.Logging
{
	public class DiskLogListener : ILogListener, IDisposable
	{
		public LogLevel DisplayedLogLevel { get; set; }

		public TextWriter LogWriter { get; protected set; }

		public Timer FlushTimer { get; protected set; }

		public bool WriteFromUnityLog { get; set; }

		public DiskLogListener(string localPath, LogLevel displayedLogLevel = LogLevel.Info, bool appendLog = false, bool includeUnityLog = false)
		{
			WriteFromUnityLog = includeUnityLog;
			DisplayedLogLevel = displayedLogLevel;
			int num = 1;
			FileStream fileStream;
			while (!Utility.TryOpenFileStream(Path.Combine(Paths.BepInExRootPath, localPath), appendLog ? FileMode.Append : FileMode.Create, out fileStream, FileAccess.Write))
			{
				if (num == 5)
				{
					Logger.LogError("Couldn't open a log file for writing. Skipping log file creation");
					return;
				}
				Logger.LogWarning("Couldn't open log file '" + localPath + "' for writing, trying another...");
				localPath = $"LogOutput.log.{num++}";
			}
			LogWriter = TextWriter.Synchronized(new StreamWriter(fileStream, Utility.UTF8NoBom));
			FlushTimer = new Timer(delegate
			{
				LogWriter?.Flush();
			}, null, 2000, 2000);
		}

		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			if ((WriteFromUnityLog || !(eventArgs.Source is UnityLogSource)) && (eventArgs.Level & DisplayedLogLevel) != 0)
			{
				LogWriter.WriteLine(eventArgs.ToString());
			}
		}

		public void Dispose()
		{
			FlushTimer?.Dispose();
			LogWriter?.Flush();
			LogWriter?.Dispose();
		}

		~DiskLogListener()
		{
			Dispose();
		}
	}
	internal class HarmonyLogSource : ILogSource, IDisposable
	{
		private static readonly ConfigEntry<LogChannel> LogChannels = ConfigFile.CoreConfig.Bind<LogChannel>("Harmony.Logger", "LogChannels", (LogChannel)24, "Specifies which Harmony log channels to listen to.\nNOTE: IL channel dumps the whole patch methods, use only when needed!");

		private static readonly Dictionary<LogChannel, LogLevel> LevelMap = new Dictionary<LogChannel, LogLevel>
		{
			[(LogChannel)2] = LogLevel.Info,
			[(LogChannel)8] = LogLevel.Warning,
			[(LogChannel)16] = LogLevel.Error,
			[(LogChannel)4] = LogLevel.Debug
		};

		public string SourceName { get; } = "HarmonyX";


		public event EventHandler<LogEventArgs> LogEvent;

		public HarmonyLogSource()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			Logger.ChannelFilter = LogChannels.Value;
			Logger.MessageReceived += HandleHarmonyMessage;
		}

		private void HandleHarmonyMessage(object sender, LogEventArgs e)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if (LevelMap.TryGetValue(e.LogChannel, out var value))
			{
				this.LogEvent?.Invoke(this, new LogEventArgs(e.Message, value, this));
			}
		}

		public void Dispose()
		{
			Logger.MessageReceived -= HandleHarmonyMessage;
		}
	}
	public class LogEventArgs : EventArgs
	{
		public object Data { get; protected set; }

		public LogLevel Level { get; protected set; }

		public ILogSource Source { get; protected set; }

		public LogEventArgs(object data, LogLevel level, ILogSource source)
		{
			Data = data;
			Level = level;
			Source = source;
		}

		public override string ToString()
		{
			return $"[{Level,-7}:{Source.SourceName,10}] {Data}";
		}

		public string ToStringLine()
		{
			return ToString() + Environment.NewLine;
		}
	}
	public static class Logger
	{
		private class LogSourceCollection : List<ILogSource>, ICollection<ILogSource>, IEnumerable<ILogSource>, IEnumerable
		{
			void ICollection<ILogSource>.Add(ILogSource item)
			{
				if (item == null)
				{
					throw new ArgumentNullException("item", "Log sources cannot be null when added to the source list.");
				}
				item.LogEvent += InternalLogEvent;
				Add(item);
			}

			void ICollection<ILogSource>.Clear()
			{
				ILogSource[] array = ToArray();
				foreach (ILogSource item in array)
				{
					((ICollection<ILogSource>)this).Remove(item);
				}
			}

			bool ICollection<ILogSource>.Remove(ILogSource item)
			{
				if (item == null)
				{
					return false;
				}
				if (!Contains(item))
				{
					return false;
				}
				item.LogEvent -= InternalLogEvent;
				Remove(item);
				return true;
			}
		}

		private static readonly ManualLogSource InternalLogSource = CreateLogSource("BepInEx");

		private static bool internalLogsInitialized;

		public static ICollection<ILogListener> Listeners { get; } = new List<ILogListener>();


		public static ICollection<ILogSource> Sources { get; } = new LogSourceCollection();


		internal static void InitializeInternalLoggers()
		{
			if (!internalLogsInitialized)
			{
				Sources.Add(new HarmonyLogSource());
				internalLogsInitialized = true;
			}
		}

		internal static void InternalLogEvent(object sender, LogEventArgs eventArgs)
		{
			foreach (ILogListener listener in Listeners)
			{
				listener?.LogEvent(sender, eventArgs);
			}
		}

		internal static void Log(LogLevel level, object data)
		{
			InternalLogSource.Log(level, data);
		}

		internal static void LogFatal(object data)
		{
			Log(LogLevel.Fatal, data);
		}

		internal static void LogError(object data)
		{
			Log(LogLevel.Error, data);
		}

		internal static void LogWarning(object data)
		{
			Log(LogLevel.Warning, data);
		}

		internal static void LogMessage(object data)
		{
			Log(LogLevel.Message, data);
		}

		internal static void LogInfo(object data)
		{
			Log(LogLevel.Info, data);
		}

		internal static void LogDebug(object data)
		{
			Log(LogLevel.Debug, data);
		}

		public static ManualLogSource CreateLogSource(string sourceName)
		{
			ManualLogSource manualLogSource = new ManualLogSource(sourceName);
			Sources.Add(manualLogSource);
			return manualLogSource;
		}
	}
	[Flags]
	public enum LogLevel
	{
		None = 0,
		Fatal = 1,
		Error = 2,
		Warning = 4,
		Message = 8,
		Info = 0x10,
		Debug = 0x20,
		All = 0x3F
	}
	public static class LogLevelExtensions
	{
		public static LogLevel GetHighestLevel(this LogLevel levels)
		{
			Array values = Enum.GetValues(typeof(LogLevel));
			Array.Sort(values);
			foreach (LogLevel item in values)
			{
				if ((levels & item) != 0)
				{
					return item;
				}
			}
			return LogLevel.None;
		}

		public static ConsoleColor GetConsoleColor(this LogLevel level)
		{
			level = level.GetHighestLevel();
			return level switch
			{
				LogLevel.Fatal => ConsoleColor.Red, 
				LogLevel.Error => ConsoleColor.DarkRed, 
				LogLevel.Warning => ConsoleColor.Yellow, 
				LogLevel.Message => ConsoleColor.White, 
				LogLevel.Debug => ConsoleColor.DarkGray, 
				_ => ConsoleColor.Gray, 
			};
		}
	}
	public interface ILogListener : IDisposable
	{
		void LogEvent(object sender, LogEventArgs eventArgs);
	}
	public interface ILogSource : IDisposable
	{
		string SourceName { get; }

		event EventHandler<LogEventArgs> LogEvent;
	}
	public class ManualLogSource : ILogSource, IDisposable
	{
		public string SourceName { get; }

		public event EventHandler<LogEventArgs> LogEvent;

		public ManualLogSource(string sourceName)
		{
			SourceName = sourceName;
		}

		public void Log(LogLevel level, object data)
		{
			this.LogEvent?.Invoke(this, new LogEventArgs(data, level, this));
		}

		public void LogFatal(object data)
		{
			Log(LogLevel.Fatal, data);
		}

		public void LogError(object data)
		{
			Log(LogLevel.Error, data);
		}

		public void LogWarning(object data)
		{
			Log(LogLevel.Warning, data);
		}

		public void LogMessage(object data)
		{
			Log(LogLevel.Message, data);
		}

		public void LogInfo(object data)
		{
			Log(LogLevel.Info, data);
		}

		public void LogDebug(object data)
		{
			Log(LogLevel.Debug, data);
		}

		public void Dispose()
		{
		}
	}
	public class TraceLogSource : TraceListener
	{
		private static TraceLogSource traceListener;

		public static bool IsListening { get; protected set; }

		protected ManualLogSource LogSource { get; }

		public static ILogSource CreateSource()
		{
			if (traceListener == null)
			{
				traceListener = new TraceLogSource();
				Trace.Listeners.Add(traceListener);
				IsListening = true;
			}
			return traceListener.LogSource;
		}

		protected TraceLogSource()
		{
			LogSource = new ManualLogSource("Trace");
		}

		public override void Write(string message)
		{
			LogSource.LogInfo(message);
		}

		public override void WriteLine(string message)
		{
			LogSource.LogInfo(message);
		}

		public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
		{
			TraceEvent(eventCache, source, eventType, id, string.Format(format, args));
		}

		public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
		{
			LogSource.Log(eventType switch
			{
				TraceEventType.Critical => LogLevel.Fatal, 
				TraceEventType.Error => LogLevel.Error, 
				TraceEventType.Warning => LogLevel.Warning, 
				TraceEventType.Information => LogLevel.Info, 
				_ => LogLevel.Debug, 
			}, (message ?? "").Trim());
		}
	}
	public class ConsoleLogListener : ILogListener, IDisposable
	{
		private static readonly ConfigEntry<LogLevel> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind("Logging.Console", "LogLevels", LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, "Which log levels to show in the console output.");

		internal bool WriteUnityLogs { get; set; } = true;


		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			if ((WriteUnityLogs || !(sender is UnityLogSource)) && (eventArgs.Level & ConfigConsoleDisplayedLevel.Value) != 0)
			{
				ConsoleManager.SetConsoleColor(eventArgs.Level.GetConsoleColor());
				ConsoleManager.ConsoleStream?.Write(eventArgs.ToStringLine());
				ConsoleManager.SetConsoleColor(ConsoleColor.Gray);
			}
		}

		public void Dispose()
		{
		}
	}
	public class UnityLogListener : ILogListener, IDisposable
	{
		internal static readonly Action<string> WriteStringToUnityLog;

		private ConfigEntry<bool> LogConsoleToUnity = ConfigFile.CoreConfig.Bind("Logging", "LogConsoleToUnityLog", defaultValue: false, new StringBuilder().AppendLine("If enabled, writes Standard Output messages to Unity log").AppendLine("NOTE: By default, Unity does so automatically. Only use this option if no console messages are visible in Unity log").ToString());

		static UnityLogListener()
		{
			MethodInfo[] methods = typeof(UnityLogWriter).GetMethods(BindingFlags.Static | BindingFlags.Public);
			foreach (MethodInfo methodInfo in methods)
			{
				try
				{
					methodInfo.Invoke(null, new object[1] { "" });
				}
				catch
				{
					continue;
				}
				WriteStringToUnityLog = (Action<string>)Delegate.CreateDelegate(typeof(Action<string>), methodInfo);
				break;
			}
			if (WriteStringToUnityLog == null)
			{
				Logger.LogError("Unable to start Unity log writer");
			}
		}

		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			if (!(eventArgs.Source is UnityLogSource) && (LogConsoleToUnity.Value || eventArgs.Source.SourceName != "Console"))
			{
				WriteStringToUnityLog?.Invoke(eventArgs.ToStringLine());
			}
		}

		public void Dispose()
		{
		}
	}
	public class UnityLogSource : ILogSource, IDisposable
	{
		private bool disposed;

		public string SourceName { get; } = "Unity Log";


		public event EventHandler<LogEventArgs> LogEvent;

		private static event EventHandler<LogEventArgs> InternalUnityLogMessage;

		public UnityLogSource()
		{
			InternalUnityLogMessage += UnityLogMessageHandler;
		}

		private void UnityLogMessageHandler(object sender, LogEventArgs eventArgs)
		{
			LogEventArgs e = new LogEventArgs(eventArgs.Data, eventArgs.Level, this);
			this.LogEvent?.Invoke(this, e);
		}

		public void Dispose()
		{
			if (!disposed)
			{
				InternalUnityLogMessage -= UnityLogMessageHandler;
				disposed = true;
			}
		}

		static UnityLogSource()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			LogCallback val = new LogCallback(OnUnityLogMessageReceived);
			EventInfo @event = typeof(Application).GetEvent("logMessageReceived", BindingFlags.Static | BindingFlags.Public);
			if ((object)@event != null)
			{
				@event.AddEventHandler(null, (Delegate?)(object)val);
				return;
			}
			typeof(Application).GetMethod("RegisterLogCallback", BindingFlags.Static | BindingFlags.Public).Invoke(null, new object[1] { val });
		}

		private static void OnUnityLogMessageReceived(string message, string stackTrace, LogType type)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected I4, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			LogLevel level;
			switch ((int)type)
			{
			case 0:
			case 1:
			case 4:
				level = LogLevel.Error;
				break;
			case 2:
				level = LogLevel.Warning;
				break;
			default:
				level = LogLevel.Info;
				break;
			}
			if ((int)type == 4)
			{
				message = message + "\nStack trace:\n" + stackTrace;
			}
			UnityLogSource.InternalUnityLogMessage?.Invoke(null, new LogEventArgs(message, level, null));
		}
	}
}
namespace BepInEx.Bootstrap
{
	public static class Chainloader
	{
		private static readonly List<BaseUnityPlugin> _plugins = new List<BaseUnityPlugin>();

		private static bool? isEditor;

		private static bool _loaded = false;

		private static bool _initialized = false;

		private static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;

		private static readonly Version CurrentAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;

		internal static readonly ConfigEntry<bool> ConfigHideBepInExGOs = ConfigFile.CoreConfig.Bind("Chainloader", "HideManagerGameObject", defaultValue: false, new StringBuilder().AppendLine("If enabled, hides BepInEx Manager GameObject from Unity.").AppendLine("This can fix loading issues in some games that attempt to prevent BepInEx from being loaded.").AppendLine("Use this only if you know what this option means, as it can affect functionality of some older plugins.")
			.ToString());

		private static readonly ConfigEntry<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Bind("Logging", "UnityLogListening", defaultValue: true, "Enables showing unity log messages in the BepInEx logging system.");

		private static readonly ConfigEntry<bool> ConfigDiskWriteUnityLog = ConfigFile.CoreConfig.Bind("Logging.Disk", "WriteUnityLog", defaultValue: false, "Include unity log messages in log file output.");

		private static readonly ConfigEntry<bool> ConfigDiskAppend = ConfigFile.CoreConfig.Bind("Logging.Disk", "AppendLog", defaultValue: false, "Appends to the log file instead of overwriting, on game startup.");

		private static readonly ConfigEntry<bool> ConfigDiskLogging = ConfigFile.CoreConfig.Bind("Logging.Disk", "Enabled", defaultValue: true, "Enables writing log messages to disk.");

		private static readonly ConfigEntry<LogLevel> ConfigDiskConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind("Logging.Disk", "LogLevels", LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, "Which log leves are saved to the disk log output.");

		public static Dictionary<string, PluginInfo> PluginInfos { get; } = new Dictionary<string, PluginInfo>();


		private static string UnityVersion
		{
			[MethodImpl(MethodImplOptions.NoInlining)]
			get
			{
				return Application.unityVersion;
			}
		}

		private static bool IsHeadless
		{
			get
			{
				MethodInfo methodInfo = AccessTools.PropertyGetter(typeof(Application), "isBatchMode");
				if ((object)methodInfo != null)
				{
					return (bool)methodInfo.Invoke(null, null);
				}
				return SystemInfo.graphicsDeviceID == 0;
			}
		}

		internal static bool IsEditor
		{
			[MethodImpl(MethodImplOptions.NoInlining)]
			get
			{
				bool? flag = isEditor;
				if (!flag.HasValue)
				{
					bool? flag2 = (isEditor = Application.isEditor);
					return flag2.GetValueOrDefault();
				}
				return flag.GetValueOrDefault();
			}
		}

		[Obsolete("Use PluginInfos instead")]
		public static List<BaseUnityPlugin> Plugins
		{
			get
			{
				lock (_plugins)
				{
					_plugins.RemoveAll((BaseUnityPlugin x) => (Object)(object)x == (Object)null);
					return _plugins.ToList();
				}
			}
		}

		public static List<string> DependencyErrors { get; } = new List<string>();


		public static GameObject ManagerObject { get; private set; }

		private static Regex allowedGuidRegex { get; } = new Regex("^[a-zA-Z0-9\\._\\-]+$");


		public static void Initialize(string gameExePath, bool startConsole = true, ICollection<LogEventArgs> preloaderLogEvents = null)
		{
			if (!_initialized)
			{
				ThreadingHelper.Initialize();
				if (gameExePath != null)
				{
					Paths.SetExecutablePath(gameExePath);
				}
				if (ConsoleManager.ConsoleEnabled && startConsole)
				{
					ConsoleManager.CreateConsole();
					Logger.Listeners.Add(new ConsoleLogListener());
				}
				Logger.InitializeInternalLoggers();
				if (ConfigDiskLogging.Value)
				{
					Logger.Listeners.Add(new DiskLogListener("LogOutput.log", ConfigDiskConsoleDisplayedLevel.Value, ConfigDiskAppend.Value, ConfigDiskWriteUnityLog.Value));
				}
				if (!TraceLogSource.IsListening)
				{
					Logger.Sources.Add(TraceLogSource.CreateSource());
				}
				ReplayPreloaderLogs(preloaderLogEvents);
				if (ConfigUnityLogging.Value)
				{
					Logger.Sources.Add(new UnityLogSource());
				}
				if (!IsHeadless)
				{
					Logger.Listeners.Add(new UnityLogListener());
				}
				else if (Logger.Listeners.FirstOrDefault((ILogListener l) => l is ConsoleLogListener) is ConsoleLogListener consoleLogListener)
				{
					consoleLogListener.WriteUnityLogs = false;
				}
				if (PlatformHelper.Is((Platform)8))
				{
					Logger.LogInfo("Detected Unity version: v" + UnityVersion);
				}
				Logger.LogMessage("Chainloader ready");
				_initialized = true;
			}
		}

		private static void ReplayPreloaderLogs(ICollection<LogEventArgs> preloaderLogEvents)
		{
			if (preloaderLogEvents == null)
			{
				return;
			}
			UnityLogListener item = new UnityLogListener();
			Logger.Listeners.Add(item);
			ILogListener logListener = Logger.Listeners.FirstOrDefault((ILogListener logger) => logger is ConsoleLogListener);
			if (logListener != null)
			{
				Logger.Listeners.Remove(logListener);
			}
			ManualLogSource manualLogSource = Logger.CreateLogSource("Preloader");
			foreach (LogEventArgs preloaderLogEvent in preloaderLogEvents)
			{
				Logger.InternalLogEvent(manualLogSource, preloaderLogEvent);
			}
			Logger.Sources.Remove(manualLogSource);
			Logger.Listeners.Remove(item);
			if (logListener != null)
			{
				Logger.Listeners.Add(logListener);
			}
		}

		public static PluginInfo ToPluginInfo(TypeDefinition type)
		{
			if (type.IsInterface || type.IsAbstract)
			{
				return null;
			}
			try
			{
				if (!type.IsSubtypeOf(typeof(BaseUnityPlugin)))
				{
					return null;
				}
			}
			catch (AssemblyResolutionException)
			{
				return null;
			}
			BepInPlugin bepInPlugin = BepInPlugin.FromCecilType(type);
			if (bepInPlugin == null)
			{
				Logger.LogWarning("Skipping over type [" + ((MemberReference)type).FullName + "] as no metadata attribute is specified");
				return null;
			}
			if (string.IsNullOrEmpty(bepInPlugin.GUID) || !allowedGuidRegex.IsMatch(bepInPlugin.GUID))
			{
				Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its GUID [" + bepInPlugin.GUID + "] is of an illegal format.");
				return null;
			}
			if (bepInPlugin.Version == null)
			{
				Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its version is invalid.");
				return null;
			}
			if (bepInPlugin.Name == null)
			{
				Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its name is null.");
				return null;
			}
			List<BepInProcess> processes = BepInProcess.FromCecilType(type);
			IEnumerable<BepInDependency> dependencies = BepInDependency.FromCecilType(type);
			IEnumerable<BepInIncompatibility> incompatibilities = BepInIncompatibility.FromCecilType(type);
			AssemblyNameReference? obj = ((IEnumerable<AssemblyNameReference>)((MemberReference)type).Module.AssemblyReferences).FirstOrDefault((Func<AssemblyNameReference, bool>)((AssemblyNameReference reference) => reference.Name == "BepInEx"));
			Version targettedBepInExVersion = ((obj != null) ? obj.Version : null) ?? new Version();
			return new PluginInfo
			{
				Metadata = bepInPlugin,
				Processes = processes,
				Dependencies = dependencies,
				Incompatibilities = incompatibilities,
				TypeName = ((MemberReference)type).FullName,
				TargettedBepInExVersion = targettedBepInExVersion
			};
		}

		private static bool HasBepinPlugins(AssemblyDefinition ass)
		{
			if (((IEnumerable<AssemblyNameReference>)ass.MainModule.AssemblyReferences).All((AssemblyNameReference r) => r.Name != CurrentAssemblyName))
			{
				return false;
			}
			if (ass.MainModule.GetTypeReferences().All((TypeReference r) => ((MemberReference)r).FullName != typeof(BepInPlugin).FullName))
			{
				return false;
			}
			return true;
		}

		private static bool PluginTargetsWrongBepin(PluginInfo pluginInfo)
		{
			Version targettedBepInExVersion = pluginInfo.TargettedBepInExVersion;
			if (targettedBepInExVersion.Major != CurrentAssemblyVersion.Major)
			{
				return true;
			}
			if (targettedBepInExVersion.Minor > CurrentAssemblyVersion.Minor)
			{
				return true;
			}
			if (targettedBepInExVersion.Minor < CurrentAssemblyVersion.Minor)
			{
				return false;
			}
			return targettedBepInExVersion.Build > CurrentAssemblyVersion.Build;
		}

		public static void Start()
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			if (_loaded)
			{
				return;
			}
			if (!_initialized)
			{
				throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
			}
			if (!Directory.Exists(Paths.PluginPath))
			{
				Directory.CreateDirectory(Paths.PluginPath);
			}
			if (!Directory.Exists(Paths.PatcherPluginPath))
			{
				Directory.CreateDirectory(Paths.PatcherPluginPath);
			}
			try
			{
				PropertyInfo property = typeof(Application).GetProperty("productName", BindingFlags.Static | BindingFlags.Public);
				if (ConsoleManager.ConsoleActive)
				{
					ConsoleManager.SetConsoleTitle($"{CurrentAssemblyName} {CurrentAssemblyVersion} - {property?.GetValue(null, null) ?? Paths.ProcessName}");
				}
				Logger.LogMessage("Chainloader started");
				ManagerObject = new GameObject("BepInEx_Manager");
				if (ConfigHideBepInExGOs.Value)
				{
					((Object)ManagerObject).hideFlags = (HideFlags)61;
				}
				Object.DontDestroyOnLoad((Object)(object)ManagerObject);
				Dictionary<string, List<PluginInfo>> dictionary = TypeLoader.FindPluginTypes(Paths.PluginPath, ToPluginInfo, HasBepinPlugins, "chainloader");
				foreach (KeyValuePair<string, List<PluginInfo>> item in dictionary)
				{
					foreach (PluginInfo item2 in item.Value)
					{
						item2.Location = item.Key;
					}
				}
				List<PluginInfo> list = dictionary.SelectMany((KeyValuePair<string, List<PluginInfo>> p) => p.Value).ToList();
				Dictionary<string, Assembly> dictionary2 = new Dictionary<string, Assembly>();
				Logger.LogInfo(string.Format("{0} plugin{1} to load", list.Count, (PluginInfos.Count == 1) ? "" : "s"));
				SortedDictionary<string, IEnumerable<string>> dependencyDict = new SortedDictionary<string, IEnumerable<string>>(StringComparer.InvariantCultureIgnoreCase);
				Dictionary<string, PluginInfo> pluginsByGUID = new Dictionary<string, PluginInfo>();
				foreach (IGrouping<string, PluginInfo> item3 in from info in list
					group info by info.Metadata.GUID)
				{
					PluginInfo pluginInfo = null;
					foreach (PluginInfo item4 in item3.OrderByDescending((PluginInfo x) => x.Metadata.Version))
					{
						if (pluginInfo != null)
						{
							Logger.LogWarning($"Skipping [{item4}] because a newer version exists ({pluginInfo})");
							continue;
						}
						List<BepInProcess> list2 = item4.Processes.ToList();
						if (list2.Count != 0 && list2.All((BepInProcess x) => !string.Equals(x.ProcessName.Replace(".exe", ""), Paths.ProcessName, StringComparison.InvariantCultureIgnoreCase)))
						{
							Logger.LogWarning(string.Format("Skipping [{0}] because of process filters ({1})", item4, string.Join(", ", item4.Processes.Select((BepInProcess p) => p.ProcessName).ToArray())));
							continue;
						}
						pluginInfo = item4;
						dependencyDict[item4.Metadata.GUID] = item4.Dependencies.Select((BepInDependency d) => d.DependencyGUID);
						pluginsByGUID[item4.Metadata.GUID] = item4;
					}
				}
				foreach (PluginInfo item5 in pluginsByGUID.Values.ToList())
				{
					if (item5.Incompatibilities.Any((BepInIncompatibility incompatibility) => pluginsByGUID.ContainsKey(incompatibility.IncompatibilityGUID)))
					{
						pluginsByGUID.Remove(item5.Metadata.GUID);
						dependencyDict.Remove(item5.Metadata.GUID);
						string[] value = (from x in item5.Incompatibilities
							select x.IncompatibilityGUID into x
							where pluginsByGUID.ContainsKey(x)
							select x).ToArray();
						string text = string.Format("Could not load [{0}] because it is incompatible with: {1}", item5, string.Join(", ", value));
						DependencyErrors.Add(text);
						Logger.LogError(text);
					}
					else if (PluginTargetsWrongBepin(item5))
					{
						string text2 = $"Plugin [{item5}] targets a wrong version of BepInEx ({item5.TargettedBepInExVersion}) and might not work until you update";
						DependencyErrors.Add(text2);
						Logger.LogWarning(text2);
					}
				}
				string[] emptyDependencies = new string[0];
				IEnumerable<string> value5;
				List<string> list3 = Utility.TopologicalSort(dependencyDict.Keys, (string x) => (!dependencyDict.TryGetValue(x, out value5)) ? emptyDependencies : value5).ToList();
				HashSet<string> hashSet = new HashSet<string>();
				Dictionary<string, Version> dictionary3 = new Dictionary<string, Version>();
				foreach (string item6 in list3)
				{
					if (!pluginsByGUID.TryGetValue(item6, out var value2))
					{
						continue;
					}
					bool flag = false;
					List<BepInDependency> list4 = new List<BepInDependency>();
					foreach (BepInDependency dependency in value2.Dependencies)
					{
						if (!dictionary3.TryGetValue(dependency.DependencyGUID, out var value3) || value3 < dependency.MinimumVersion)
						{
							if (IsHardDependency(dependency))
							{
								list4.Add(dependency);
							}
						}
						else if (hashSet.Contains(dependency.DependencyGUID) && IsHardDependency(dependency))
						{
							flag = true;
							break;
						}
					}
					dictionary3.Add(item6, value2.Metadata.Version);
					if (flag)
					{
						string text3 = $"Skipping [{value2}] because it has a dependency that was not loaded. See previous errors for details.";
						DependencyErrors.Add(text3);
						Logger.LogWarning(text3);
						continue;
					}
					if (list4.Count != 0)
					{
						string text4 = string.Format("Could not load [{0}] because it has missing dependencies: {1}", value2, string.Join(", ", list4.Select((BepInDependency s) => (!IsEmptyVersion(s.MinimumVersion)) ? $"{s.DependencyGUID} (v{s.MinimumVersion} or newer)" : s.DependencyGUID).ToArray()));
						DependencyErrors.Add(text4);
						Logger.LogError(text4);
						hashSet.Add(item6);
						continue;
					}
					try
					{
						Logger.LogInfo($"Loading [{value2}]");
						if (!dictionary2.TryGetValue(value2.Location, out var value4))
						{
							value4 = (dictionary2[value2.Location] = Assembly.LoadFile(value2.Location));
						}
						PluginInfos[item6] = value2;
						value2.Instance = (BaseUnityPlugin)(object)ManagerObject.AddComponent(value4.GetType(value2.TypeName));
						_plugins.Add(value2.Instance);
					}
					catch (Exception ex)
					{
						hashSet.Add(item6);
						PluginInfos.Remove(item6);
						Logger.LogError($"Error loading [{value2}] : {ex.Message}");
						if (ex is ReflectionTypeLoadException ex2)
						{
							Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(ex2));
						}
						else
						{
							Logger.LogDebug(ex);
						}
					}
				}
			}
			catch (Exception ex3)
			{
				try
				{
					ConsoleManager.CreateConsole();
				}
				catch
				{
				}
				Logger.LogFatal("Error occurred starting the game");
				Logger.LogFatal(ex3.ToString());
			}
			Logger.LogMessage("Chainloader startup complete");
			_loaded = true;
			static bool IsEmptyVersion(Version v)
			{
				if (v.Major == 0 && v.Minor == 0 && v.Build <= 0)
				{
					return v.Revision <= 0;
				}
				return false;
			}
			static bool IsHardDependency(BepInDependency dep)
			{
				return (dep.Flags & BepInDependency.DependencyFlags.HardDependency) != 0;
			}
		}
	}
	public interface ICacheable
	{
		void Save(BinaryWriter bw);

		void Load(BinaryReader br);
	}
	public class CachedAssembly<T> where T : ICacheable
	{
		public List<T> CacheItems { get; set; }

		public long Timestamp { get; set; }
	}
	public static class TypeLoader
	{
		public static readonly DefaultAssemblyResolver Resolver;

		public static readonly ReaderParameters ReaderParameters;

		[CompilerGenerated]
		private static AssemblyResolveEventHandler m_AssemblyResolve;

		private static readonly ConfigEntry<bool> EnableAssemblyCache;

		public static event AssemblyResolveEventHandler AssemblyResolve
		{
			[CompilerGenerated]
			add
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Expected O, but got Unknown
				AssemblyResolveEventHandler val = TypeLoader.m_AssemblyResolve;
				AssemblyResolveEventHandler val2;
				do
				{
					val2 = val;
					AssemblyResolveEventHandler value2 = (AssemblyResolveEventHandler)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref TypeLoader.m_AssemblyResolve, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Expected O, but got Unknown
				AssemblyResolveEventHandler val = TypeLoader.m_AssemblyResolve;
				AssemblyResolveEventHandler val2;
				do
				{
					val2 = val;
					AssemblyResolveEventHandler value2 = (AssemblyResolveEventHandler)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref TypeLoader.m_AssemblyResolve, value2, val2);
				}
				while (val != val2);
			}
		}

		static TypeLoader()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			EnableAssemblyCache = ConfigFile.CoreConfig.Bind("Caching", "EnableAssemblyCache", defaultValue: true, "Enable/disable assembly metadata cache\nEnabling this will speed up discovery of plugins and patchers by caching the metadata of all types BepInEx discovers.");
			Resolver = new DefaultAssemblyResolver();
			ReaderParameters = new ReaderParameters
			{
				AssemblyResolver = (IAssemblyResolver)(object)Resolver
			};
			((BaseAssemblyResolver)Resolver).ResolveFailure += (AssemblyResolveEventHandler)delegate(object sender, AssemblyNameReference reference)
			{
				if (!Utility.TryParseAssemblyName(reference.FullName, out var assemblyName))
				{
					AssemblyResolveEventHandler assemblyResolve = TypeLoader.AssemblyResolve;
					if (assemblyResolve == null)
					{
						return null;
					}
					return assemblyResolve.Invoke(sender, reference);
				}
				foreach (string item in new string[3]
				{
					Paths.BepInExAssemblyDirectory,
					Paths.PluginPath,
					Paths.PatcherPluginPath
				}.Concat(Paths.DllSearchPaths))
				{
					if (Utility.TryResolveDllAssembly(assemblyName, item, ReaderParameters, out var assembly))
					{
						return assembly;
					}
				}
				AssemblyResolveEventHandler assemblyResolve2 = TypeLoader.AssemblyResolve;
				return (assemblyResolve2 == null) ? null : assemblyResolve2.Invoke(sender, reference);
			};
		}

		public static Dictionary<string, List<T>> FindPluginTypes<T>(string directory, Func<TypeDefinition, T> typeSelector, Func<AssemblyDefinition, bool> assemblyFilter = null, string cacheName = null) where T : ICacheable, new()
		{
			Dictionary<string, List<T>> dictionary = new Dictionary<string, List<T>>();
			Dictionary<string, CachedAssembly<T>> dictionary2 = null;
			if (cacheName != null)
			{
				dictionary2 = LoadAssemblyCache<T>(cacheName);
			}
			string[] files = Directory.GetFiles(Path.GetFullPath(directory), "*.dll", SearchOption.AllDirectories);
			foreach (string text in files)
			{
				try
				{
					if (dictionary2 != null && dictionary2.TryGetValue(text, out var value) && File.GetLastWriteTimeUtc(text).Ticks == value.Timestamp)
					{
						dictionary[text] = value.CacheItems;
						continue;
					}
					AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text, ReaderParameters);
					if (assemblyFilter != null && !assemblyFilter(val))
					{
						dictionary[text] = new List<T>();
						val.Dispose();
						continue;
					}
					List<T> value2 = (from t in ((IEnumerable<TypeDefinition>)val.MainModule.Types).Select(typeSelector)
						where t != null
						select t).ToList();
					dictionary[text] = value2;
					val.Dispose();
				}
				catch (BadImageFormatException ex)
				{
					Logger.LogDebug("Skipping loading " + text + " because it's not a valid .NET assembly. Full error: " + ex.Message);
				}
				catch (Exception ex2)
				{
					Logger.LogError(ex2.ToString());
				}
			}
			if (cacheName != null)
			{
				SaveAssemblyCache(cacheName, dictionary);
			}
			return dictionary;
		}

		public static Dictionary<string, CachedAssembly<T>> LoadAssemblyCache<T>(string cacheName) where T : ICacheable, new()
		{
			if (!EnableAssemblyCache.Value)
			{
				return null;
			}
			Dictionary<string, CachedAssembly<T>> dictionary = new Dictionary<string, CachedAssembly<T>>();
			try
			{
				string path = Path.Combine(Paths.CachePath, cacheName + "_typeloader.dat");
				if (!File.Exists(path))
				{
					return null;
				}
				using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path));
				int num = binaryReader.ReadInt32();
				for (int i = 0; i < num; i++)
				{
					string key = binaryReader.ReadString();
					long timestamp = binaryReader.ReadInt64();
					int num2 = binaryReader.ReadInt32();
					List<T> list = new List<T>();
					for (int j = 0; j < num2; j++)
					{
						T item = new T();
						item.Load(binaryReader);
						list.Add(item);
					}
					dictionary[key] = new CachedAssembly<T>
					{
						Timestamp = timestamp,
						CacheItems = list
					};
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning("Failed to load cache \"" + cacheName + "\"; skipping loading cache. Reason: " + ex.Message + ".");
			}
			return dictionary;
		}

		public static void SaveAssemblyCache<T>(string cacheName, Dictionary<string, List<T>> entries) where T : ICacheable
		{
			if (!EnableAssemblyCache.Value)
			{
				return;
			}
			try
			{
				if (!Directory.Exists(Paths.CachePath))
				{
					Directory.CreateDirectory(Paths.CachePath);
				}
				using BinaryWriter binaryWriter = new BinaryWriter(File.OpenWrite(Path.Combine(Paths.CachePath, cacheName + "_typeloader.dat")));
				binaryWriter.Write(entries.Count);
				foreach (KeyValuePair<string, List<T>> entry in entries)
				{
					binaryWriter.Write(entry.Key);
					binaryWriter.Write(File.GetLastWriteTimeUtc(entry.Key).Ticks);
					binaryWriter.Write(entry.Value.Count);
					foreach (T item in entry.Value)
					{
						item.Save(binaryWriter);
					}
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning("Failed to save cache \"" + cacheName + "\"; skipping saving cache. Reason: " + ex.Message + ".");
			}
		}

		public static string TypeLoadExceptionToString(ReflectionTypeLoadException ex)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Exception[] loaderExceptions = ex.LoaderExceptions;
			foreach (Exception ex2 in loaderExceptions)
			{
				stringBuilder.AppendLine(ex2.Message);
				if (ex2 is FileNotFoundException ex3)
				{
					if (!string.IsNullOrEmpty(ex3.FusionLog))
					{
						stringBuilder.AppendLine("Fusion Log:");
						stringBuilder.AppendLine(ex3.FusionLog);
					}
				}
				else if (ex2 is FileLoadException ex4 && !string.IsNullOrEmpty(ex4.FusionLog))
				{
					stringBuilder.AppendLine("Fusion Log:");
					stringBuilder.AppendLine(ex4.FusionLog);
				}
				stringBuilder.AppendLine();
			}
			return stringBuilder.ToString();
		}
	}
}
namespace BepInEx.ConsoleUtil
{
	internal class Kon
	{
		private struct CONSOLE_SCREEN_BUFFER_INFO
		{
			internal COORD dwSize;

			internal COORD dwCursorPosition;

			internal short wAttributes;

			internal SMALL_RECT srWindow;

			internal COORD dwMaximumWindowSize;
		}

		private struct COORD
		{
			internal short X;

			internal short Y;
		}

		private struct SMALL_RECT
		{
			internal short Left;

			internal short Top;

			internal short Right;

			internal short Bottom;
		}

		private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);

		internal static IntPtr conOut = IntPtr.Zero;

		public static ConsoleColor ForegroundColor
		{
			get
			{
				return GetConsoleColor(isBackground: false);
			}
			set
			{
				SetConsoleColor(isBackground: false, value);
			}
		}

		public static ConsoleColor BackgroundColor
		{
			get
			{
				return GetConsoleColor(isBackground: true);
			}
			set
			{
				SetConsoleColor(isBackground: true, value);
			}
		}

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, short attributes);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr GetStdHandle(int nStdHandle);

		private static short ConsoleColorToColorAttribute(short color, bool isBackground)
		{
			if (((uint)color & 0xFFFFFFF0u) != 0)
			{
				throw new ArgumentException("Arg_InvalidConsoleColor");
			}
			if (isBackground)
			{
				color <<= 4;
			}
			return color;
		}

		private static CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(bool throwOnNoConsole, out bool succeeded)
		{
			succeeded = false;
			if (!(conOut == INVALID_HANDLE_VALUE))
			{
				if (!GetConsoleScreenBufferInfo(conOut, out var lpConsoleScreenBufferInfo))
				{
					bool consoleScreenBufferInfo = GetConsoleScreenBufferInfo(GetStdHandle(-12), out lpConsoleScreenBufferInfo);
					if (!consoleScreenBufferInfo)
					{
						consoleScreenBufferInfo = GetConsoleScreenBufferInfo(GetStdHandle(-10), out lpConsoleScreenBufferInfo);
					}
					if (!consoleScreenBufferInfo && Marshal.GetLastWin32Error() == 6 && !throwOnNoConsole)
					{
						return default(CONSOLE_SCREEN_BUFFER_INFO);
					}
				}
				succeeded = true;
				return lpConsoleScreenBufferInfo;
			}
			if (!throwOnNoConsole)
			{
				return default(CONSOLE_SCREEN_BUFFER_INFO);
			}
			throw new Exception("IO.IO_NoConsole");
		}

		private static void SetConsoleColor(bool isBackground, ConsoleColor c)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			((CodeAccessPermission)new UIPermission((UIPermissionWindow)2)).Demand();
			short num = ConsoleColorToColorAttribute((short)c, isBackground);
			bool succeeded;
			CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole: false, out succeeded);
			if (succeeded)
			{
				short wAttributes = bufferInfo.wAttributes;
				wAttributes &= (short)(isBackground ? (-241) : (-16));
				wAttributes = (short)((ushort)wAttributes | (ushort)num);
				SetConsoleTextAttribute(conOut, wAttributes);
			}
		}

		private static ConsoleColor GetConsoleColor(bool isBackground)
		{
			bool succeeded;
			CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole: false, out succeeded);
			if (!succeeded)
			{
				if (!isBackground)
				{
					return ConsoleColor.Gray;
				}
				return ConsoleColor.Black;
			}
			return ColorAttributeToConsoleCo

BooBoo Building/BepInEx/core/BepInEx.Harmony.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("BepInEx.Harmony")]
[assembly: AssemblyDescription("Harmony wrapper for BepInEx")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BepInEx.Harmony")]
[assembly: AssemblyCopyright("Copyright © Bepis 2019")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("54161cfe-ff42-4dde-b161-3a49545db5cd")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyVersion("2.0.0.0")]
namespace BepInEx.Harmony;

[AttributeUsage(AttributeTargets.Method)]
[Obsolete("Use HarmonyLib.ParameterByRefAttribute directly", true)]
public class ParameterByRefAttribute : ParameterByRefAttribute
{
	public int[] ParameterIndices => ((ParameterByRefAttribute)this).ParameterIndices;

	public ParameterByRefAttribute(params int[] parameterIndices)
		: base(parameterIndices)
	{
	}
}
public static class HarmonyExtensions
{
	[Obsolete("Use HarmonyLib.Harmony.PatchAll directly", true)]
	public static void PatchAll(this Harmony harmonyInstance, Type type)
	{
		HarmonyWrapper.PatchAll(type, harmonyInstance);
	}
}
public class HarmonyWrapper
{
	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll or HarmonyLib.Harmony.PatchAll", true)]
	public static Harmony PatchAll(Type type, Harmony harmonyInstance = null)
	{
		if (harmonyInstance == null)
		{
			return Harmony.CreateAndPatchAll(type, (string)null);
		}
		harmonyInstance.PatchAll(type);
		return harmonyInstance;
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll", true)]
	public static Harmony PatchAll(Type type, string harmonyInstanceId)
	{
		return Harmony.CreateAndPatchAll(type, harmonyInstanceId);
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll or HarmonyLib.Harmony.PatchAll", true)]
	public static Harmony PatchAll(Assembly assembly, Harmony harmonyInstance = null)
	{
		return assembly.GetTypes().Aggregate(harmonyInstance, (Harmony current, Type type) => PatchAll(type, current));
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll", true)]
	public static Harmony PatchAll(Assembly assembly, string harmonyInstanceId)
	{
		return Harmony.CreateAndPatchAll(assembly, harmonyInstanceId);
	}

	[Obsolete("Use HarmonyLib.Harmony.PatchAll with no arguments", true)]
	public static Harmony PatchAll(Harmony harmonyInstance = null)
	{
		return PatchAll(Assembly.GetCallingAssembly(), harmonyInstance);
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), ...)", true)]
	public static Harmony PatchAll(string harmonyInstanceId)
	{
		return PatchAll(Assembly.GetCallingAssembly(), harmonyInstanceId);
	}

	[Obsolete("Use HarmonyLib.Transpilers.EmitDelegate instead", true)]
	public static CodeInstruction EmitDelegate<T>(T action) where T : Delegate
	{
		return Transpilers.EmitDelegate<T>(action);
	}
}

BooBoo Building/BepInEx/core/BepInEx.Preloader.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.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Preloader.Patching;
using BepInEx.Preloader.RuntimeFixes;
using HarmonyLib;
using HarmonyXInterop;
using Mono.Cecil;
using Mono.Cecil.Cil;
using MonoMod.RuntimeDetour;
using MonoMod.RuntimeDetour.Platforms;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("BepInEx.Preloader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BepInEx.Preloader")]
[assembly: AssemblyCopyright("Copyright ©  2019")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("f7abbe07-c02f-4f7c-bf6e-c6656bf588ca")]
[assembly: AssemblyFileVersion("5.4.21.0")]
[assembly: AssemblyVersion("5.4.21.0")]
namespace BepInEx.Preloader
{
	public static class EnvVars
	{
		public static string DOORSTOP_INVOKE_DLL_PATH { get; private set; }

		public static string DOORSTOP_MANAGED_FOLDER_DIR { get; private set; }

		public static string DOORSTOP_PROCESS_PATH { get; private set; }

		public static string[] DOORSTOP_DLL_SEARCH_DIRS { get; private set; }

		internal static void LoadVars()
		{
			DOORSTOP_INVOKE_DLL_PATH = Environment.GetEnvironmentVariable("DOORSTOP_INVOKE_DLL_PATH");
			DOORSTOP_MANAGED_FOLDER_DIR = Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR");
			DOORSTOP_PROCESS_PATH = Environment.GetEnvironmentVariable("DOORSTOP_PROCESS_PATH");
			DOORSTOP_DLL_SEARCH_DIRS = Environment.GetEnvironmentVariable("DOORSTOP_DLL_SEARCH_DIRS")?.Split(new char[1] { Path.PathSeparator }) ?? new string[0];
		}
	}
	internal static class PreloaderRunner
	{
		private static readonly string[] CriticalAssemblies = new string[7] { "Mono.Cecil.dll", "Mono.Cecil.Mdb.dll", "Mono.Cecil.Pdb.dll", "Mono.Cecil.Rocks.dll", "MonoMod.Utils.dll", "MonoMod.RuntimeDetour.dll", "0Harmony.dll" };

		private static void LoadCriticalAssemblies()
		{
			string[] criticalAssemblies = CriticalAssemblies;
			foreach (string path in criticalAssemblies)
			{
				try
				{
					Assembly.LoadFile(Path.Combine(Paths.BepInExAssemblyDirectory, path));
				}
				catch (Exception)
				{
				}
			}
		}

		public static void PreloaderPreMain()
		{
			PlatformUtils.SetPlatform();
			string text = Utility.ParentDirectory(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH), 2);
			Paths.SetExecutablePath(EnvVars.DOORSTOP_PROCESS_PATH, text, EnvVars.DOORSTOP_MANAGED_FOLDER_DIR, EnvVars.DOORSTOP_DLL_SEARCH_DIRS);
			LoadCriticalAssemblies();
			AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
			AppDomain.CurrentDomain.AssemblyResolve -= Entrypoint.ResolveCurrentDirectory;
			PreloaderMain();
		}

		private static void PreloaderMain()
		{
			if (Preloader.ConfigApplyRuntimePatches.Value)
			{
				XTermFix.Apply();
				ConsoleSetOutFix.Apply();
			}
			Preloader.Run();
		}

		private static Assembly LocalResolve(object sender, ResolveEventArgs args)
		{
			AssemblyName assemblyName = default(AssemblyName);
			if (!Utility.TryParseAssemblyName(args.Name, ref assemblyName))
			{
				return null;
			}
			AssemblyName assemblyName2 = default(AssemblyName);
			var source = (from a in AppDomain.CurrentDomain.GetAssemblies()
				select new
				{
					assembly = a,
					name = (Utility.TryParseAssemblyName(a.FullName, ref assemblyName2) ? assemblyName2 : null)
				} into a
				where a.name != null && a.name.Name == assemblyName.Name
				orderby a.name.Version descending
				select a).ToList();
			Assembly assembly = (source.FirstOrDefault(a => a.name.Version == assemblyName.Version) ?? source.FirstOrDefault())?.assembly;
			if ((object)assembly != null)
			{
				return assembly;
			}
			if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, ref assembly) || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, ref assembly) || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, ref assembly))
			{
				return assembly;
			}
			return null;
		}
	}
	internal static class Entrypoint
	{
		private static string preloaderPath;

		public static void Main()
		{
			string text = $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log";
			try
			{
				EnvVars.LoadVars();
				text = Path.Combine(Path.GetDirectoryName(EnvVars.DOORSTOP_PROCESS_PATH) ?? ".", text);
				preloaderPath = Path.GetDirectoryName(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH));
				AppDomain.CurrentDomain.AssemblyResolve += ResolveCurrentDirectory;
				typeof(Entrypoint).Assembly.GetType("BepInEx.Preloader.PreloaderRunner")?.GetMethod("PreloaderPreMain")?.Invoke(null, null);
			}
			catch (Exception ex)
			{
				File.WriteAllText(text, ex.ToString());
			}
			finally
			{
				AppDomain.CurrentDomain.AssemblyResolve -= ResolveCurrentDirectory;
			}
		}

		internal static Assembly ResolveCurrentDirectory(object sender, ResolveEventArgs args)
		{
			AssemblyName assemblyName = new AssemblyName(args.Name);
			try
			{
				return Assembly.LoadFile(Path.Combine(preloaderPath, assemblyName.Name + ".dll"));
			}
			catch (Exception)
			{
				return null;
			}
		}
	}
	internal static class PlatformUtils
	{
		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct utsname_osx
		{
			private const int osx_utslen = 256;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string sysname;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string nodename;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string release;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string version;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string machine;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct utsname_linux
		{
			private const int linux_utslen = 65;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string sysname;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string nodename;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string release;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string version;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string machine;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string domainname;
		}

		[DllImport("libc.so.6", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "uname")]
		private static extern IntPtr uname_linux(ref utsname_linux utsname);

		[DllImport("/usr/lib/libSystem.dylib", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "uname")]
		private static extern IntPtr uname_osx(ref utsname_osx utsname);

		public static void SetPlatform()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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_00d1: 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_00eb: 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_012d: 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_013a: 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_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: 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_0162: 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_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: 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_01d2: 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)
			Platform val = (Platform)17;
			PropertyInfo property = typeof(Environment).GetProperty("Platform", BindingFlags.Static | BindingFlags.NonPublic);
			string text = (((object)property == null) ? Environment.OSVersion.Platform.ToString() : property.GetValue(null, new object[0]).ToString());
			text = text.ToLowerInvariant();
			if (text.Contains("win"))
			{
				val = (Platform)37;
			}
			else if (text.Contains("mac") || text.Contains("osx"))
			{
				val = (Platform)73;
			}
			else if (text.Contains("lin") || text.Contains("unix"))
			{
				val = (Platform)137;
			}
			if (Is(val, (Platform)137) && Directory.Exists("/data") && File.Exists("/system/build.prop"))
			{
				val = (Platform)393;
			}
			else if (Is(val, (Platform)8) && Directory.Exists("/System/Library/AccessibilityBundles"))
			{
				val = (Platform)585;
			}
			MethodInfo methodInfo = typeof(Environment).GetProperty("Is64BitOperatingSystem")?.GetGetMethod();
			val = (Platform)(((object)methodInfo == null) ? (val | ((IntPtr.Size >= 8) ? 2 : 0)) : (val | (((bool)methodInfo.Invoke(null, new object[0])) ? 2 : 0)));
			if ((Is(val, (Platform)73) || Is(val, (Platform)137)) && (object)Type.GetType("Mono.Runtime") != null)
			{
				IntPtr intPtr;
				string machine;
				if (Is(val, (Platform)73))
				{
					utsname_osx utsname = default(utsname_osx);
					intPtr = uname_osx(ref utsname);
					machine = utsname.machine;
				}
				else
				{
					utsname_linux utsname2 = default(utsname_linux);
					intPtr = uname_linux(ref utsname2);
					machine = utsname2.machine;
				}
				if (intPtr == IntPtr.Zero && (machine.StartsWith("aarch") || machine.StartsWith("arm")))
				{
					val = (Platform)(val | 0x10000);
				}
			}
			else
			{
				typeof(object).Module.GetPEKind(out var _, out var machine2);
				if (machine2 == ImageFileMachine.ARM)
				{
					val = (Platform)(val | 0x10000);
				}
			}
			PlatformHelper.Current = val;
		}

		private static bool Is(Platform current, Platform expected)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return (Platform)(current & expected) == expected;
		}
	}
	internal static class Preloader
	{
		private enum MonoModBackend
		{
			[Description("Auto")]
			auto,
			[Description("DynamicMethod")]
			dynamicmethod,
			[Description("MethodBuilder")]
			methodbuilder,
			[Description("Cecil")]
			cecil
		}

		private static readonly ConfigEntry<string> ConfigEntrypointAssembly = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Assembly", IsPostUnity2017 ? "UnityEngine.CoreModule.dll" : "UnityEngine.dll", "The local filename of the assembly to target.");

		private static readonly ConfigEntry<string> ConfigEntrypointType = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Type", "Application", "The name of the type in the entrypoint assembly to search for the entrypoint method.");

		private static readonly ConfigEntry<string> ConfigEntrypointMethod = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Method", ".cctor", "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from.");

		internal static readonly ConfigEntry<bool> ConfigApplyRuntimePatches = ConfigFile.CoreConfig.Bind<bool>("Preloader", "ApplyRuntimePatches", true, "Enables or disables runtime patches.\nThis should always be true, unless you cannot start the game due to a Harmony related issue (such as running .NET Standard runtime) or you know what you're doing.");

		private static readonly ConfigEntry<MonoModBackend> HarmonyBackend = ConfigFile.CoreConfig.Bind<MonoModBackend>("Preloader", "HarmonyBackend", MonoModBackend.auto, "Specifies which MonoMod backend to use for Harmony patches. Auto uses the best available backend.\nThis setting should only be used for development purposes (e.g. debugging in dnSpy). Other code might override this setting.");

		private static PreloaderConsoleListener PreloaderLog { get; set; }

		public static bool IsPostUnity2017 { get; } = File.Exists(Path.Combine(Paths.ManagedPath, "UnityEngine.CoreModule.dll"));


		public static void Run()
		{
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				InitializeHarmony();
				HarmonyInteropFix.Apply();
				ConsoleManager.Initialize(false);
				AllocateConsole();
				Exception ex = default(Exception);
				Utility.TryDo((Action)delegate
				{
					if (ConfigApplyRuntimePatches.Value)
					{
						UnityPatches.Apply();
					}
				}, ref ex);
				Logger.InitializeInternalLoggers();
				Logger.Sources.Add(TraceLogSource.CreateSource());
				PreloaderLog = new PreloaderConsoleListener();
				Logger.Listeners.Add((ILogListener)(object)PreloaderLog);
				Version version = typeof(Paths).Assembly.GetName().Version;
				string text = $"BepInEx {version} - {Paths.ProcessName}";
				if (ConsoleManager.ConsoleActive)
				{
					ConsoleManager.SetConsoleTitle(text);
				}
				Logger.LogMessage((object)$"{text} ({File.GetLastWriteTime(Paths.ExecutablePath)})");
				object[] customAttributes = typeof(BuildInfoAttribute).Assembly.GetCustomAttributes(typeof(BuildInfoAttribute), inherit: false);
				if (customAttributes.Length != 0)
				{
					Logger.LogMessage((object)((BuildInfoAttribute)customAttributes[0]).Info);
				}
				Logger.LogInfo((object)("Running under Unity v" + GetUnityVersion()));
				Logger.LogInfo((object)$"CLR runtime version: {Environment.Version}");
				Logger.LogInfo((object)$"Supports SRE: {Utility.CLRSupportsDynamicAssemblies}");
				Logger.LogInfo((object)$"System platform: {PlatformHelper.Current}");
				if (ex != null)
				{
					Logger.LogWarning((object)("Failed to apply runtime patches for Mono. See more info in the output log. Error message: " + ex.Message));
				}
				Logger.LogMessage((object)"Preloader started");
				AssemblyPatcher.AddPatcher(new PatcherPlugin
				{
					TargetDLLs = () => new string[1] { ConfigEntrypointAssembly.Value },
					Patcher = PatchEntrypoint,
					TypeName = "BepInEx.Chainloader"
				});
				Logger.Log((LogLevel)16, (object)$"Loaded 1 patcher method from [BepInEx.Preloader {version}]");
				AssemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath);
				Logger.LogInfo((object)string.Format("{0} patcher plugin{1} loaded", AssemblyPatcher.PatcherPlugins.Count, (AssemblyPatcher.PatcherPlugins.Count == 1) ? "" : "s"));
				AssemblyPatcher.PatchAndLoad(Paths.DllSearchPaths);
				AssemblyPatcher.DisposePatchers();
				Logger.LogMessage((object)"Preloader finished");
				Logger.Listeners.Remove((ILogListener)(object)PreloaderLog);
				PreloaderLog.Dispose();
			}
			catch (Exception ex2)
			{
				try
				{
					Logger.LogFatal((object)"Could not run preloader!");
					Logger.LogFatal((object)ex2);
					if (!ConsoleManager.ConsoleActive)
					{
						AllocateConsole();
						Console.Write(PreloaderLog);
					}
				}
				catch
				{
				}
				string text2 = string.Empty;
				try
				{
					text2 = string.Join("\r\n", PreloaderConsoleListener.LogEvents.Select((LogEventArgs x) => ((object)x).ToString()).ToArray());
					text2 += "\r\n";
					PreloaderLog?.Dispose();
					PreloaderLog = null;
				}
				catch
				{
				}
				File.WriteAllText(Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"), text2 + ex2);
			}
		}

		public static void PatchEntrypoint(ref AssemblyDefinition assembly)
		{
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Expected O, but got Unknown
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0309: Unknown result type (might be due to invalid IL or missing references)
			if (((IEnumerable<AssemblyNameReference>)assembly.MainModule.AssemblyReferences).Any((AssemblyNameReference x) => x.Name.Contains("BepInEx")))
			{
				throw new Exception("BepInEx has been detected to be patched! Please unpatch before using a patchless variant!");
			}
			string entrypointType = ConfigEntrypointType.Value;
			string entrypointMethod = ConfigEntrypointMethod.Value;
			bool flag = Utility.IsNullOrWhiteSpace(entrypointMethod) || entrypointMethod == ".cctor";
			TypeDefinition val = ((IEnumerable<TypeDefinition>)assembly.MainModule.Types).FirstOrDefault((Func<TypeDefinition, bool>)((TypeDefinition x) => ((MemberReference)x).Name == entrypointType));
			if (val == null)
			{
				throw new Exception("The entrypoint type is invalid! Please check your config/BepInEx.cfg file");
			}
			AssemblyDefinition val2 = AssemblyDefinition.ReadAssembly(Paths.BepInExAssemblyPath);
			try
			{
				MethodDefinition val3 = ((IEnumerable<MethodDefinition>)((IEnumerable<TypeDefinition>)val2.MainModule.Types).First((TypeDefinition x) => ((MemberReference)x).Name == "Chainloader").Methods).First((MethodDefinition x) => ((MemberReference)x).Name == "Initialize");
				MethodDefinition val4 = ((IEnumerable<MethodDefinition>)((IEnumerable<TypeDefinition>)val2.MainModule.Types).First((TypeDefinition x) => ((MemberReference)x).Name == "Chainloader").Methods).First((MethodDefinition x) => ((MemberReference)x).Name == "Start");
				MethodReference val5 = assembly.MainModule.ImportReference((MethodReference)(object)val3);
				MethodReference val6 = assembly.MainModule.ImportReference((MethodReference)(object)val4);
				List<MethodDefinition> list = new List<MethodDefinition>();
				if (flag)
				{
					MethodDefinition val7 = ((IEnumerable<MethodDefinition>)val.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => m.IsConstructor && m.IsStatic));
					if (val7 == null)
					{
						val7 = new MethodDefinition(".cctor", (MethodAttributes)6289, assembly.MainModule.ImportReference(typeof(void)));
						val.Methods.Add(val7);
						ILProcessor iLProcessor = val7.Body.GetILProcessor();
						iLProcessor.Append(iLProcessor.Create(OpCodes.Ret));
					}
					list.Add(val7);
				}
				else
				{
					list.AddRange(((IEnumerable<MethodDefinition>)val.Methods).Where((MethodDefinition x) => ((MemberReference)x).Name == entrypointMethod));
				}
				if (!list.Any())
				{
					throw new Exception("The entrypoint method is invalid! Please check your config.ini");
				}
				foreach (MethodDefinition item in list)
				{
					ILProcessor iLProcessor2 = item.Body.GetILProcessor();
					Instruction val8 = ((IEnumerable<Instruction>)iLProcessor2.Body.Instructions).First();
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Ldnull));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Ldc_I4_0));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, assembly.MainModule.ImportReference((MethodBase)AccessTools.PropertyGetter(typeof(PreloaderConsoleListener), "LogEvents"))));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, val5));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, val6));
				}
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}

		public static void AllocateConsole()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			if (!ConsoleManager.ConsoleEnabled)
			{
				return;
			}
			try
			{
				ConsoleManager.CreateConsole();
				Logger.Listeners.Add((ILogListener)new ConsoleLogListener());
			}
			catch (Exception ex)
			{
				Logger.LogError((object)"Failed to allocate console!");
				Logger.LogError((object)ex);
			}
		}

		public static string GetUnityVersion()
		{
			if (PlatformHelper.Is((Platform)37))
			{
				return FileVersionInfo.GetVersionInfo(Paths.ExecutablePath).FileVersion;
			}
			return "Unknown (" + (IsPostUnity2017 ? "post" : "pre") + "-2017)";
		}

		private static void InitializeHarmony()
		{
			switch (HarmonyBackend.Value)
			{
			case MonoModBackend.dynamicmethod:
			case MonoModBackend.methodbuilder:
			case MonoModBackend.cecil:
				Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", HarmonyBackend.Value.ToString());
				break;
			default:
				throw new ArgumentOutOfRangeException("HarmonyBackend", HarmonyBackend.Value, "Unknown backend");
			case MonoModBackend.auto:
				break;
			}
		}
	}
	public class PreloaderConsoleListener : ILogListener, IDisposable
	{
		private static readonly ConfigEntry<LogLevel> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind<LogLevel>("Logging.Console", "LogLevels", (LogLevel)31, "Which log levels to show in the console output.");

		public static List<LogEventArgs> LogEvents { get; } = new List<LogEventArgs>();


		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			//IL_0001: 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_0010: Unknown result type (might be due to invalid IL or missing references)
			if ((eventArgs.Level & ConfigConsoleDisplayedLevel.Value) != 0)
			{
				LogEvents.Add(eventArgs);
			}
		}

		public void Dispose()
		{
		}
	}
}
namespace BepInEx.Preloader.RuntimeFixes
{
	internal static class ConsoleSetOutFix
	{
		private static LoggedTextWriter loggedTextWriter;

		internal static ManualLogSource ConsoleLogSource = Logger.CreateLogSource("Console");

		public static void Apply()
		{
			loggedTextWriter = new LoggedTextWriter
			{
				Parent = Console.Out
			};
			Console.SetOut(loggedTextWriter);
			Harmony.CreateAndPatchAll(typeof(ConsoleSetOutFix), (string)null);
		}

		[HarmonyPatch(typeof(Console), "SetOut")]
		[HarmonyPrefix]
		private static bool OnSetOut(TextWriter newOut)
		{
			loggedTextWriter.Parent = newOut;
			return false;
		}
	}
	internal class LoggedTextWriter : TextWriter
	{
		public override Encoding Encoding { get; } = Encoding.UTF8;


		public TextWriter Parent { get; set; }

		public override void Flush()
		{
			Parent.Flush();
		}

		public override void Write(string value)
		{
			ConsoleSetOutFix.ConsoleLogSource.LogInfo((object)value);
			Parent.Write(value);
		}

		public override void WriteLine(string value)
		{
			ConsoleSetOutFix.ConsoleLogSource.LogInfo((object)value);
			Parent.WriteLine(value);
		}
	}
	internal static class HarmonyInteropFix
	{
		public static void Apply()
		{
			HarmonyInterop.Initialize(Paths.CachePath);
			Harmony.CreateAndPatchAll(typeof(HarmonyInteropFix), "org.bepinex.fixes.harmonyinterop");
		}

		[HarmonyReversePatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPatch(typeof(Assembly), "LoadFile", new Type[] { typeof(string) })]
		private static Assembly LoadFile(string path)
		{
			return null;
		}

		[HarmonyPatch(typeof(Assembly), "LoadFile", new Type[] { typeof(string) })]
		[HarmonyPatch(typeof(Assembly), "LoadFrom", new Type[] { typeof(string) })]
		[HarmonyPrefix]
		private static bool OnAssemblyLoad(ref Assembly __result, string __0)
		{
			HarmonyInterop.TryShim(__0, Paths.GameRootPath, (Action<string>)Logger.LogWarning, TypeLoader.ReaderParameters);
			__result = LoadFile(__0);
			return true;
		}
	}
	internal static class TraceFix
	{
		private static Type TraceImplType;

		private static object ListenersSyncRoot;

		private static TraceListenerCollection Listeners;

		private static PropertyInfo prop_AutoFlush;

		private static bool AutoFlush => (bool)prop_AutoFlush.GetValue(null, null);

		public static void ApplyFix()
		{
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			TraceImplType = AppDomain.CurrentDomain.GetAssemblies().First((Assembly x) => x.GetName().Name == "System").GetTypes()
				.FirstOrDefault((Type x) => x.Name == "TraceImpl");
			if ((object)TraceImplType != null)
			{
				ListenersSyncRoot = AccessTools.Property(TraceImplType, "ListenersSyncRoot").GetValue(null, null);
				Listeners = (TraceListenerCollection)AccessTools.Property(TraceImplType, "Listeners").GetValue(null, null);
				prop_AutoFlush = AccessTools.Property(TraceImplType, "AutoFlush");
				new Harmony("com.bepis.bepinex.tracefix").Patch((MethodBase)typeof(Trace).GetMethod("DoTrace", BindingFlags.Static | BindingFlags.NonPublic), new HarmonyMethod(typeof(TraceFix).GetMethod("DoTraceReplacement", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool DoTraceReplacement(string kind, Assembly report, string message)
		{
			string source = string.Empty;
			try
			{
				source = report.GetName().Name;
			}
			catch (MethodAccessException)
			{
			}
			TraceEventType eventType = (TraceEventType)Enum.Parse(typeof(TraceEventType), kind);
			lock (ListenersSyncRoot)
			{
				foreach (TraceListener listener in Listeners)
				{
					listener.TraceEvent(new TraceEventCache(), source, eventType, 0, message);
					if (AutoFlush)
					{
						listener.Flush();
					}
				}
			}
			return false;
		}
	}
	internal static class UnityPatches
	{
		private static Harmony HarmonyInstance { get; set; }

		public static Dictionary<string, string> AssemblyLocations { get; } = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);


		public static void Apply()
		{
			HarmonyInstance = Harmony.CreateAndPatchAll(typeof(UnityPatches), (string)null);
			try
			{
				TraceFix.ApplyFix();
			}
			catch
			{
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		public static void GetLocation(ref string __result, Assembly __instance)
		{
			if (AssemblyLocations.TryGetValue(__instance.FullName, out var value))
			{
				__result = value;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		public static void GetCodeBase(ref string __result, Assembly __instance)
		{
			if (AssemblyLocations.TryGetValue(__instance.FullName, out var value))
			{
				__result = "file://" + value.Replace('\\', '/');
			}
		}
	}
	internal static class XTermFix
	{
		public static int intOffset;

		public static void Apply()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Expected O, but got Unknown
			if (!PlatformHelper.Is((Platform)37) && (object)typeof(Console).Assembly.GetType("System.ConsoleDriver") != null && (object)AccessTools.Method("System.TermInfoReader:DetermineVersion", (Type[])null, (Type[])null) == null)
			{
				DetourHelper.Native = (IDetourNativePlatform)new DetourNativeX86Platform();
				Harmony val = new Harmony("com.bepinex.xtermfix");
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:ReadHeader", (Type[])null, (Type[])null), new HarmonyMethod(typeof(XTermFix), "ReadHeaderPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:Get", new Type[1] { AccessTools.TypeByName("System.TermInfoNumbers") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoNumbersTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:Get", new Type[1] { AccessTools.TypeByName("System.TermInfoStrings") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoStringsTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:GetStringBytes", new Type[1] { AccessTools.TypeByName("System.TermInfoStrings") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoStringsTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				DetourHelper.Native = null;
			}
		}

		public static int GetInt32(byte[] buffer, int offset)
		{
			byte num = buffer[offset];
			int num2 = buffer[offset + 1];
			int num3 = buffer[offset + 2];
			int num4 = buffer[offset + 3];
			return num | (num2 << 8) | (num3 << 16) | (num4 << 24);
		}

		public static short GetInt16(byte[] buffer, int offset)
		{
			byte num = buffer[offset];
			int num2 = buffer[offset + 1];
			return (short)(num | (num2 << 8));
		}

		public static int GetInteger(byte[] buffer, int offset)
		{
			if (intOffset != 2)
			{
				return GetInt32(buffer, offset);
			}
			return GetInt16(buffer, offset);
		}

		public static void DetermineVersion(short magic)
		{
			switch (magic)
			{
			case 282:
				intOffset = 2;
				break;
			case 542:
				intOffset = 4;
				break;
			default:
				throw new Exception($"Unknown xterm header format: {magic}");
			}
		}

		public static bool ReadHeaderPrefix(byte[] buffer, ref int position, ref short ___boolSize, ref short ___numSize, ref short ___strOffsets)
		{
			short @int = GetInt16(buffer, position);
			position += 2;
			DetermineVersion(@int);
			position += 2;
			___boolSize = GetInt16(buffer, position);
			position += 2;
			___numSize = GetInt16(buffer, position);
			position += 2;
			___strOffsets = GetInt16(buffer, position);
			position += 2;
			position += 2;
			return false;
		}

		public static IEnumerable<CodeInstruction> GetTermInfoNumbersTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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
			List<CodeInstruction> list = instructions.ToList();
			list[31] = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(XTermFix), "intOffset"));
			list[36] = new CodeInstruction(OpCodes.Nop, (object)null);
			list[39] = new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(XTermFix), "GetInteger", (Type[])null, (Type[])null));
			return list;
		}

		public static IEnumerable<CodeInstruction> GetTermInfoStringsTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			List<CodeInstruction> list = instructions.ToList();
			list[32] = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(XTermFix), "intOffset"));
			return list;
		}
	}
}
namespace BepInEx.Preloader.Patching
{
	public delegate void AssemblyPatcherDelegate(ref AssemblyDefinition assembly);
	public static class AssemblyPatcher
	{
		private const BindingFlags ALL = BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly string DumpedAssembliesPath = Utility.CombinePaths(new string[3]
		{
			Paths.BepInExRootPath,
			"DumpedAssemblies",
			Paths.ProcessName
		});

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

		private static readonly ConfigEntry<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "DumpAssemblies", false, "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers.");

		private static readonly ConfigEntry<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "LoadDumpedAssemblies", false, "If enabled, BepInEx will load patched assemblies from BepInEx/DumpedAssemblies instead of memory.\nThis can be used to be able to load patched assemblies into debuggers like dnSpy.\nIf set to true, will override DumpAssemblies.");

		private static readonly ConfigEntry<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "BreakBeforeLoadAssemblies", false, "If enabled, BepInEx will call Debugger.Break() once before loading patched assemblies.\nThis can be used with debuggers like dnSpy to install breakpoints into patched assemblies before they are loaded.");

		public static List<PatcherPlugin> PatcherPlugins { get; } = new List<PatcherPlugin>();


		private static IEnumerable<PatcherPlugin> PatcherPluginsSafe => PatcherPlugins.ToList();

		public static void AddPatcher(PatcherPlugin patcher)
		{
			PatcherPlugins.Add(patcher);
		}

		private static T CreateDelegate<T>(MethodInfo method) where T : class
		{
			if ((object)method == null)
			{
				return null;
			}
			return Delegate.CreateDelegate(typeof(T), method) as T;
		}

		private static PatcherPlugin ToPatcherPlugin(TypeDefinition type)
		{
			if (type.IsInterface || (type.IsAbstract && !type.IsSealed))
			{
				return null;
			}
			MethodDefinition val = ((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name.Equals("get_TargetDLLs", StringComparison.InvariantCultureIgnoreCase) && m.IsPublic && m.IsStatic));
			if (val == null || ((MemberReference)((MethodReference)val).ReturnType).FullName != "System.Collections.Generic.IEnumerable`1<System.String>")
			{
				return null;
			}
			if (((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name.Equals("Patch") && m.IsPublic && m.IsStatic && ((MemberReference)((MethodReference)m).ReturnType).FullName == "System.Void" && ((MethodReference)m).Parameters.Count == 1 && (((MemberReference)((ParameterReference)((MethodReference)m).Parameters[0]).ParameterType).FullName == "Mono.Cecil.AssemblyDefinition&" || ((MemberReference)((ParameterReference)((MethodReference)m).Parameters[0]).ParameterType).FullName == "Mono.Cecil.AssemblyDefinition"))) == null)
			{
				return null;
			}
			return new PatcherPlugin
			{
				TypeName = ((MemberReference)type).FullName
			};
		}

		public static void AddPatchersFromDirectory(string directory)
		{
			if (!Directory.Exists(directory))
			{
				return;
			}
			SortedDictionary<string, PatcherPlugin> sortedDictionary = new SortedDictionary<string, PatcherPlugin>();
			foreach (KeyValuePair<string, List<PatcherPlugin>> item in TypeLoader.FindPluginTypes<PatcherPlugin>(directory, (Func<TypeDefinition, PatcherPlugin>)ToPatcherPlugin, (Func<AssemblyDefinition, bool>)null, (string)null))
			{
				string key = item.Key;
				List<PatcherPlugin> value = item.Value;
				if (value.Count == 0)
				{
					continue;
				}
				Assembly assembly = Assembly.LoadFile(key);
				foreach (PatcherPlugin item2 in value)
				{
					try
					{
						Type type = assembly.GetType(item2.TypeName);
						MethodInfo[] methods = type.GetMethods(BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
						item2.Initializer = CreateDelegate<Action>(methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Initialize", StringComparison.InvariantCultureIgnoreCase) && m.GetParameters().Length == 0 && (object)m.ReturnType == typeof(void)));
						item2.Finalizer = CreateDelegate<Action>(methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Finish", StringComparison.InvariantCultureIgnoreCase) && m.GetParameters().Length == 0 && (object)m.ReturnType == typeof(void)));
						item2.TargetDLLs = CreateDelegate<Func<IEnumerable<string>>>(type.GetProperty("TargetDLLs", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod());
						MethodInfo patcher = methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Patch", StringComparison.CurrentCultureIgnoreCase) && (object)m.ReturnType == typeof(void) && m.GetParameters().Length == 1 && ((object)m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition) || (object)m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition).MakeByRefType()));
						item2.Patcher = delegate(ref AssemblyDefinition pAss)
						{
							//IL_001e: Unknown result type (might be due to invalid IL or missing references)
							//IL_0024: Expected O, but got Unknown
							object[] array = new object[1] { pAss };
							patcher.Invoke(null, array);
							pAss = (AssemblyDefinition)array[0];
						};
						sortedDictionary.Add(assembly.GetName().Name + "/" + type.FullName, item2);
					}
					catch (Exception ex)
					{
						Logger.LogError((object)("Failed to load patcher [" + item2.TypeName + "]: " + ex.Message));
						if (ex is ReflectionTypeLoadException ex2)
						{
							Logger.LogDebug((object)TypeLoader.TypeLoadExceptionToString(ex2));
						}
						else
						{
							Logger.LogDebug((object)ex.ToString());
						}
					}
				}
				AssemblyName name = assembly.GetName();
				Logger.Log((LogLevel)(value.Any() ? 16 : 32), (object)string.Format("Loaded {0} patcher method{1} from [{2} {3}]", value.Count, (value.Count == 1) ? "" : "s", name.Name, name.Version));
			}
			foreach (KeyValuePair<string, PatcherPlugin> item3 in sortedDictionary)
			{
				AddPatcher(item3.Value);
			}
		}

		private static void InitializePatchers()
		{
			foreach (PatcherPlugin item in PatcherPluginsSafe)
			{
				try
				{
					item.Initializer?.Invoke();
				}
				catch (Exception arg)
				{
					Logger.LogError((object)$"Failed to run Initializer of {item.TypeName}: {arg}");
				}
			}
		}

		private static void FinalizePatching()
		{
			foreach (PatcherPlugin item in PatcherPluginsSafe)
			{
				try
				{
					item.Finalizer?.Invoke();
				}
				catch (Exception arg)
				{
					Logger.LogError((object)$"Failed to run Finalizer of {item.TypeName}: {arg}");
				}
			}
		}

		public static void DisposePatchers()
		{
			PatcherPlugins.Clear();
		}

		private static string GetAssemblyName(string fullName)
		{
			AssemblyName assemblyName = default(AssemblyName);
			if (!Utility.TryParseAssemblyName(fullName, ref assemblyName))
			{
				return fullName;
			}
			return assemblyName.Name;
		}

		public static void PatchAndLoad(params string[] directories)
		{
			Dictionary<string, AssemblyDefinition> dictionary = new Dictionary<string, AssemblyDefinition>(StringComparer.InvariantCultureIgnoreCase);
			foreach (string uniqueFilesInDirectory in Utility.GetUniqueFilesInDirectories((IEnumerable<string>)directories, "*.dll"))
			{
				AssemblyDefinition val;
				try
				{
					val = AssemblyDefinition.ReadAssembly(uniqueFilesInDirectory);
				}
				catch (BadImageFormatException)
				{
					continue;
				}
				if (((AssemblyNameReference)val.Name).Name == "System" || ((AssemblyNameReference)val.Name).Name == "mscorlib")
				{
					val.Dispose();
					continue;
				}
				if (UnityPatches.AssemblyLocations.ContainsKey(val.FullName))
				{
					Logger.LogWarning((object)("Tried to load duplicate assembly " + Path.GetFileName(uniqueFilesInDirectory) + " from Managed folder! Skipping..."));
					continue;
				}
				dictionary.Add(Path.GetFileName(uniqueFilesInDirectory), val);
				UnityPatches.AssemblyLocations.Add(val.FullName, Path.GetFullPath(uniqueFilesInDirectory));
			}
			InitializePatchers();
			HashSet<string> patchedAssemblies = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
			Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
			HashSet<string> hashSet = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
			foreach (PatcherPlugin item in PatcherPluginsSafe)
			{
				foreach (string item2 in item.TargetDLLs())
				{
					if (!dictionary.TryGetValue(item2, out var value) || hashSet.Contains(item2))
					{
						continue;
					}
					Logger.LogInfo((object)("Patching [" + ((AssemblyNameReference)value.Name).Name + "] with [" + item.TypeName + "]"));
					try
					{
						item.Patcher?.Invoke(ref value);
					}
					catch (Exception arg)
					{
						Logger.LogError((object)$"Failed to run [{item.TypeName}] when patching [{((AssemblyNameReference)value.Name).Name}]. This assembly will not be patched. Error: {arg}");
						patchedAssemblies.Remove(item2);
						hashSet.Add(item2);
						continue;
					}
					dictionary[item2] = value;
					patchedAssemblies.Add(item2);
					Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
					for (int i = 0; i < assemblies.Length; i++)
					{
						string assemblyName = GetAssemblyName(assemblies[i].FullName);
						if (!dictionary2.ContainsKey(assemblyName))
						{
							dictionary2[assemblyName] = item.TypeName;
						}
					}
				}
			}
			HashSet<string> patchedAssemblyNames = new HashSet<string>(from kv in dictionary
				where patchedAssemblies.Contains(kv.Key)
				select ((AssemblyNameReference)kv.Value.Name).Name, StringComparer.InvariantCultureIgnoreCase);
			List<KeyValuePair<string, string>> list = dictionary2.Where((KeyValuePair<string, string> kv) => patchedAssemblyNames.Contains(kv.Key)).ToList();
			if (list.Count != 0)
			{
				Logger.LogWarning((object)new StringBuilder().AppendLine("The following assemblies have been loaded too early and will not be patched by preloader:").AppendLine(string.Join(Environment.NewLine, list.Select((KeyValuePair<string, string> kv) => "* [" + kv.Key + "] (first loaded by [" + kv.Value + "])").ToArray())).AppendLine("Expect unexpected behavior and issues with plugins and patchers not being loaded.")
					.ToString());
			}
			DumpedAssemblyPaths.Clear();
			if (ConfigDumpAssemblies.Value || ConfigLoadDumpedAssemblies.Value)
			{
				if (!Directory.Exists(DumpedAssembliesPath))
				{
					Directory.CreateDirectory(DumpedAssembliesPath);
				}
				FileStream fileStream = default(FileStream);
				foreach (KeyValuePair<string, AssemblyDefinition> item3 in dictionary)
				{
					string key = item3.Key;
					string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(key);
					string extension = Path.GetExtension(key);
					AssemblyDefinition value2 = item3.Value;
					if (!patchedAssemblies.Contains(key))
					{
						continue;
					}
					int num = 0;
					string text2;
					while (true)
					{
						string text = ((num > 0) ? $"_{num}" : "");
						text2 = Path.Combine(DumpedAssembliesPath, fileNameWithoutExtension + text + extension);
						if (Utility.TryOpenFileStream(text2, FileMode.Create, ref fileStream, FileAccess.ReadWrite, FileShare.Read))
						{
							break;
						}
						num++;
					}
					value2.Write((Stream)fileStream);
					fileStream.Dispose();
					DumpedAssemblyPaths[key] = text2;
				}
			}
			if (ConfigBreakBeforeLoadAssemblies.Value)
			{
				Logger.LogInfo((object)("BepInEx is about load the following assemblies:\n" + string.Join("\n", patchedAssemblies.ToArray())));
				Logger.LogInfo((object)("The assemblies were dumped into " + DumpedAssembliesPath));
				Logger.LogInfo((object)"Load any assemblies into the debugger, set breakpoints and continue execution.");
				Debugger.Break();
			}
			foreach (KeyValuePair<string, AssemblyDefinition> item4 in dictionary)
			{
				string key2 = item4.Key;
				AssemblyDefinition value3 = item4.Value;
				if (patchedAssemblies.Contains(key2))
				{
					Load(value3, key2);
				}
				value3.Dispose();
			}
			FinalizePatching();
		}

		public static void Load(AssemblyDefinition assembly, string filename)
		{
			if (ConfigLoadDumpedAssemblies.Value && DumpedAssemblyPaths.TryGetValue(filename, out var value))
			{
				Assembly.LoadFile(value);
				return;
			}
			using MemoryStream memoryStream = new MemoryStream();
			assembly.Write((Stream)memoryStream);
			Assembly.Load(memoryStream.ToArray());
		}
	}
	public class PatcherPlugin : ICacheable
	{
		public Func<IEnumerable<string>> TargetDLLs { get; set; }

		public Action Initializer { get; set; }

		public Action Finalizer { get; set; }

		public AssemblyPatcherDelegate Patcher { get; set; }

		public string TypeName { get; set; } = string.Empty;


		public void Save(BinaryWriter bw)
		{
			bw.Write(TypeName);
		}

		public void Load(BinaryReader br)
		{
			TypeName = br.ReadString();
		}
	}
}

BooBoo Building/BepInEx/core/HarmonyXInterop.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.InteropServices;
using HarmonyLib;
using HarmonyLib.Public.Patching;
using HarmonyLib.Tools;
using Mono.Cecil;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("HarmonyXInterop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HarmonyXInterop")]
[assembly: AssemblyCopyright("Copyright ©  2020")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("160F7FE0-288D-435C-9E7E-497D3E0DE3A6")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HarmonyXInterop;

internal static class DMDUtil
{
	public static MethodInfo GenerateWith<T>(this DynamicMethodDefinition dmd, object context = null) where T : DMDGenerator<T>, new()
	{
		return DMDGenerator<T>.Generate(dmd, context);
	}
}
public static class HarmonyInterop
{
	private const string BACKUP_PATH = "BepInEx_Shim_Backup";

	private static Version maxAvailableShimVersion;

	private static readonly SortedDictionary<Version, string> Assemblies = new SortedDictionary<Version, string>();

	private static readonly HashSet<string> InteropAssemblyNames = new HashSet<string>();

	private static readonly Func<MethodBase, PatchInfo, MethodInfo> UpdateWrapper = AccessTools.MethodDelegate<Func<MethodBase, PatchInfo, MethodInfo>>(AccessTools.Method(typeof(HarmonyManipulator).Assembly.GetType("HarmonyLib.PatchFunctions"), "UpdateWrapper", (Type[])null, (Type[])null), (object)null, true);

	private static readonly Action<LogChannel, Func<string>, bool> HarmonyLog = AccessTools.MethodDelegate<Action<LogChannel, Func<string>, bool>>(AccessTools.Method(typeof(Logger), "Log", (Type[])null, (Type[])null), (object)null, true);

	private static readonly Action<LogChannel, string, bool> HarmonyLogText = AccessTools.MethodDelegate<Action<LogChannel, string, bool>>(AccessTools.Method(typeof(Logger), "LogText", (Type[])null, (Type[])null), (object)null, true);

	private static readonly Dictionary<string, long> shimCache = new Dictionary<string, long>();

	private static BinaryWriter cacheWriter;

	public static void Log(int channel, Func<string> message)
	{
		HarmonyLog((LogChannel)channel, message, arg3: false);
	}

	public static void LogText(int channel, string message)
	{
		HarmonyLogText((LogChannel)channel, message, arg3: false);
	}

	public static void Initialize(string cachePath)
	{
		Directory.CreateDirectory(cachePath);
		string path = Path.Combine(cachePath, "harmony_interop_cache.dat");
		string[] files = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "0Harmony*.dll", SearchOption.AllDirectories);
		for (int i = 0; i < files.Length; i++)
		{
			AssemblyDefinition val = AssemblyDefinition.ReadAssembly(files[i]);
			try
			{
				if (((AssemblyNameReference)val.Name).Name != "0Harmony")
				{
					Assemblies.Add(((AssemblyNameReference)val.Name).Version, ((AssemblyNameReference)val.Name).Name);
					InteropAssemblyNames.Add(((AssemblyNameReference)val.Name).Name);
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}
		maxAvailableShimVersion = Assemblies.LastOrDefault().Key;
		if (File.Exists(path))
		{
			try
			{
				using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path));
				while (true)
				{
					string key = binaryReader.ReadString();
					long value = binaryReader.ReadInt64();
					shimCache[key] = value;
				}
			}
			catch (Exception)
			{
			}
		}
		try
		{
			cacheWriter = new BinaryWriter(File.Create(path));
			foreach (KeyValuePair<string, long> item in shimCache)
			{
				cacheWriter.Write(item.Key);
				cacheWriter.Write(item.Value);
			}
			cacheWriter.Flush();
		}
		catch (IOException)
		{
		}
	}

	public static byte[] TryShim(string path, string gameRootDirectory, Action<string> logMessage = null, ReaderParameters readerParameters = null)
	{
		HashSet<string> hashSet = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
		List<string> deps;
		byte[] result = TryShimInternal(path, gameRootDirectory, logMessage, readerParameters, out deps);
		foreach (string item in deps)
		{
			hashSet.Add(item);
		}
		while (hashSet.Count != 0)
		{
			string text = hashSet.First();
			TryShimInternal(text, gameRootDirectory, logMessage, readerParameters, out deps);
			foreach (string item2 in deps)
			{
				hashSet.Add(item2);
			}
			hashSet.Remove(text);
		}
		return result;
	}

	private static bool NeedsShimming(string path, out long lastWriteTime, Action<string> logMessage = null)
	{
		lastWriteTime = 0L;
		try
		{
			if (!File.Exists(path))
			{
				return false;
			}
		}
		catch (Exception arg)
		{
			logMessage?.Invoke($"Failed to read path {path}: {arg}");
			return false;
		}
		lastWriteTime = File.GetLastWriteTimeUtc(path).Ticks;
		if (shimCache.TryGetValue(path, out var value))
		{
			return value != lastWriteTime;
		}
		return true;
	}

	private static byte[] TryShimInternal(string path, string gameRootDirectory, Action<string> logMessage, ReaderParameters readerParameters, out List<string> deps)
	{
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		deps = new List<string>();
		if (!NeedsShimming(path, out var lastWriteTime, logMessage))
		{
			return null;
		}
		byte[] result = null;
		try
		{
			string dir = Path.GetDirectoryName(path);
			byte[] array;
			try
			{
				array = File.ReadAllBytes(path);
			}
			catch (Exception)
			{
				return null;
			}
			using MemoryStream memoryStream = new MemoryStream(array);
			AssemblyDefinition val = AssemblyDefinition.ReadAssembly((Stream)memoryStream, (ReaderParameters)(((object)readerParameters) ?? ((object)new ReaderParameters())));
			try
			{
				deps.AddRange(from a in (IEnumerable<AssemblyNameReference>)val.MainModule.AssemblyReferences
					select Path.Combine(dir, a.Name + ".dll") into p
					where NeedsShimming(p, out var _, logMessage)
					select p);
				AssemblyNameReference harmonyRef = ((IEnumerable<AssemblyNameReference>)val.MainModule.AssemblyReferences).FirstOrDefault((Func<AssemblyNameReference, bool>)((AssemblyNameReference a) => a.Name.StartsWith("0Harmony") && !InteropAssemblyNames.Contains(a.Name)));
				if (harmonyRef != null)
				{
					KeyValuePair<Version, string> keyValuePair = Assemblies.LastOrDefault((KeyValuePair<Version, string> kv) => VersionMatches(kv.Key, harmonyRef.Version));
					if (keyValuePair.Value != null)
					{
						logMessage?.Invoke("Shimming " + path + " to use older version of Harmony (" + keyValuePair.Value + "). Please update the plugin if possible.");
						harmonyRef.Name = keyValuePair.Value;
						using MemoryStream memoryStream2 = new MemoryStream();
						val.Write((Stream)memoryStream2);
						try
						{
							string path2 = Path.Combine(gameRootDirectory, "BepInEx_Shim_Backup");
							string directoryName = Path.GetDirectoryName(Path.GetFullPath(path).Substring(gameRootDirectory.Length + 1));
							string text = Path.Combine(path2, directoryName);
							Directory.CreateDirectory(text);
							File.WriteAllBytes(Path.Combine(text, Path.GetFileName(path)), array);
							File.WriteAllBytes(path, memoryStream2.ToArray());
							lastWriteTime = File.GetLastWriteTimeUtc(path).Ticks;
						}
						catch (IOException)
						{
							lastWriteTime = 0L;
						}
						result = memoryStream2.ToArray();
					}
				}
				shimCache[path] = lastWriteTime;
				if (cacheWriter != null)
				{
					cacheWriter.Write(path);
					cacheWriter.Write(lastWriteTime);
					cacheWriter.Flush();
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}
		catch (Exception arg)
		{
			logMessage?.Invoke($"Failed to shim {path}: {arg}");
		}
		return result;
		static bool VersionMatches(Version cmpV, Version refV)
		{
			if (maxAvailableShimVersion != null && refV <= maxAvailableShimVersion && cmpV.Major == refV.Major && cmpV.Minor == refV.Minor)
			{
				return cmpV <= refV;
			}
			return false;
		}
	}

	public static void ApplyPatch(MethodBase target, PatchInfoWrapper add, PatchInfoWrapper remove)
	{
		PatchInfo val = PatchManager.ToPatchInfo(target);
		lock (val)
		{
			val.prefixes = Sync(add.prefixes, remove.prefixes, val.prefixes);
			val.postfixes = Sync(add.postfixes, remove.postfixes, val.postfixes);
			val.transpilers = Sync(WrapTranspilers(add.transpilers), WrapTranspilers(remove.transpilers), val.transpilers);
			val.finalizers = Sync(add.finalizers, remove.finalizers, val.finalizers);
		}
		UpdateWrapper(target, val);
		static PatchMethod[] WrapTranspilers(PatchMethod[] transpilers)
		{
			return transpilers.Select((PatchMethod p) => new PatchMethod
			{
				after = p.after,
				before = p.before,
				method = TranspilerInterop.WrapInterop(p.method),
				owner = p.owner,
				priority = p.priority
			}).ToArray();
		}
	}

	private static Patch[] Sync(PatchMethod[] add, PatchMethod[] remove, Patch[] current)
	{
		if (add.Length == 0 && remove.Length == 0)
		{
			return current;
		}
		current = current.Where((Patch p) => !remove.Any((PatchMethod r) => (object)r.method == p.PatchMethod && r.owner == p.owner)).ToArray();
		int initialIndex = current.Length;
		return current.Concat(add.Where((PatchMethod method) => method != null).Select((Func<PatchMethod, int, Patch>)((PatchMethod method, int i) => new Patch(method.ToHarmonyMethod(), i + initialIndex, method.owner)))).ToArray();
	}
}
public class PatchInfoWrapper
{
	public PatchMethod[] finalizers;

	public PatchMethod[] postfixes;

	public PatchMethod[] prefixes;

	public PatchMethod[] transpilers;
}
public class PatchMethod
{
	public string[] after;

	public string[] before;

	public MethodInfo method;

	public string owner;

	public int priority = -1;

	public HarmonyMethod ToHarmonyMethod()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: 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_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		return new HarmonyMethod
		{
			after = after,
			before = before,
			method = method,
			priority = priority
		};
	}
}
public class PatchMethodComparer : IEqualityComparer<PatchMethod>
{
	public static PatchMethodComparer Instance { get; } = new PatchMethodComparer();


	public bool Equals(PatchMethod x, PatchMethod y)
	{
		if (x == y)
		{
			return true;
		}
		if (x == null)
		{
			return false;
		}
		if (y == null)
		{
			return false;
		}
		if ((object)x.GetType() != y.GetType())
		{
			return false;
		}
		if (object.Equals(x.method, y.method))
		{
			return x.owner == y.owner;
		}
		return false;
	}

	public int GetHashCode(PatchMethod obj)
	{
		return ((((object)obj.method != null) ? obj.method.GetHashCode() : 0) * 397) ^ ((obj.owner != null) ? obj.owner.GetHashCode() : 0);
	}
}
internal static class TranspilerInterop
{
	private static readonly Dictionary<OpCode, OpCode> AllJumpCodes = new Dictionary<OpCode, OpCode>
	{
		{
			OpCodes.Beq_S,
			OpCodes.Beq
		},
		{
			OpCodes.Bge_S,
			OpCodes.Bge
		},
		{
			OpCodes.Bge_Un_S,
			OpCodes.Bge_Un
		},
		{
			OpCodes.Bgt_S,
			OpCodes.Bgt
		},
		{
			OpCodes.Bgt_Un_S,
			OpCodes.Bgt_Un
		},
		{
			OpCodes.Ble_S,
			OpCodes.Ble
		},
		{
			OpCodes.Ble_Un_S,
			OpCodes.Ble_Un
		},
		{
			OpCodes.Blt_S,
			OpCodes.Blt
		},
		{
			OpCodes.Blt_Un_S,
			OpCodes.Blt_Un
		},
		{
			OpCodes.Bne_Un_S,
			OpCodes.Bne_Un
		},
		{
			OpCodes.Brfalse_S,
			OpCodes.Brfalse
		},
		{
			OpCodes.Brtrue_S,
			OpCodes.Brtrue
		},
		{
			OpCodes.Br_S,
			OpCodes.Br
		},
		{
			OpCodes.Leave_S,
			OpCodes.Leave
		}
	};

	private static readonly Dictionary<MethodInfo, MethodInfo> Wrappers = new Dictionary<MethodInfo, MethodInfo>();

	private static readonly MethodInfo ResolveToken = AccessTools.Method(typeof(MethodBase), "GetMethodFromHandle", new Type[1] { typeof(RuntimeMethodHandle) }, (Type[])null);

	private static readonly MethodInfo ApplyTranspilerMethod = AccessTools.Method(typeof(TranspilerInterop), "ApplyTranspiler", (Type[])null, (Type[])null);

	public static MethodInfo WrapInterop(MethodInfo transpiler)
	{
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Expected O, but got Unknown
		lock (Wrappers)
		{
			if (Wrappers.TryGetValue(transpiler, out var value))
			{
				return value;
			}
		}
		DynamicMethodDefinition val = new DynamicMethodDefinition("TranspilerWrapper<" + Extensions.GetID((MethodBase)transpiler, (string)null, (string)null, true, false, true) + ">", typeof(IEnumerable<CodeInstruction>), new Type[3]
		{
			typeof(IEnumerable<CodeInstruction>),
			typeof(ILGenerator),
			typeof(MethodBase)
		});
		try
		{
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldtoken, transpiler);
			iLGenerator.Emit(OpCodes.Call, ResolveToken);
			iLGenerator.Emit(OpCodes.Castclass, typeof(MethodInfo));
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Ldarg_2);
			iLGenerator.Emit(OpCodes.Call, ApplyTranspilerMethod);
			iLGenerator.Emit(OpCodes.Ret);
			MethodInfo methodInfo = val.GenerateWith<DMDCecilGenerator>((object)null);
			lock (Wrappers)
			{
				Wrappers[transpiler] = methodInfo;
			}
			return methodInfo;
		}
		finally
		{
			((IDisposable)val)?.Dispose();
		}
	}

	private static IEnumerable<CodeInstruction> ApplyTranspiler(MethodInfo transpiler, IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase method)
	{
		Dictionary<object, Dictionary<string, object>> unassignedValues;
		IEnumerable enumerable = ConvertToGeneralInstructions(transpiler, instructions, out unassignedValues);
		List<object> originalInstructions = null;
		if (unassignedValues != null)
		{
			originalInstructions = instructions.Cast<object>().ToList();
		}
		List<object> transpilerCallParameters = GetTranspilerCallParameters(generator, transpiler, method, enumerable);
		if (transpiler.Invoke(null, transpilerCallParameters.ToArray()) is IEnumerable enumerable2)
		{
			enumerable = enumerable2;
		}
		if (unassignedValues != null)
		{
			enumerable = ConvertToOurInstructions(enumerable, typeof(CodeInstruction), originalInstructions, unassignedValues);
		}
		return (enumerable as List<CodeInstruction>) ?? enumerable.Cast<CodeInstruction>().ToList();
	}

	private static OpCode ReplaceShortJumps(OpCode opcode)
	{
		using (IEnumerator<KeyValuePair<OpCode, OpCode>> enumerator = AllJumpCodes.Where((KeyValuePair<OpCode, OpCode> pair) => opcode == pair.Key).GetEnumerator())
		{
			if (enumerator.MoveNext())
			{
				return enumerator.Current.Value;
			}
		}
		return opcode;
	}

	private static object ConvertInstruction(Type type, object instruction, out Dictionary<string, object> unassigned)
	{
		Dictionary<string, object> nonExisting = new Dictionary<string, object>();
		object result = AccessTools.MakeDeepCopy(instruction, type, (Func<string, Traverse, Traverse, object>)delegate(string namePath, Traverse trvSrc, Traverse trvDest)
		{
			object value = trvSrc.GetValue();
			if (trvDest.FieldExists())
			{
				if (!(namePath == "opcode"))
				{
					return value;
				}
				return ReplaceShortJumps((OpCode)value);
			}
			nonExisting[namePath] = value;
			return null;
		}, "");
		unassigned = nonExisting;
		return result;
	}

	private static bool ShouldAddExceptionInfo(object op, int opIndex, List<object> originalInstructions, List<object> newInstructions, Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		int num = originalInstructions.IndexOf(op);
		if (num == -1)
		{
			return false;
		}
		if (!unassignedValues.TryGetValue(op, out var unassigned))
		{
			return false;
		}
		if (!unassigned.TryGetValue("blocks", out var blocksObject))
		{
			return false;
		}
		List<ExceptionBlock> blocks = blocksObject as List<ExceptionBlock>;
		if (newInstructions.Count((object instr) => instr == op) <= 1)
		{
			return true;
		}
		ExceptionBlock val = ((IEnumerable<ExceptionBlock>)blocks).FirstOrDefault((Func<ExceptionBlock, bool>)((ExceptionBlock block) => (int)block.blockType != 5));
		ExceptionBlock val2 = ((IEnumerable<ExceptionBlock>)blocks).FirstOrDefault((Func<ExceptionBlock, bool>)((ExceptionBlock block) => (int)block.blockType == 5));
		if (val != null && val2 == null)
		{
			object obj = originalInstructions.Skip(num + 1).FirstOrDefault(delegate(object instr)
			{
				if (!unassignedValues.TryGetValue(instr, out unassigned))
				{
					return false;
				}
				if (!unassigned.TryGetValue("blocks", out blocksObject))
				{
					return false;
				}
				blocks = blocksObject as List<ExceptionBlock>;
				return blocks.Any();
			});
			if (obj != null)
			{
				int num2 = num + 1;
				int num3 = num2 + originalInstructions.Skip(num2).ToList().IndexOf(obj) - 1;
				IEnumerable<object> first = originalInstructions.GetRange(num2, num3 - num2).Intersect(newInstructions);
				obj = newInstructions.Skip(opIndex + 1).FirstOrDefault(delegate(object instr)
				{
					if (!unassignedValues.TryGetValue(instr, out unassigned))
					{
						return false;
					}
					if (!unassigned.TryGetValue("blocks", out blocksObject))
					{
						return false;
					}
					blocks = blocksObject as List<ExceptionBlock>;
					return blocks.Any();
				});
				if (obj != null)
				{
					num2 = opIndex + 1;
					num3 = num2 + newInstructions.Skip(opIndex + 1).ToList().IndexOf(obj) - 1;
					List<object> range = newInstructions.GetRange(num2, num3 - num2);
					return !first.Except(range).ToList().Any();
				}
			}
		}
		if (val == null && val2 != null)
		{
			object obj2 = originalInstructions.GetRange(0, num).LastOrDefault(delegate(object instr)
			{
				if (!unassignedValues.TryGetValue(instr, out unassigned))
				{
					return false;
				}
				if (!unassigned.TryGetValue("blocks", out blocksObject))
				{
					return false;
				}
				blocks = blocksObject as List<ExceptionBlock>;
				return blocks.Any();
			});
			if (obj2 == null)
			{
				return true;
			}
			int num4 = originalInstructions.GetRange(0, num).LastIndexOf(obj2);
			int num5 = num;
			IEnumerable<object> first2 = originalInstructions.GetRange(num4, num5 - num4).Intersect(newInstructions);
			obj2 = newInstructions.GetRange(0, opIndex).LastOrDefault(delegate(object instr)
			{
				if (!unassignedValues.TryGetValue(instr, out unassigned))
				{
					return false;
				}
				if (!unassigned.TryGetValue("blocks", out blocksObject))
				{
					return false;
				}
				blocks = blocksObject as List<ExceptionBlock>;
				return blocks.Any();
			});
			if (obj2 == null)
			{
				return true;
			}
			num4 = newInstructions.GetRange(0, opIndex).LastIndexOf(obj2);
			num5 = opIndex;
			List<object> range2 = newInstructions.GetRange(num4, num5 - num4);
			return !first2.Except(range2).Any();
		}
		return true;
	}

	private static IEnumerable ConvertInstructionsAndUnassignedValues(Type type, IEnumerable enumerable, out Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		Assembly assembly = type.GetGenericTypeDefinition().Assembly;
		Type? type2 = assembly.GetType(typeof(List<>).FullName);
		Type type3 = type.GetGenericArguments()[0];
		Type type4 = type2.MakeGenericType(type3);
		object obj = Activator.CreateInstance(assembly.GetType(type4.FullName));
		MethodInfo method = obj.GetType().GetMethod("Add");
		unassignedValues = new Dictionary<object, Dictionary<string, object>>();
		foreach (object item in enumerable)
		{
			Dictionary<string, object> unassigned;
			object obj2 = ConvertInstruction(type3, item, out unassigned);
			unassignedValues.Add(obj2, unassigned);
			method.Invoke(obj, new object[1] { obj2 });
		}
		return obj as IEnumerable;
	}

	private static IEnumerable ConvertToOurInstructions(IEnumerable instructions, Type codeInstructionType, List<object> originalInstructions, Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		List<object> newInstructions = instructions.Cast<object>().ToList();
		int index = -1;
		foreach (object item in newInstructions)
		{
			index++;
			object obj = AccessTools.MakeDeepCopy(item, codeInstructionType, (Func<string, Traverse, Traverse, object>)null, "");
			if (unassignedValues.TryGetValue(item, out var value))
			{
				bool addExceptionInfo = ShouldAddExceptionInfo(item, index, originalInstructions, newInstructions, unassignedValues);
				Traverse val = Traverse.Create(obj);
				foreach (KeyValuePair<string, object> item2 in value.Where((KeyValuePair<string, object> field) => addExceptionInfo || field.Key != "blocks"))
				{
					val.Field(item2.Key).SetValue(item2.Value);
				}
			}
			yield return obj;
		}
	}

	private static bool IsCodeInstructionsParameter(Type type)
	{
		if (type.IsGenericType)
		{
			return type.GetGenericTypeDefinition().Name.StartsWith("IEnumerable", StringComparison.Ordinal);
		}
		return false;
	}

	private static IEnumerable ConvertToGeneralInstructions(MethodInfo transpiler, IEnumerable enumerable, out Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		Type type = (from p in transpiler.GetParameters()
			select p.ParameterType).FirstOrDefault((Type t) => IsCodeInstructionsParameter(t));
		if ((object)type == null)
		{
			unassignedValues = new Dictionary<object, Dictionary<string, object>>();
			return enumerable;
		}
		if ((object)type != typeof(IEnumerable<CodeInstruction>))
		{
			return ConvertInstructionsAndUnassignedValues(type, enumerable, out unassignedValues);
		}
		unassignedValues = null;
		return (enumerable as IList<CodeInstruction>) ?? ((enumerable as IEnumerable<CodeInstruction>) ?? enumerable.Cast<CodeInstruction>()).ToList();
	}

	private static List<object> GetTranspilerCallParameters(ILGenerator generator, MethodInfo transpiler, MethodBase method, IEnumerable instructions)
	{
		List<object> parameter = new List<object>();
		CollectionExtensions.Do<Type>(from param in transpiler.GetParameters()
			select param.ParameterType, (Action<Type>)delegate(Type type)
		{
			if (type.IsAssignableFrom(typeof(ILGenerator)))
			{
				parameter.Add(generator);
			}
			else if (type.IsAssignableFrom(typeof(MethodBase)))
			{
				parameter.Add(method);
			}
			else if (IsCodeInstructionsParameter(type))
			{
				parameter.Add(instructions);
			}
		});
		return parameter;
	}
}

BooBoo Building/BepInEx/core/Mono.Cecil.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
using Mono.Collections.Generic;
using Mono.Security.Cryptography;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil")]
[assembly: Guid("fd225bb4-fa53-44b2-a6db-85f5e48dcb54")]
[assembly: InternalsVisibleTo("Mono.Cecil.Pdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: InternalsVisibleTo("Mono.Cecil.Mdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: InternalsVisibleTo("Mono.Cecil.Rocks, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: InternalsVisibleTo("Mono.Cecil.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: AssemblyVersion("0.10.4.0")]
internal static class Consts
{
	public const string AssemblyName = "Mono.Cecil";

	public const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf";
}
namespace Mono
{
	internal static class Disposable
	{
		public static Disposable<T> Owned<T>(T value) where T : class, IDisposable
		{
			return new Disposable<T>(value, owned: true);
		}

		public static Disposable<T> NotOwned<T>(T value) where T : class, IDisposable
		{
			return new Disposable<T>(value, owned: false);
		}
	}
	internal struct Disposable<T> : IDisposable where T : class, IDisposable
	{
		internal readonly T value;

		private readonly bool owned;

		public Disposable(T value, bool owned)
		{
			this.value = value;
			this.owned = owned;
		}

		public void Dispose()
		{
			if (value != null && owned)
			{
				value.Dispose();
			}
		}
	}
	internal static class Empty<T>
	{
		public static readonly T[] Array = new T[0];
	}
	internal class ArgumentNullOrEmptyException : ArgumentException
	{
		public ArgumentNullOrEmptyException(string paramName)
			: base("Argument null or empty", paramName)
		{
		}
	}
	internal class MergeSort<T>
	{
		private readonly T[] elements;

		private readonly T[] buffer;

		private readonly IComparer<T> comparer;

		private MergeSort(T[] elements, IComparer<T> comparer)
		{
			this.elements = elements;
			buffer = new T[elements.Length];
			Array.Copy(this.elements, buffer, elements.Length);
			this.comparer = comparer;
		}

		public static void Sort(T[] source, IComparer<T> comparer)
		{
			Sort(source, 0, source.Length, comparer);
		}

		public static void Sort(T[] source, int start, int length, IComparer<T> comparer)
		{
			new MergeSort<T>(source, comparer).Sort(start, length);
		}

		private void Sort(int start, int length)
		{
			TopDownSplitMerge(buffer, elements, start, length);
		}

		private void TopDownSplitMerge(T[] a, T[] b, int start, int end)
		{
			if (end - start >= 2)
			{
				int num = (end + start) / 2;
				TopDownSplitMerge(b, a, start, num);
				TopDownSplitMerge(b, a, num, end);
				TopDownMerge(a, b, start, num, end);
			}
		}

		private void TopDownMerge(T[] a, T[] b, int start, int middle, int end)
		{
			int num = start;
			int num2 = middle;
			for (int i = start; i < end; i++)
			{
				if (num < middle && (num2 >= end || comparer.Compare(a[num], a[num2]) <= 0))
				{
					b[i] = a[num++];
				}
				else
				{
					b[i] = a[num2++];
				}
			}
		}
	}
	internal static class TypeExtensions
	{
		public static TypeCode GetTypeCode(this Type type)
		{
			return Type.GetTypeCode(type);
		}

		public static Assembly Assembly(this Type type)
		{
			return type.Assembly;
		}

		public static MethodBase DeclaringMethod(this Type type)
		{
			return type.DeclaringMethod;
		}

		public static Type[] GetGenericArguments(this Type type)
		{
			return type.GetGenericArguments();
		}

		public static bool IsGenericType(this Type type)
		{
			return type.IsGenericType;
		}

		public static bool IsGenericTypeDefinition(this Type type)
		{
			return type.IsGenericTypeDefinition;
		}

		public static bool IsValueType(this Type type)
		{
			return type.IsValueType;
		}
	}
}
namespace Mono.Security.Cryptography
{
	internal static class CryptoConvert
	{
		private static int ToInt32LE(byte[] bytes, int offset)
		{
			return (bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset];
		}

		private static uint ToUInt32LE(byte[] bytes, int offset)
		{
			return (uint)((bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]);
		}

		private static byte[] Trim(byte[] array)
		{
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i] != 0)
				{
					byte[] array2 = new byte[array.Length - i];
					Buffer.BlockCopy(array, i, array2, 0, array2.Length);
					return array2;
				}
			}
			return null;
		}

		private static RSA FromCapiPrivateKeyBlob(byte[] blob, int offset)
		{
			RSAParameters parameters = default(RSAParameters);
			try
			{
				if (blob[offset] != 7 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 843141970)
				{
					throw new CryptographicException("Invalid blob header");
				}
				int num = ToInt32LE(blob, offset + 12);
				byte[] array = new byte[4];
				Buffer.BlockCopy(blob, offset + 16, array, 0, 4);
				Array.Reverse((Array)array);
				parameters.Exponent = Trim(array);
				int num2 = offset + 20;
				int num3 = num >> 3;
				parameters.Modulus = new byte[num3];
				Buffer.BlockCopy(blob, num2, parameters.Modulus, 0, num3);
				Array.Reverse((Array)parameters.Modulus);
				num2 += num3;
				int num4 = num3 >> 1;
				parameters.P = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.P, 0, num4);
				Array.Reverse((Array)parameters.P);
				num2 += num4;
				parameters.Q = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.Q, 0, num4);
				Array.Reverse((Array)parameters.Q);
				num2 += num4;
				parameters.DP = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.DP, 0, num4);
				Array.Reverse((Array)parameters.DP);
				num2 += num4;
				parameters.DQ = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.DQ, 0, num4);
				Array.Reverse((Array)parameters.DQ);
				num2 += num4;
				parameters.InverseQ = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.InverseQ, 0, num4);
				Array.Reverse((Array)parameters.InverseQ);
				num2 += num4;
				parameters.D = new byte[num3];
				if (num2 + num3 + offset <= blob.Length)
				{
					Buffer.BlockCopy(blob, num2, parameters.D, 0, num3);
					Array.Reverse((Array)parameters.D);
				}
			}
			catch (Exception inner)
			{
				throw new CryptographicException("Invalid blob.", inner);
			}
			RSA rSA = null;
			try
			{
				rSA = RSA.Create();
				rSA.ImportParameters(parameters);
			}
			catch (CryptographicException)
			{
				bool flag = false;
				try
				{
					rSA = new RSACryptoServiceProvider(new CspParameters
					{
						Flags = CspProviderFlags.UseMachineKeyStore
					});
					rSA.ImportParameters(parameters);
				}
				catch
				{
					flag = true;
				}
				if (flag)
				{
					throw;
				}
			}
			return rSA;
		}

		private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset)
		{
			try
			{
				if (blob[offset] != 6 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 826364754)
				{
					throw new CryptographicException("Invalid blob header");
				}
				int num = ToInt32LE(blob, offset + 12);
				RSAParameters parameters = new RSAParameters
				{
					Exponent = new byte[3]
				};
				parameters.Exponent[0] = blob[offset + 18];
				parameters.Exponent[1] = blob[offset + 17];
				parameters.Exponent[2] = blob[offset + 16];
				int srcOffset = offset + 20;
				int num2 = num >> 3;
				parameters.Modulus = new byte[num2];
				Buffer.BlockCopy(blob, srcOffset, parameters.Modulus, 0, num2);
				Array.Reverse((Array)parameters.Modulus);
				RSA rSA = null;
				try
				{
					rSA = RSA.Create();
					rSA.ImportParameters(parameters);
				}
				catch (CryptographicException)
				{
					rSA = new RSACryptoServiceProvider(new CspParameters
					{
						Flags = CspProviderFlags.UseMachineKeyStore
					});
					rSA.ImportParameters(parameters);
				}
				return rSA;
			}
			catch (Exception inner)
			{
				throw new CryptographicException("Invalid blob.", inner);
			}
		}

		public static RSA FromCapiKeyBlob(byte[] blob)
		{
			return FromCapiKeyBlob(blob, 0);
		}

		public static RSA FromCapiKeyBlob(byte[] blob, int offset)
		{
			if (blob == null)
			{
				throw new ArgumentNullException("blob");
			}
			if (offset >= blob.Length)
			{
				throw new ArgumentException("blob is too small.");
			}
			switch (blob[offset])
			{
			case 0:
				if (blob[offset + 12] == 6)
				{
					return FromCapiPublicKeyBlob(blob, offset + 12);
				}
				break;
			case 6:
				return FromCapiPublicKeyBlob(blob, offset);
			case 7:
				return FromCapiPrivateKeyBlob(blob, offset);
			}
			throw new CryptographicException("Unknown blob format.");
		}
	}
}
namespace Mono.Collections.Generic
{
	public class Collection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection
	{
		public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator
		{
			private Collection<T> collection;

			private T current;

			private int next;

			private readonly int version;

			public T Current => current;

			object IEnumerator.Current
			{
				get
				{
					CheckState();
					if (next <= 0)
					{
						throw new InvalidOperationException();
					}
					return current;
				}
			}

			internal Enumerator(Collection<T> collection)
			{
				this = default(Enumerator);
				this.collection = collection;
				version = collection.version;
			}

			public bool MoveNext()
			{
				CheckState();
				if (next < 0)
				{
					return false;
				}
				if (next < collection.size)
				{
					current = collection.items[next++];
					return true;
				}
				next = -1;
				return false;
			}

			public void Reset()
			{
				CheckState();
				next = 0;
			}

			private void CheckState()
			{
				if (collection == null)
				{
					throw new ObjectDisposedException(GetType().FullName);
				}
				if (version != collection.version)
				{
					throw new InvalidOperationException();
				}
			}

			public void Dispose()
			{
				collection = null;
			}
		}

		internal T[] items;

		internal int size;

		private int version;

		public int Count => size;

		public T this[int index]
		{
			get
			{
				if (index >= size)
				{
					throw new ArgumentOutOfRangeException();
				}
				return items[index];
			}
			set
			{
				CheckIndex(index);
				if (index == size)
				{
					throw new ArgumentOutOfRangeException();
				}
				OnSet(value, index);
				items[index] = value;
			}
		}

		public int Capacity
		{
			get
			{
				return items.Length;
			}
			set
			{
				if (value < 0 || value < size)
				{
					throw new ArgumentOutOfRangeException();
				}
				Resize(value);
			}
		}

		bool ICollection<T>.IsReadOnly => false;

		bool IList.IsFixedSize => false;

		bool IList.IsReadOnly => false;

		object IList.this[int index]
		{
			get
			{
				return this[index];
			}
			set
			{
				CheckIndex(index);
				try
				{
					this[index] = (T)value;
					return;
				}
				catch (InvalidCastException)
				{
				}
				catch (NullReferenceException)
				{
				}
				throw new ArgumentException();
			}
		}

		int ICollection.Count => Count;

		bool ICollection.IsSynchronized => false;

		object ICollection.SyncRoot => this;

		public Collection()
		{
			items = Empty<T>.Array;
		}

		public Collection(int capacity)
		{
			if (capacity < 0)
			{
				throw new ArgumentOutOfRangeException();
			}
			items = new T[capacity];
		}

		public Collection(ICollection<T> items)
		{
			if (items == null)
			{
				throw new ArgumentNullException("items");
			}
			this.items = new T[items.Count];
			items.CopyTo(this.items, 0);
			size = this.items.Length;
		}

		public void Add(T item)
		{
			if (size == items.Length)
			{
				Grow(1);
			}
			OnAdd(item, size);
			items[size++] = item;
			version++;
		}

		public bool Contains(T item)
		{
			return IndexOf(item) != -1;
		}

		public int IndexOf(T item)
		{
			return Array.IndexOf(items, item, 0, size);
		}

		public void Insert(int index, T item)
		{
			CheckIndex(index);
			if (size == items.Length)
			{
				Grow(1);
			}
			OnInsert(item, index);
			Shift(index, 1);
			items[index] = item;
			version++;
		}

		public void RemoveAt(int index)
		{
			if (index < 0 || index >= size)
			{
				throw new ArgumentOutOfRangeException();
			}
			T item = items[index];
			OnRemove(item, index);
			Shift(index, -1);
			version++;
		}

		public bool Remove(T item)
		{
			int num = IndexOf(item);
			if (num == -1)
			{
				return false;
			}
			OnRemove(item, num);
			Shift(num, -1);
			version++;
			return true;
		}

		public void Clear()
		{
			OnClear();
			Array.Clear(items, 0, size);
			size = 0;
			version++;
		}

		public void CopyTo(T[] array, int arrayIndex)
		{
			Array.Copy(items, 0, array, arrayIndex, size);
		}

		public T[] ToArray()
		{
			T[] array = new T[size];
			Array.Copy(items, 0, array, 0, size);
			return array;
		}

		private void CheckIndex(int index)
		{
			if (index < 0 || index > size)
			{
				throw new ArgumentOutOfRangeException();
			}
		}

		private void Shift(int start, int delta)
		{
			if (delta < 0)
			{
				start -= delta;
			}
			if (start < size)
			{
				Array.Copy(items, start, items, start + delta, size - start);
			}
			size += delta;
			if (delta < 0)
			{
				Array.Clear(items, size, -delta);
			}
		}

		protected virtual void OnAdd(T item, int index)
		{
		}

		protected virtual void OnInsert(T item, int index)
		{
		}

		protected virtual void OnSet(T item, int index)
		{
		}

		protected virtual void OnRemove(T item, int index)
		{
		}

		protected virtual void OnClear()
		{
		}

		internal virtual void Grow(int desired)
		{
			int num = size + desired;
			if (num > items.Length)
			{
				num = Math.Max(Math.Max(items.Length * 2, 4), num);
				Resize(num);
			}
		}

		protected void Resize(int new_size)
		{
			if (new_size != size)
			{
				if (new_size < size)
				{
					throw new ArgumentOutOfRangeException();
				}
				items = items.Resize(new_size);
			}
		}

		int IList.Add(object value)
		{
			try
			{
				Add((T)value);
				return size - 1;
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
			throw new ArgumentException();
		}

		void IList.Clear()
		{
			Clear();
		}

		bool IList.Contains(object value)
		{
			return ((IList)this).IndexOf(value) > -1;
		}

		int IList.IndexOf(object value)
		{
			try
			{
				return IndexOf((T)value);
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
			return -1;
		}

		void IList.Insert(int index, object value)
		{
			CheckIndex(index);
			try
			{
				Insert(index, (T)value);
				return;
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
			throw new ArgumentException();
		}

		void IList.Remove(object value)
		{
			try
			{
				Remove((T)value);
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
		}

		void IList.RemoveAt(int index)
		{
			RemoveAt(index);
		}

		void ICollection.CopyTo(Array array, int index)
		{
			Array.Copy(items, 0, array, index, size);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return new Enumerator(this);
		}

		IEnumerator<T> IEnumerable<T>.GetEnumerator()
		{
			return new Enumerator(this);
		}
	}
	public sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection
	{
		private static ReadOnlyCollection<T> empty;

		public static ReadOnlyCollection<T> Empty => empty ?? (empty = new ReadOnlyCollection<T>());

		bool ICollection<T>.IsReadOnly => true;

		bool IList.IsFixedSize => true;

		bool IList.IsReadOnly => true;

		private ReadOnlyCollection()
		{
		}

		public ReadOnlyCollection(T[] array)
		{
			if (array == null)
			{
				throw new ArgumentNullException();
			}
			Initialize(array, array.Length);
		}

		public ReadOnlyCollection(Collection<T> collection)
		{
			if (collection == null)
			{
				throw new ArgumentNullException();
			}
			Initialize(collection.items, collection.size);
		}

		private void Initialize(T[] items, int size)
		{
			base.items = new T[size];
			Array.Copy(items, 0, base.items, 0, size);
			base.size = size;
		}

		internal override void Grow(int desired)
		{
			throw new InvalidOperationException();
		}

		protected override void OnAdd(T item, int index)
		{
			throw new InvalidOperationException();
		}

		protected override void OnClear()
		{
			throw new InvalidOperationException();
		}

		protected override void OnInsert(T item, int index)
		{
			throw new InvalidOperationException();
		}

		protected override void OnRemove(T item, int index)
		{
			throw new InvalidOperationException();
		}

		protected override void OnSet(T item, int index)
		{
			throw new InvalidOperationException();
		}
	}
}
namespace Mono.Cecil
{
	internal static class Mixin
	{
		public enum Argument
		{
			name,
			fileName,
			fullName,
			stream,
			type,
			method,
			field,
			parameters,
			module,
			modifierType,
			eventType,
			fieldType,
			declaringType,
			returnType,
			propertyType,
			interfaceType
		}

		public static Version ZeroVersion = new Version(0, 0, 0, 0);

		public const int NotResolvedMarker = -2;

		public const int NoDataMarker = -1;

		internal static object NoValue = new object();

		internal static object NotResolved = new object();

		public const string mscorlib = "mscorlib";

		public const string system_runtime = "System.Runtime";

		public const string system_private_corelib = "System.Private.CoreLib";

		public const string netstandard = "netstandard";

		public const int TableCount = 58;

		public const int CodedIndexCount = 14;

		public static bool IsNullOrEmpty<T>(this T[] self)
		{
			if (self != null)
			{
				return self.Length == 0;
			}
			return true;
		}

		public static bool IsNullOrEmpty<T>(this Collection<T> self)
		{
			if (self != null)
			{
				return self.size == 0;
			}
			return true;
		}

		public static T[] Resize<T>(this T[] self, int length)
		{
			Array.Resize(ref self, length);
			return self;
		}

		public static T[] Add<T>(this T[] self, T item)
		{
			if (self == null)
			{
				self = new T[1] { item };
				return self;
			}
			self = self.Resize(self.Length + 1);
			self[^1] = item;
			return self;
		}

		public static Version CheckVersion(Version version)
		{
			if (version == null)
			{
				return ZeroVersion;
			}
			if (version.Build == -1)
			{
				return new Version(version.Major, version.Minor, 0, 0);
			}
			if (version.Revision == -1)
			{
				return new Version(version.Major, version.Minor, version.Build, 0);
			}
			return version;
		}

		public static bool TryGetUniqueDocument(this MethodDebugInformation info, out Document document)
		{
			document = info.SequencePoints[0].Document;
			for (int i = 1; i < info.SequencePoints.Count; i++)
			{
				if (info.SequencePoints[i].Document != document)
				{
					return false;
				}
			}
			return true;
		}

		public static void ResolveConstant(this IConstantProvider self, ref object constant, ModuleDefinition module)
		{
			if (module == null)
			{
				constant = NoValue;
				return;
			}
			lock (module.SyncRoot)
			{
				if (constant != NotResolved)
				{
					return;
				}
				if (module.HasImage())
				{
					constant = module.Read(self, (IConstantProvider provider, MetadataReader reader) => reader.ReadConstant(provider));
				}
				else
				{
					constant = NoValue;
				}
			}
		}

		public static bool GetHasCustomAttributes(this ICustomAttributeProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.HasCustomAttributes(provider));
			}
			return false;
		}

		public static Collection<CustomAttribute> GetCustomAttributes(this ICustomAttributeProvider self, ref Collection<CustomAttribute> variable, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return variable = new Collection<CustomAttribute>();
			}
			return module.Read(ref variable, self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.ReadCustomAttributes(provider));
		}

		public static bool ContainsGenericParameter(this IGenericInstance self)
		{
			Collection<TypeReference> genericArguments = self.GenericArguments;
			for (int i = 0; i < genericArguments.Count; i++)
			{
				if (genericArguments[i].ContainsGenericParameter)
				{
					return true;
				}
			}
			return false;
		}

		public static void GenericInstanceFullName(this IGenericInstance self, StringBuilder builder)
		{
			builder.Append("<");
			Collection<TypeReference> genericArguments = self.GenericArguments;
			for (int i = 0; i < genericArguments.Count; i++)
			{
				if (i > 0)
				{
					builder.Append(",");
				}
				builder.Append(genericArguments[i].FullName);
			}
			builder.Append(">");
		}

		public static bool GetHasGenericParameters(this IGenericParameterProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (IGenericParameterProvider provider, MetadataReader reader) => reader.HasGenericParameters(provider));
			}
			return false;
		}

		public static Collection<GenericParameter> GetGenericParameters(this IGenericParameterProvider self, ref Collection<GenericParameter> collection, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return collection = new GenericParameterCollection(self);
			}
			return module.Read(ref collection, self, (IGenericParameterProvider provider, MetadataReader reader) => reader.ReadGenericParameters(provider));
		}

		public static bool GetHasMarshalInfo(this IMarshalInfoProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.HasMarshalInfo(provider));
			}
			return false;
		}

		public static MarshalInfo GetMarshalInfo(this IMarshalInfoProvider self, ref MarshalInfo variable, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return null;
			}
			return module.Read(ref variable, self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.ReadMarshalInfo(provider));
		}

		public static bool GetAttributes(this uint self, uint attributes)
		{
			return (self & attributes) != 0;
		}

		public static uint SetAttributes(this uint self, uint attributes, bool value)
		{
			if (value)
			{
				return self | attributes;
			}
			return self & ~attributes;
		}

		public static bool GetMaskedAttributes(this uint self, uint mask, uint attributes)
		{
			return (self & mask) == attributes;
		}

		public static uint SetMaskedAttributes(this uint self, uint mask, uint attributes, bool value)
		{
			if (value)
			{
				self &= ~mask;
				return self | attributes;
			}
			return self & ~(mask & attributes);
		}

		public static bool GetAttributes(this ushort self, ushort attributes)
		{
			return (self & attributes) != 0;
		}

		public static ushort SetAttributes(this ushort self, ushort attributes, bool value)
		{
			if (value)
			{
				return (ushort)(self | attributes);
			}
			return (ushort)(self & ~attributes);
		}

		public static bool GetMaskedAttributes(this ushort self, ushort mask, uint attributes)
		{
			return (self & mask) == attributes;
		}

		public static ushort SetMaskedAttributes(this ushort self, ushort mask, uint attributes, bool value)
		{
			if (value)
			{
				self = (ushort)(self & ~mask);
				return (ushort)(self | attributes);
			}
			return (ushort)(self & ~(mask & attributes));
		}

		public static bool HasImplicitThis(this IMethodSignature self)
		{
			if (self.HasThis)
			{
				return !self.ExplicitThis;
			}
			return false;
		}

		public static void MethodSignatureFullName(this IMethodSignature self, StringBuilder builder)
		{
			builder.Append("(");
			if (self.HasParameters)
			{
				Collection<ParameterDefinition> parameters = self.Parameters;
				for (int i = 0; i < parameters.Count; i++)
				{
					ParameterDefinition parameterDefinition = parameters[i];
					if (i > 0)
					{
						builder.Append(",");
					}
					if (parameterDefinition.ParameterType.IsSentinel)
					{
						builder.Append("...,");
					}
					builder.Append(parameterDefinition.ParameterType.FullName);
				}
			}
			builder.Append(")");
		}

		public static void CheckModule(ModuleDefinition module)
		{
			if (module == null)
			{
				throw new ArgumentNullException(Argument.module.ToString());
			}
		}

		public static bool TryGetAssemblyNameReference(this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
		{
			Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences;
			for (int i = 0; i < assemblyReferences.Count; i++)
			{
				AssemblyNameReference assemblyNameReference = assemblyReferences[i];
				if (Equals(name_reference, assemblyNameReference))
				{
					assembly_reference = assemblyNameReference;
					return true;
				}
			}
			assembly_reference = null;
			return false;
		}

		private static bool Equals(byte[] a, byte[] b)
		{
			if (a == b)
			{
				return true;
			}
			if (a == null)
			{
				return false;
			}
			if (a.Length != b.Length)
			{
				return false;
			}
			for (int i = 0; i < a.Length; i++)
			{
				if (a[i] != b[i])
				{
					return false;
				}
			}
			return true;
		}

		private static bool Equals<T>(T a, T b) where T : class, IEquatable<T>
		{
			if (a == b)
			{
				return true;
			}
			return a?.Equals(b) ?? false;
		}

		private static bool Equals(AssemblyNameReference a, AssemblyNameReference b)
		{
			if (a == b)
			{
				return true;
			}
			if (a.Name != b.Name)
			{
				return false;
			}
			if (!Equals(a.Version, b.Version))
			{
				return false;
			}
			if (a.Culture != b.Culture)
			{
				return false;
			}
			if (!Equals(a.PublicKeyToken, b.PublicKeyToken))
			{
				return false;
			}
			return true;
		}

		public static ParameterDefinition GetParameter(this Mono.Cecil.Cil.MethodBody self, int index)
		{
			MethodDefinition method = self.method;
			if (method.HasThis)
			{
				if (index == 0)
				{
					return self.ThisParameter;
				}
				index--;
			}
			Collection<ParameterDefinition> parameters = method.Parameters;
			if (index < 0 || index >= parameters.size)
			{
				return null;
			}
			return parameters[index];
		}

		public static VariableDefinition GetVariable(this Mono.Cecil.Cil.MethodBody self, int index)
		{
			Collection<VariableDefinition> variables = self.Variables;
			if (index < 0 || index >= variables.size)
			{
				return null;
			}
			return variables[index];
		}

		public static bool GetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics)
		{
			return (self.SemanticsAttributes & semantics) != 0;
		}

		public static void SetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics, bool value)
		{
			if (value)
			{
				self.SemanticsAttributes |= semantics;
			}
			else
			{
				self.SemanticsAttributes &= (MethodSemanticsAttributes)(ushort)(~(int)semantics);
			}
		}

		public static bool IsVarArg(this IMethodSignature self)
		{
			return self.CallingConvention == MethodCallingConvention.VarArg;
		}

		public static int GetSentinelPosition(this IMethodSignature self)
		{
			if (!self.HasParameters)
			{
				return -1;
			}
			Collection<ParameterDefinition> parameters = self.Parameters;
			for (int i = 0; i < parameters.Count; i++)
			{
				if (parameters[i].ParameterType.IsSentinel)
				{
					return i;
				}
			}
			return -1;
		}

		public static void CheckName(object name)
		{
			if (name == null)
			{
				throw new ArgumentNullException(Argument.name.ToString());
			}
		}

		public static void CheckName(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				throw new ArgumentNullOrEmptyException(Argument.name.ToString());
			}
		}

		public static void CheckFileName(string fileName)
		{
			if (string.IsNullOrEmpty(fileName))
			{
				throw new ArgumentNullOrEmptyException(Argument.fileName.ToString());
			}
		}

		public static void CheckFullName(string fullName)
		{
			if (string.IsNullOrEmpty(fullName))
			{
				throw new ArgumentNullOrEmptyException(Argument.fullName.ToString());
			}
		}

		public static void CheckStream(object stream)
		{
			if (stream == null)
			{
				throw new ArgumentNullException(Argument.stream.ToString());
			}
		}

		public static void CheckWriteSeek(Stream stream)
		{
			if (!stream.CanWrite || !stream.CanSeek)
			{
				throw new ArgumentException("Stream must be writable and seekable.");
			}
		}

		public static void CheckReadSeek(Stream stream)
		{
			if (!stream.CanRead || !stream.CanSeek)
			{
				throw new ArgumentException("Stream must be readable and seekable.");
			}
		}

		public static void CheckType(object type)
		{
			if (type == null)
			{
				throw new ArgumentNullException(Argument.type.ToString());
			}
		}

		public static void CheckType(object type, Argument argument)
		{
			if (type == null)
			{
				throw new ArgumentNullException(argument.ToString());
			}
		}

		public static void CheckField(object field)
		{
			if (field == null)
			{
				throw new ArgumentNullException(Argument.field.ToString());
			}
		}

		public static void CheckMethod(object method)
		{
			if (method == null)
			{
				throw new ArgumentNullException(Argument.method.ToString());
			}
		}

		public static void CheckParameters(object parameters)
		{
			if (parameters == null)
			{
				throw new ArgumentNullException(Argument.parameters.ToString());
			}
		}

		public static uint GetTimestamp()
		{
			return (uint)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
		}

		public static bool HasImage(this ModuleDefinition self)
		{
			return self?.HasImage ?? false;
		}

		public static string GetFileName(this Stream self)
		{
			if (!(self is FileStream fileStream))
			{
				return string.Empty;
			}
			return Path.GetFullPath(fileStream.Name);
		}

		public static void CopyTo(this Stream self, Stream target)
		{
			byte[] array = new byte[8192];
			int count;
			while ((count = self.Read(array, 0, array.Length)) > 0)
			{
				target.Write(array, 0, count);
			}
		}

		public static TargetRuntime ParseRuntime(this string self)
		{
			if (string.IsNullOrEmpty(self))
			{
				return TargetRuntime.Net_4_0;
			}
			switch (self[1])
			{
			case '1':
				if (self[3] != '0')
				{
					return TargetRuntime.Net_1_1;
				}
				return TargetRuntime.Net_1_0;
			case '2':
				return TargetRuntime.Net_2_0;
			default:
				return TargetRuntime.Net_4_0;
			}
		}

		public static string RuntimeVersionString(this TargetRuntime runtime)
		{
			return runtime switch
			{
				TargetRuntime.Net_1_0 => "v1.0.3705", 
				TargetRuntime.Net_1_1 => "v1.1.4322", 
				TargetRuntime.Net_2_0 => "v2.0.50727", 
				_ => "v4.0.30319", 
			};
		}

		public static bool IsWindowsMetadata(this ModuleDefinition module)
		{
			return module.MetadataKind != MetadataKind.Ecma335;
		}

		public static byte[] ReadAll(this Stream self)
		{
			MemoryStream memoryStream = new MemoryStream((int)self.Length);
			byte[] array = new byte[1024];
			int count;
			while ((count = self.Read(array, 0, array.Length)) != 0)
			{
				memoryStream.Write(array, 0, count);
			}
			return memoryStream.ToArray();
		}

		public static void Read(object o)
		{
		}

		public static bool GetHasSecurityDeclarations(this ISecurityDeclarationProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.HasSecurityDeclarations(provider));
			}
			return false;
		}

		public static Collection<SecurityDeclaration> GetSecurityDeclarations(this ISecurityDeclarationProvider self, ref Collection<SecurityDeclaration> variable, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return variable = new Collection<SecurityDeclaration>();
			}
			return module.Read(ref variable, self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.ReadSecurityDeclarations(provider));
		}

		public static TypeReference GetEnumUnderlyingType(this TypeDefinition self)
		{
			Collection<FieldDefinition> fields = self.Fields;
			for (int i = 0; i < fields.Count; i++)
			{
				FieldDefinition fieldDefinition = fields[i];
				if (!fieldDefinition.IsStatic)
				{
					return fieldDefinition.FieldType;
				}
			}
			throw new ArgumentException();
		}

		public static TypeDefinition GetNestedType(this TypeDefinition self, string fullname)
		{
			if (!self.HasNestedTypes)
			{
				return null;
			}
			Collection<TypeDefinition> nestedTypes = self.NestedTypes;
			for (int i = 0; i < nestedTypes.Count; i++)
			{
				TypeDefinition typeDefinition = nestedTypes[i];
				if (typeDefinition.TypeFullName() == fullname)
				{
					return typeDefinition;
				}
			}
			return null;
		}

		public static bool IsPrimitive(this ElementType self)
		{
			switch (self)
			{
			case ElementType.Boolean:
			case ElementType.Char:
			case ElementType.I1:
			case ElementType.U1:
			case ElementType.I2:
			case ElementType.U2:
			case ElementType.I4:
			case ElementType.U4:
			case ElementType.I8:
			case ElementType.U8:
			case ElementType.R4:
			case ElementType.R8:
			case ElementType.I:
			case ElementType.U:
				return true;
			default:
				return false;
			}
		}

		public static string TypeFullName(this TypeReference self)
		{
			if (!string.IsNullOrEmpty(self.Namespace))
			{
				return self.Namespace + "." + self.Name;
			}
			return self.Name;
		}

		public static bool IsTypeOf(this TypeReference self, string @namespace, string name)
		{
			if (self.Name == name)
			{
				return self.Namespace == @namespace;
			}
			return false;
		}

		public static bool IsTypeSpecification(this TypeReference type)
		{
			switch (type.etype)
			{
			case ElementType.Ptr:
			case ElementType.ByRef:
			case ElementType.Var:
			case ElementType.Array:
			case ElementType.GenericInst:
			case ElementType.FnPtr:
			case ElementType.SzArray:
			case ElementType.MVar:
			case ElementType.CModReqD:
			case ElementType.CModOpt:
			case ElementType.Sentinel:
			case ElementType.Pinned:
				return true;
			default:
				return false;
			}
		}

		public static TypeDefinition CheckedResolve(this TypeReference self)
		{
			return self.Resolve() ?? throw new ResolutionException(self);
		}

		public static bool TryGetCoreLibraryReference(this ModuleDefinition module, out AssemblyNameReference reference)
		{
			Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences;
			for (int i = 0; i < assemblyReferences.Count; i++)
			{
				reference = assemblyReferences[i];
				if (IsCoreLibrary(reference))
				{
					return true;
				}
			}
			reference = null;
			return false;
		}

		public static bool IsCoreLibrary(this ModuleDefinition module)
		{
			if (module.Assembly == null)
			{
				return false;
			}
			if (!IsCoreLibrary(module.Assembly.Name))
			{
				return false;
			}
			if (module.HasImage && module.Read(module, (ModuleDefinition m, MetadataReader reader) => reader.image.GetTableLength(Table.AssemblyRef) > 0))
			{
				return false;
			}
			return true;
		}

		public static void KnownValueType(this TypeReference type)
		{
			if (!type.IsDefinition)
			{
				type.IsValueType = true;
			}
		}

		private static bool IsCoreLibrary(AssemblyNameReference reference)
		{
			string name = reference.Name;
			switch (name)
			{
			default:
				return name == "netstandard";
			case "mscorlib":
			case "System.Runtime":
			case "System.Private.CoreLib":
				return true;
			}
		}

		public static ImageDebugHeaderEntry GetCodeViewEntry(this ImageDebugHeader header)
		{
			return header.GetEntry(ImageDebugType.CodeView);
		}

		public static ImageDebugHeaderEntry GetDeterministicEntry(this ImageDebugHeader header)
		{
			return header.GetEntry(ImageDebugType.Deterministic);
		}

		public static ImageDebugHeader AddDeterministicEntry(this ImageDebugHeader header)
		{
			ImageDebugDirectory directory = default(ImageDebugDirectory);
			directory.Type = ImageDebugType.Deterministic;
			ImageDebugHeaderEntry imageDebugHeaderEntry = new ImageDebugHeaderEntry(directory, Empty<byte>.Array);
			if (header == null)
			{
				return new ImageDebugHeader(imageDebugHeaderEntry);
			}
			ImageDebugHeaderEntry[] array = new ImageDebugHeaderEntry[header.Entries.Length + 1];
			Array.Copy(header.Entries, array, header.Entries.Length);
			array[^1] = imageDebugHeaderEntry;
			return new ImageDebugHeader(array);
		}

		public static ImageDebugHeaderEntry GetEmbeddedPortablePdbEntry(this ImageDebugHeader header)
		{
			return header.GetEntry(ImageDebugType.EmbeddedPortablePdb);
		}

		private static ImageDebugHeaderEntry GetEntry(this ImageDebugHeader header, ImageDebugType type)
		{
			if (!header.HasEntries)
			{
				return null;
			}
			for (int i = 0; i < header.Entries.Length; i++)
			{
				ImageDebugHeaderEntry imageDebugHeaderEntry = header.Entries[i];
				if (imageDebugHeaderEntry.Directory.Type == type)
				{
					return imageDebugHeaderEntry;
				}
			}
			return null;
		}

		public static string GetPdbFileName(string assemblyFileName)
		{
			return Path.ChangeExtension(assemblyFileName, ".pdb");
		}

		public static string GetMdbFileName(string assemblyFileName)
		{
			return assemblyFileName + ".mdb";
		}

		public static bool IsPortablePdb(string fileName)
		{
			using FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
			return IsPortablePdb(stream);
		}

		public static bool IsPortablePdb(Stream stream)
		{
			if (stream.Length < 4)
			{
				return false;
			}
			long position = stream.Position;
			try
			{
				return new BinaryReader(stream).ReadUInt32() == 1112167234;
			}
			finally
			{
				stream.Position = position;
			}
		}

		public static uint ReadCompressedUInt32(this byte[] data, ref int position)
		{
			uint result;
			if ((data[position] & 0x80) == 0)
			{
				result = data[position];
				position++;
			}
			else if ((data[position] & 0x40) == 0)
			{
				result = (uint)((data[position] & -129) << 8);
				result |= data[position + 1];
				position += 2;
			}
			else
			{
				result = (uint)((data[position] & -193) << 24);
				result |= (uint)(data[position + 1] << 16);
				result |= (uint)(data[position + 2] << 8);
				result |= data[position + 3];
				position += 4;
			}
			return result;
		}

		public static MetadataToken GetMetadataToken(this CodedIndex self, uint data)
		{
			uint rid;
			TokenType type;
			switch (self)
			{
			case CodedIndex.TypeDefOrRef:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_006d;
				case 2u:
					goto IL_0078;
				default:
					goto end_IL_0001;
				}
				type = TokenType.TypeDef;
				goto IL_05b3;
			case CodedIndex.HasConstant:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_00ad;
				case 2u:
					goto IL_00b8;
				default:
					goto end_IL_0001;
				}
				type = TokenType.Field;
				goto IL_05b3;
			case CodedIndex.HasCustomAttribute:
				rid = data >> 5;
				switch (data & 0x1F)
				{
				case 0u:
					break;
				case 1u:
					goto IL_013a;
				case 2u:
					goto IL_0145;
				case 3u:
					goto IL_0150;
				case 4u:
					goto IL_015b;
				case 5u:
					goto IL_0166;
				case 6u:
					goto IL_0171;
				case 7u:
					goto IL_017c;
				case 8u:
					goto IL_0183;
				case 9u:
					goto IL_018e;
				case 10u:
					goto IL_0199;
				case 11u:
					goto IL_01a4;
				case 12u:
					goto IL_01af;
				case 13u:
					goto IL_01ba;
				case 14u:
					goto IL_01c5;
				case 15u:
					goto IL_01d0;
				case 16u:
					goto IL_01db;
				case 17u:
					goto IL_01e6;
				case 18u:
					goto IL_01f1;
				case 19u:
					goto IL_01fc;
				case 20u:
					goto IL_0207;
				case 21u:
					goto IL_0212;
				default:
					goto end_IL_0001;
				}
				type = TokenType.Method;
				goto IL_05b3;
			case CodedIndex.HasFieldMarshal:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Param;
				}
				else
				{
					type = TokenType.Field;
				}
				goto IL_05b3;
			}
			case CodedIndex.HasDeclSecurity:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_0271;
				case 2u:
					goto IL_027c;
				default:
					goto end_IL_0001;
				}
				type = TokenType.TypeDef;
				goto IL_05b3;
			case CodedIndex.MemberRefParent:
				rid = data >> 3;
				switch (data & 7)
				{
				case 0u:
					break;
				case 1u:
					goto IL_02b9;
				case 2u:
					goto IL_02c4;
				case 3u:
					goto IL_02cf;
				case 4u:
					goto IL_02da;
				default:
					goto end_IL_0001;
				}
				type = TokenType.TypeDef;
				goto IL_05b3;
			case CodedIndex.HasSemantics:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Property;
				}
				else
				{
					type = TokenType.Event;
				}
				goto IL_05b3;
			}
			case CodedIndex.MethodDefOrRef:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.MemberRef;
				}
				else
				{
					type = TokenType.Method;
				}
				goto IL_05b3;
			}
			case CodedIndex.MemberForwarded:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Method;
				}
				else
				{
					type = TokenType.Field;
				}
				goto IL_05b3;
			}
			case CodedIndex.Implementation:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_038d;
				case 2u:
					goto IL_0398;
				default:
					goto end_IL_0001;
				}
				type = TokenType.File;
				goto IL_05b3;
			case CodedIndex.CustomAttributeType:
			{
				rid = data >> 3;
				uint num = data & 7u;
				if (num != 2)
				{
					if (num != 3)
					{
						break;
					}
					type = TokenType.MemberRef;
				}
				else
				{
					type = TokenType.Method;
				}
				goto IL_05b3;
			}
			case CodedIndex.ResolutionScope:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_03f8;
				case 2u:
					goto IL_0403;
				case 3u:
					goto IL_040e;
				default:
					goto end_IL_0001;
				}
				type = TokenType.Module;
				goto IL_05b3;
			case CodedIndex.TypeOrMethodDef:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Method;
				}
				else
				{
					type = TokenType.TypeDef;
				}
				goto IL_05b3;
			}
			case CodedIndex.HasCustomDebugInformation:
				{
					rid = data >> 5;
					switch (data & 0x1F)
					{
					case 0u:
						break;
					case 1u:
						goto IL_04ce;
					case 2u:
						goto IL_04d9;
					case 3u:
						goto IL_04e4;
					case 4u:
						goto IL_04ef;
					case 5u:
						goto IL_04fa;
					case 6u:
						goto IL_0505;
					case 7u:
						goto IL_0510;
					case 8u:
						goto IL_0517;
					case 9u:
						goto IL_0522;
					case 10u:
						goto IL_052d;
					case 11u:
						goto IL_0535;
					case 12u:
						goto IL_053d;
					case 13u:
						goto IL_0545;
					case 14u:
						goto IL_054d;
					case 15u:
						goto IL_0555;
					case 16u:
						goto IL_055d;
					case 17u:
						goto IL_0565;
					case 18u:
						goto IL_056d;
					case 19u:
						goto IL_0575;
					case 20u:
						goto IL_057d;
					case 21u:
						goto IL_0585;
					case 22u:
						goto IL_058d;
					case 23u:
						goto IL_0595;
					case 24u:
						goto IL_059d;
					case 25u:
						goto IL_05a5;
					case 26u:
						goto IL_05ad;
					default:
						goto end_IL_0001;
					}
					type = TokenType.Method;
					goto IL_05b3;
				}
				IL_05ad:
				type = TokenType.ImportScope;
				goto IL_05b3;
				IL_05a5:
				type = TokenType.LocalConstant;
				goto IL_05b3;
				IL_059d:
				type = TokenType.LocalVariable;
				goto IL_05b3;
				IL_0595:
				type = TokenType.LocalScope;
				goto IL_05b3;
				IL_058d:
				type = TokenType.Document;
				goto IL_05b3;
				IL_0585:
				type = TokenType.MethodSpec;
				goto IL_05b3;
				IL_057d:
				type = TokenType.GenericParamConstraint;
				goto IL_05b3;
				IL_0575:
				type = TokenType.GenericParam;
				goto IL_05b3;
				IL_056d:
				type = TokenType.ManifestResource;
				goto IL_05b3;
				IL_0565:
				type = TokenType.ExportedType;
				goto IL_05b3;
				IL_055d:
				type = TokenType.File;
				goto IL_05b3;
				IL_0555:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_054d:
				type = TokenType.Assembly;
				goto IL_05b3;
				IL_0545:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_053d:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_0535:
				type = TokenType.Signature;
				goto IL_05b3;
				IL_052d:
				type = TokenType.Event;
				goto IL_05b3;
				IL_0522:
				type = TokenType.Property;
				goto IL_05b3;
				IL_0517:
				type = TokenType.Permission;
				goto IL_05b3;
				IL_0510:
				type = TokenType.Module;
				goto IL_05b3;
				IL_0505:
				type = TokenType.MemberRef;
				goto IL_05b3;
				IL_04fa:
				type = TokenType.InterfaceImpl;
				goto IL_05b3;
				IL_04ef:
				type = TokenType.Param;
				goto IL_05b3;
				IL_04e4:
				type = TokenType.TypeDef;
				goto IL_05b3;
				IL_04d9:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_04ce:
				type = TokenType.Field;
				goto IL_05b3;
				IL_01db:
				type = TokenType.File;
				goto IL_05b3;
				IL_01d0:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_01ba:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_01c5:
				type = TokenType.Assembly;
				goto IL_05b3;
				IL_040e:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_0403:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_03f8:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_01af:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_01a4:
				type = TokenType.Signature;
				goto IL_05b3;
				IL_018e:
				type = TokenType.Property;
				goto IL_05b3;
				IL_0199:
				type = TokenType.Event;
				goto IL_05b3;
				IL_0398:
				type = TokenType.ExportedType;
				goto IL_05b3;
				IL_038d:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_0183:
				type = TokenType.Permission;
				goto IL_05b3;
				IL_017c:
				type = TokenType.Module;
				goto IL_05b3;
				IL_0166:
				type = TokenType.InterfaceImpl;
				goto IL_05b3;
				IL_0171:
				type = TokenType.MemberRef;
				goto IL_05b3;
				IL_015b:
				type = TokenType.Param;
				goto IL_05b3;
				IL_0145:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_0150:
				type = TokenType.TypeDef;
				goto IL_05b3;
				IL_013a:
				type = TokenType.Field;
				goto IL_05b3;
				IL_006d:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_02da:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_02cf:
				type = TokenType.Method;
				goto IL_05b3;
				IL_02c4:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_02b9:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_00b8:
				type = TokenType.Property;
				goto IL_05b3;
				IL_027c:
				type = TokenType.Assembly;
				goto IL_05b3;
				IL_0271:
				type = TokenType.Method;
				goto IL_05b3;
				IL_00ad:
				type = TokenType.Param;
				goto IL_05b3;
				IL_05b3:
				return new MetadataToken(type, rid);
				IL_0078:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_0212:
				type = TokenType.MethodSpec;
				goto IL_05b3;
				IL_0207:
				type = TokenType.GenericParamConstraint;
				goto IL_05b3;
				IL_01fc:
				type = TokenType.GenericParam;
				goto IL_05b3;
				IL_01f1:
				type = TokenType.ManifestResource;
				goto IL_05b3;
				IL_01e6:
				type = TokenType.ExportedType;
				goto IL_05b3;
				end_IL_0001:
				break;
			}
			return MetadataToken.Zero;
		}

		public static uint CompressMetadataToken(this CodedIndex self, MetadataToken token)
		{
			uint result = 0u;
			if (token.RID == 0)
			{
				return result;
			}
			switch (self)
			{
			case CodedIndex.TypeDefOrRef:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.TypeRef:
					return result | 1u;
				case TokenType.TypeSpec:
					return result | 2u;
				}
				break;
			case CodedIndex.HasConstant:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.Field:
					return result | 0u;
				case TokenType.Param:
					return result | 1u;
				case TokenType.Property:
					return result | 2u;
				}
				break;
			case CodedIndex.HasCustomAttribute:
				result = token.RID << 5;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 0u;
				case TokenType.Field:
					return result | 1u;
				case TokenType.TypeRef:
					return result | 2u;
				case TokenType.TypeDef:
					return result | 3u;
				case TokenType.Param:
					return result | 4u;
				case TokenType.InterfaceImpl:
					return result | 5u;
				case TokenType.MemberRef:
					return result | 6u;
				case TokenType.Module:
					return result | 7u;
				case TokenType.Permission:
					return result | 8u;
				case TokenType.Property:
					return result | 9u;
				case TokenType.Event:
					return result | 0xAu;
				case TokenType.Signature:
					return result | 0xBu;
				case TokenType.ModuleRef:
					return result | 0xCu;
				case TokenType.TypeSpec:
					return result | 0xDu;
				case TokenType.Assembly:
					return result | 0xEu;
				case TokenType.AssemblyRef:
					return result | 0xFu;
				case TokenType.File:
					return result | 0x10u;
				case TokenType.ExportedType:
					return result | 0x11u;
				case TokenType.ManifestResource:
					return result | 0x12u;
				case TokenType.GenericParam:
					return result | 0x13u;
				case TokenType.GenericParamConstraint:
					return result | 0x14u;
				case TokenType.MethodSpec:
					return result | 0x15u;
				}
				break;
			case CodedIndex.HasFieldMarshal:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Field:
					return result | 0u;
				case TokenType.Param:
					return result | 1u;
				}
				break;
			case CodedIndex.HasDeclSecurity:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.Method:
					return result | 1u;
				case TokenType.Assembly:
					return result | 2u;
				}
				break;
			case CodedIndex.MemberRefParent:
				result = token.RID << 3;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.TypeRef:
					return result | 1u;
				case TokenType.ModuleRef:
					return result | 2u;
				case TokenType.Method:
					return result | 3u;
				case TokenType.TypeSpec:
					return result | 4u;
				}
				break;
			case CodedIndex.HasSemantics:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Event:
					return result | 0u;
				case TokenType.Property:
					return result | 1u;
				}
				break;
			case CodedIndex.MethodDefOrRef:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 0u;
				case TokenType.MemberRef:
					return result | 1u;
				}
				break;
			case CodedIndex.MemberForwarded:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Field:
					return result | 0u;
				case TokenType.Method:
					return result | 1u;
				}
				break;
			case CodedIndex.Implementation:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.File:
					return result | 0u;
				case TokenType.AssemblyRef:
					return result | 1u;
				case TokenType.ExportedType:
					return result | 2u;
				}
				break;
			case CodedIndex.CustomAttributeType:
				result = token.RID << 3;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 2u;
				case TokenType.MemberRef:
					return result | 3u;
				}
				break;
			case CodedIndex.ResolutionScope:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.Module:
					return result | 0u;
				case TokenType.ModuleRef:
					return result | 1u;
				case TokenType.AssemblyRef:
					return result | 2u;
				case TokenType.TypeRef:
					return result | 3u;
				}
				break;
			case CodedIndex.TypeOrMethodDef:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.Method:
					return result | 1u;
				}
				break;
			case CodedIndex.HasCustomDebugInformation:
				result = token.RID << 5;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 0u;
				case TokenType.Field:
					return result | 1u;
				case TokenType.TypeRef:
					return result | 2u;
				case TokenType.TypeDef:
					return result | 3u;
				case TokenType.Param:
					return result | 4u;
				case TokenType.InterfaceImpl:
					return result | 5u;
				case TokenType.MemberRef:
					return result | 6u;
				case TokenType.Module:
					return result | 7u;
				case TokenType.Permission:
					return result | 8u;
				case TokenType.Property:
					return result | 9u;
				case TokenType.Event:
					return result | 0xAu;
				case TokenType.Signature:
					return result | 0xBu;
				case TokenType.ModuleRef:
					return result | 0xCu;
				case TokenType.TypeSpec:
					return result | 0xDu;
				case TokenType.Assembly:
					return result | 0xEu;
				case TokenType.AssemblyRef:
					return result | 0xFu;
				case TokenType.File:
					return result | 0x10u;
				case TokenType.ExportedType:
					return result | 0x11u;
				case TokenType.ManifestResource:
					return result | 0x12u;
				case TokenType.GenericParam:
					return result | 0x13u;
				case TokenType.GenericParamConstraint:
					return result | 0x14u;
				case TokenType.MethodSpec:
					return result | 0x15u;
				case TokenType.Document:
					return result | 0x16u;
				case TokenType.LocalScope:
					return result | 0x17u;
				case TokenType.LocalVariable:
					return result | 0x18u;
				case TokenType.LocalConstant:
					return result | 0x19u;
				case TokenType.ImportScope:
					return result | 0x1Au;
				}
				break;
			}
			throw new ArgumentException();
		}

		public static int GetSize(this CodedIndex self, Func<Table, int> counter)
		{
			int num;
			Table[] array;
			switch (self)
			{
			case CodedIndex.TypeDefOrRef:
				num = 2;
				array = new Table[3]
				{
					Table.TypeDef,
					Table.TypeRef,
					Table.TypeSpec
				};
				break;
			case CodedIndex.HasConstant:
				num = 2;
				array = new Table[3]
				{
					Table.Field,
					Table.Param,
					Table.Property
				};
				break;
			case CodedIndex.HasCustomAttribute:
				num = 5;
				array = new Table[22]
				{
					Table.Method,
					Table.Field,
					Table.TypeRef,
					Table.TypeDef,
					Table.Param,
					Table.InterfaceImpl,
					Table.MemberRef,
					Table.Module,
					Table.DeclSecurity,
					Table.Property,
					Table.Event,
					Table.StandAloneSig,
					Table.ModuleRef,
					Table.TypeSpec,
					Table.Assembly,
					Table.AssemblyRef,
					Table.File,
					Table.ExportedType,
					Table.ManifestResource,
					Table.GenericParam,
					Table.GenericParamConstraint,
					Table.MethodSpec
				};
				break;
			case CodedIndex.HasFieldMarshal:
				num = 1;
				array = new Table[2]
				{
					Table.Field,
					Table.Param
				};
				break;
			case CodedIndex.HasDeclSecurity:
				num = 2;
				array = new Table[3]
				{
					Table.TypeDef,
					Table.Method,
					Table.Assembly
				};
				break;
			case CodedIndex.MemberRefParent:
				num = 3;
				array = new Table[5]
				{
					Table.TypeDef,
					Table.TypeRef,
					Table.ModuleRef,
					Table.Method,
					Table.TypeSpec
				};
				break;
			case CodedIndex.HasSemantics:
				num = 1;
				array = new Table[2]
				{
					Table.Event,
					Table.Property
				};
				break;
			case CodedIndex.MethodDefOrRef:
				num = 1;
				array = new Table[2]
				{
					Table.Method,
					Table.MemberRef
				};
				break;
			case CodedIndex.MemberForwarded:
				num = 1;
				array = new Table[2]
				{
					Table.Field,
					Table.Method
				};
				break;
			case CodedIndex.Implementation:
				num = 2;
				array = new Table[3]
				{
					Table.File,
					Table.AssemblyRef,
					Table.ExportedType
				};
				break;
			case CodedIndex.CustomAttributeType:
				num = 3;
				array = new Table[2]
				{
					Table.Method,
					Table.MemberRef
				};
				break;
			case CodedIndex.ResolutionScope:
				num = 2;
				array = new Table[4]
				{
					Table.Module,
					Table.ModuleRef,
					Table.AssemblyRef,
					Table.TypeRef
				};
				break;
			case CodedIndex.TypeOrMethodDef:
				num = 1;
				array = new Table[2]
				{
					Table.TypeDef,
					Table.Method
				};
				break;
			case CodedIndex.HasCustomDebugInformation:
				num = 5;
				array = new Table[27]
				{
					Table.Method,
					Table.Field,
					Table.TypeRef,
					Table.TypeDef,
					Table.Param,
					Table.InterfaceImpl,
					Table.MemberRef,
					Table.Module,
					Table.DeclSecurity,
					Table.Property,
					Table.Event,
					Table.StandAloneSig,
					Table.ModuleRef,
					Table.TypeSpec,
					Table.Assembly,
					Table.AssemblyRef,
					Table.File,
					Table.ExportedType,
					Table.ManifestResource,
					Table.GenericParam,
					Table.GenericParamConstraint,
					Table.MethodSpec,
					Table.Document,
					Table.LocalScope,
					Table.LocalVariable,
					Table.LocalConstant,
					Table.ImportScope
				};
				break;
			default:
				throw new ArgumentException();
			}
			int num2 = 0;
			for (int i = 0; i < array.Length; i++)
			{
				num2 = Math.Max(counter(array[i]), num2);
			}
			if (num2 >= 1 << 16 - num)
			{
				return 4;
			}
			return 2;
		}

		public static RSA CreateRSA(this StrongNameKeyPair key_pair)
		{
			if (!TryGetKeyContainer(key_pair, out var key, out var key_container))
			{
				return CryptoConvert.FromCapiKeyBlob(key);
			}
			return new RSACryptoServiceProvider(new CspParameters
			{
				Flags = CspProviderFlags.UseMachineKeyStore,
				KeyContainerName = key_container,
				KeyNumber = 2
			});
		}

		private static bool TryGetKeyContainer(ISerializable key_pair, out byte[] key, out string key_container)
		{
			SerializationInfo serializationInfo = new SerializationInfo(typeof(StrongNameKeyPair), new FormatterConverter());
			key_pair.GetObjectData(serializationInfo, default(StreamingContext));
			key = (byte[])serializationInfo.GetValue("_keyPairArray", typeof(byte[]));
			key_container = serializationInfo.GetString("_keyPairContainer");
			return key_container != null;
		}
	}
	public struct ArrayDimension
	{
		private int? lower_bound;

		private int? upper_bound;

		public int? LowerBound
		{
			get
			{
				return lower_bound;
			}
			set
			{
				lower_bound = value;
			}
		}

		public int? UpperBound
		{
			get
			{
				return upper_bound;
			}
			set
			{
				upper_bound = value;
			}
		}

		public bool IsSized
		{
			get
			{
				if (!lower_bound.HasValue)
				{
					return upper_bound.HasValue;
				}
				return true;
			}
		}

		public ArrayDimension(int? lowerBound, int? upperBound)
		{
			lower_bound = lowerBound;
			upper_bound = upperBound;
		}

		public override string ToString()
		{
			if (IsSized)
			{
				return lower_bound + "..." + upper_bound;
			}
			return string.Empty;
		}
	}
	public sealed class ArrayType : TypeSpecification
	{
		private Collection<ArrayDimension> dimensions;

		public Collection<ArrayDimension> Dimensions
		{
			get
			{
				if (dimensions != null)
				{
					return dimensions;
				}
				dimensions = new Collection<ArrayDimension>();
				dimensions.Add(default(ArrayDimension));
				return dimensions;
			}
		}

		public int Rank
		{
			get
			{
				if (dimensions != null)
				{
					return dimensions.Count;
				}
				return 1;
			}
		}

		public bool IsVector
		{
			get
			{
				if (dimensions == null)
				{
					return true;
				}
				if (dimensions.Count > 1)
				{
					return false;
				}
				return !dimensions[0].IsSized;
			}
		}

		public override bool IsValueType
		{
			get
			{
				return false;
			}
			set
			{
				throw new InvalidOperationException();
			}
		}

		public override string Name => base.Name + Suffix;

		public override string FullName => base.FullName + Suffix;

		private string Suffix
		{
			get
			{
				if (IsVector)
				{
					return "[]";
				}
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append("[");
				for (int i = 0; i < dimensions.Count; i++)
				{
					if (i > 0)
					{
						stringBuilder.Append(",");
					}
					stringBuilder.Append(dimensions[i].ToString());
				}
				stringBuilder.Append("]");
				return stringBuilder.ToString();
			}
		}

		public override bool IsArray => true;

		public ArrayType(TypeReference type)
			: base(type)
		{
			Mixin.CheckType(type);
			etype = Mono.Cecil.Metadata.ElementType.Array;
		}

		public ArrayType(TypeReference type, int rank)
			: this(type)
		{
			Mixin.CheckType(type);
			if (rank != 1)
			{
				dimensions = new Collection<ArrayDimension>(rank);
				for (int i = 0; i < rank; i++)
				{
					dimensions.Add(default(ArrayDimension));
				}
				etype = Mono.Cecil.Metadata.ElementType.Array;
			}
		}
	}
	public sealed class AssemblyDefinition : ICustomAttributeProvider, IMetadataTokenProvider, ISecurityDeclarationProvider, IDisposable
	{
		private AssemblyNameDefinition name;

		internal ModuleDefinition main_module;

		private Collection<ModuleDefinition> modules;

		private Collection<CustomAttribute> custom_attributes;

		private Collection<SecurityDeclaration> security_declarations;

		public AssemblyNameDefinition Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
			}
		}

		public string FullName
		{
			get
			{
				if (name == null)
				{
					return string.Empty;
				}
				return name.FullName;
			}
		}

		public MetadataToken MetadataToken
		{
			get
			{
				return new MetadataToken(TokenType.Assembly, 1);
			}
			set
			{
			}
		}

		public Collection<ModuleDefinition> Modules
		{
			get
			{
				if (modules != null)
				{
					return modules;
				}
				if (main_module.HasImage)
				{
					return main_module.Read(ref modules, this, (AssemblyDefinition _, MetadataReader reader) => reader.ReadModules());
				}
				return modules = new Collection<ModuleDefinition>(1) { main_module };
			}
		}

		public ModuleDefinition MainModule => main_module;

		public MethodDefinition EntryPoint
		{
			get
			{
				return main_module.EntryPoint;
			}
			set
			{
				main_module.EntryPoint = value;
			}
		}

		public bool HasCustomAttributes
		{
			get
			{
				if (custom_attributes != null)
				{
					return custom_attributes.Count > 0;
				}
				return this.GetHasCustomAttributes(main_module);
			}
		}

		public Collection<CustomAttribute> CustomAttributes => custom_attributes ?? this.GetCustomAttributes(ref custom_attributes, main_module);

		public bool HasSecurityDeclarations
		{
			get
			{
				if (security_declarations != null)
				{
					return security_declarations.Count > 0;
				}
				return this.GetHasSecurityDeclarations(main_module);
			}
		}

		public Collection<SecurityDeclaration> SecurityDeclarations => security_declarations ?? this.GetSecurityDeclarations(ref security_declarations, main_module);

		internal AssemblyDefinition()
		{
		}

		public void Dispose()
		{
			if (modules == null)
			{
				main_module.Dispose();
				return;
			}
			Collection<ModuleDefinition> collection = Modules;
			for (int i = 0; i < collection.Count; i++)
			{
				collection[i].Dispose();
			}
		}

		public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleKind kind)
		{
			return CreateAssembly(assemblyName, moduleName, new ModuleParameters
			{
				Kind = kind
			});
		}

		public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleParameters parameters)
		{
			if (assemblyName == null)
			{
				throw new ArgumentNullException("assemblyName");
			}
			if (moduleName == null)
			{
				throw new ArgumentNullException("moduleName");
			}
			Mixin.CheckParameters(parameters);
			if (parameters.Kind == ModuleKind.NetModule)
			{
				throw new ArgumentException("kind");
			}
			AssemblyDefinition assembly = ModuleDefinition.CreateModule(moduleName, parameters).Assembly;
			assembly.Name = assemblyName;
			return assembly;
		}

		public static AssemblyDefinition ReadAssembly(string fileName)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(fileName));
		}

		public static AssemblyDefinition ReadAssembly(string fileName, ReaderParameters parameters)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(fileName, parameters));
		}

		public static AssemblyDefinition ReadAssembly(Stream stream)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(stream));
		}

		public static AssemblyDefinition ReadAssembly(Stream stream, ReaderParameters parameters)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(stream, parameters));
		}

		private static AssemblyDefinition ReadAssembly(ModuleDefinition module)
		{
			return module.Assembly ?? throw new ArgumentException();
		}

		public void Write(string fileName)
		{
			Write(fileName, new WriterParameters());
		}

		public void Write(string fileName, WriterParameters parameters)
		{
			main_module.Write(fileName, parameters);
		}

		public void Write()
		{
			main_module.Write();
		}

		public void Write(WriterParameters parameters)
		{
			main_module.Write(parameters);
		}

		public void Write(Stream stream)
		{
			Write(stream, new WriterParameters());
		}

		public void Write(Stream stream, WriterParameters parameters)
		{
			main_module.Write(stream, parameters);
		}

		public override string ToString()
		{
			return FullName;
		}
	}
	[Flags]
	public enum AssemblyAttributes : uint
	{
		PublicKey = 1u,
		SideBySideCompatible = 0u,
		Retargetable = 0x100u,
		WindowsRuntime = 0x200u,
		DisableJITCompileOptimizer = 0x4000u,
		EnableJITCompileTracking = 0x8000u
	}
	public enum AssemblyHashAlgorithm : uint
	{
		None = 0u,
		Reserved = 32771u,
		SHA1 = 32772u
	}
	public sealed class AssemblyLinkedResource : Resource
	{
		private AssemblyNameReference reference;

		public AssemblyNameReference Assembly
		{
			get
			{
				return reference;
			}
			set
			{
				reference = value;
			}
		}

		public override ResourceType ResourceType => ResourceType.AssemblyLinked;

		public AssemblyLinkedResource(string name, ManifestResourceAttributes flags)
			: base(name, flags)
		{
		}

		public AssemblyLinkedResource(string name, ManifestResourceAttributes flags, AssemblyNameReference reference)
			: base(name, flags)
		{
			this.reference = reference;
		}
	}
	public sealed class AssemblyNameDefinition : AssemblyNameReference
	{
		public override byte[] Hash => Empty<byte>.Array;

		internal AssemblyNameDefinition()
		{
			token = new MetadataToken(TokenType.Assembly, 1);
		}

		public AssemblyNameDefinition(string name, Version version)
			: base(name, version)
		{
			token = new MetadataToken(TokenType.Assembly, 1);
		}
	}
	public class AssemblyNameReference : IMetadataScope, IMetadataTokenProvider
	{
		private string name;

		private string culture;

		private Version version;

		private uint attributes;

		private byte[] public_key;

		private byte[] public_key_token;

		private AssemblyHashAlgorithm hash_algorithm;

		private byte[] hash;

		internal MetadataToken token;

		private string full_name;

		public string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
				full_name = null;
			}
		}

		public string Culture
		{
			get
			{
				return culture;
			}
			set
			{
				culture = value;
				full_name = null;
			}
		}

		public Version Version
		{
			get
			{
				return version;
			}
			set
			{
				version = Mixin.CheckVersion(value);
				full_name = null;
			}
		}

		public AssemblyAttributes Attributes
		{
			get
			{
				return (AssemblyAttributes)attributes;
			}
			set
			{
				attributes = (uint)value;
			}
		}

		public bool HasPublicKey
		{
			get
			{
				return attributes.GetAttributes(1u);
			}
			set
			{
				attributes = attributes.SetAttributes(1u, value);
			}
		}

		public bool IsSideBySideCompatible
		{
			get
			{
				return attributes.GetAttributes(0u);
			}
			set
			{
				attributes = attributes.SetAttributes(0u, value);
			}
		}

		public bool IsRetargetable
		{
			get
			{
				return attributes.GetAttributes(256u);
			}
			set
			{
				attributes = attributes.SetAttributes(256u, value);
			}
		}

		public bool IsWindowsRuntime
		{
			get
			{
				return attributes.GetAttributes(512u);
			}
			set
			{
				attributes = attributes.SetAttributes(512u, value);
			}
		}

		public byte[] PublicKey
		{
			get
			{
				return public_key ?? Empty<byte>.Array;
			}
			set
			{
				public_key = value;
				HasPublicKey = !public_key.IsNullOrEmpty();
				public_key_token = Empty<byte>.Array;
				full_name = null;
			}
		}

		public byte[] PublicKeyToken
		{
			get
			{
				if (public_key_token.IsNullOrEmpty() && !public_key.IsNullOrEmpty())
				{
					byte[] array = HashPublicKey();
					byte[] array2 = new byte[8];
					Array.Copy(array, array.Length - 8, array2, 0, 8);
					Array.Reverse((Array)array2, 0, 8);
					public_key_token = array2;
				}
				return public_key_token ?? Empty<byte>.Array;
			}
			set
			{
				public_key_token = value;
				full_name = null;
			}
		}

		public virtual MetadataScopeType MetadataScopeType => MetadataScopeType.AssemblyNameReference;

		public string FullName
		{
			get
			{
				if (full_name != null)
				{
					return full_name;
				}
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append(name);
				stringBuilder.Append(", ");
				stringBuilder.Append("Version=");
				stringBuilder.Append(version.ToString(4));
				stringBuilder.Append(", ");
				stringBuilder.Append("Culture=");
				stringBuilder.Append(string.IsNullOrEmpty(culture) ? "neutral" : culture);
				stringBuilder.Append(", ");
				stringBuilder.Append("PublicKeyToken=");
				byte[] publicKeyToken = PublicKeyToken;
				if (!publicKeyToken.IsNullOrEmpty() && publicKeyToken.Length != 0)
				{
					for (int i = 0; i < publicKeyToken.Length; i++)
					{
						stringBuilder.Append(publicKeyToken[i].ToString("x2"));
					}
				}
				else
				{
					stringBuilder.Append("null");
				}
				if (IsRetargetable)
				{
					stringBuilder.Append(", ");
					stringBuilder.Append("Retargetable=Yes");
				}
				return full_name = stringBuilder.ToString();
			}
		}

		public AssemblyHashAlgorithm HashAlgorithm
		{
			get
			{
				return hash_algorithm;
			}
			set
			{
				hash_algorithm = value;
			}
		}

		public virtual byte[] Hash
		{
			get
			{
				return hash;
			}
			set
			{
				hash = value;
			}
		}

		public MetadataToken MetadataToken
		{
			get
			{
				return token;
			}
			set
			{
				token = value;
			}
		}

		private byte[] HashPublicKey()
		{
			AssemblyHashAlgorithm assemblyHashAlgorithm = hash_algorithm;
			HashAlgorithm hashAlgorithm = ((assemblyHashAlgorithm != AssemblyHashAlgorithm.Reserved) ? ((HashAlgorithm)SHA1.Create()) : ((HashAlgorithm)MD5.Create()));
			using (hashAlgorithm)
			{
				return hashAlgorithm.ComputeHash(public_key);
			}
		}

		public static AssemblyNameReference Parse(string fullName)
		{
			if (fullName == null)
			{
				throw new ArgumentNullException("fullName");
			}
			if (fullName.Length == 0)
			{
				throw new ArgumentException("Name can not be empty");
			}
			AssemblyNameReference assemblyNameReference = new AssemblyNameReference();
			string[] array = fullName.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (i == 0)
				{
					assemblyNameReference.Name = text;
					continue;
				}
				string[] array2 = text.Split(new char[1] { '=' });
				if (array2.Length != 2)
				{
					throw new ArgumentException("Malformed name");
				}
				switch (array2[0].ToLowerInvariant())
				{
				case "version":
					assemblyNameReference.Version = new Version(array2[1]);
					break;
				case "culture":
					assemblyNameReference.Culture = ((array2[1] == "neutral") ? "" : array2[1]);
					break;
				case "publickeytoken":
				{
					string text2 = array2[1];
					if (!(text2 == "null"))
					{
						assemblyNameReference.PublicKeyToken = new byte[text2.Length / 2];
						for (int j = 0; j < assemblyNameReference.PublicKeyToken.Length; j++)
						{
							assemblyNameReference.PublicKeyToken[j] = byte.Parse(text2.Substring(j * 2, 2), NumberStyles.HexNumber);
						}
					}
					break;
				}
				}
			}
			return assemblyNameReference;
		}

		internal AssemblyNameReference()
		{
			version = Mixin.ZeroVersion;
			token = new MetadataToken(TokenType.AssemblyRef);
		}

		public AssemblyNameReference(string name, Version version)
		{
			Mixin.CheckName(name);
			this.name = name;
			this.version = Mixin.CheckVersion(version);
			hash_algorithm = AssemblyHashAlgorithm.None;
			token = new MetadataToken(TokenType.AssemblyRef);
		}

		public override string ToString()
		{
			return FullName;
		}
	}
	internal abstract class ModuleReader
	{
		protected readonly ModuleDefinition module;

		protected ModuleReader(Image image, ReadingMode mode)
		{
			module = new ModuleDefinition(image);
			module.ReadingMode = mode;
		}

		protected abstract void ReadModule();

		public abstract void ReadSymbols(ModuleDefinition module);

		protected void ReadModuleManifest(MetadataReader reader)
		{
			reader.Populate(module);
			ReadAssembly(reader);
		}

		private void ReadAssembly(MetadataReader reader)
		{
			AssemblyNameDefinition assemblyNameDefinition = reader.ReadAssemblyNameDefinition();
			if (assemblyNameDefinition == null)
			{
				module.kind = ModuleKind.NetModule;
				return;
			}
			AssemblyDefinition assemblyDefinition = new AssemblyDefinition();
			assemblyDefinition.Name = assemblyNameDefinition;
			module.assembly = assemblyDefinition;
			assemblyDefinition.main_module = module;
		}

		public static ModuleDefinition CreateModule(Image image, ReaderParameters parameters)
		{
			ModuleReader moduleReader = CreateModuleReader(image, parameters.ReadingMode);
			ModuleDefinition moduleDefinition = moduleReader.module;
			if (parameters.assembly_resolver != null)
			{
				moduleDefinition.assembly_resolver = Disposable.NotOwned(parameters.assembly_resolver);
			}
			if (parameters.metadata_resolver != null)
			{
				moduleDefinition.metadata_resolver = parameters.metadata_resolver;
			}
			if (parameters.metadata_importer_provider != null)
			{
				moduleDefinition.metadata_importer = parameters.metadata_importer_provider.GetMetadataImporter(moduleDefinition);
			}
			if (parameters.reflection_importer_provider != null)
			{
				moduleDefinition.reflection_importer = parameters.reflection_importer_provider.GetReflectionImporter(moduleDefinition);
			}
			GetMetadataKind(moduleDefinition, parameters);
			moduleReader.ReadModule();
			ReadSymbols(moduleDefinition, parameters);
			moduleReader.ReadSymbols(moduleDefinition);
			if (parameters.ReadingMode == ReadingMode.Immediate)
			{
				moduleDefinition.MetadataSystem.Clear();
			}
			return moduleDefinition;
		}

		private static void ReadSymbols(ModuleDefinition module, ReaderParameters parameters)
		{
			ISymbolReaderProvider symbolReaderProvider = parameters.SymbolReaderProvider;
			if (symbolReaderProvider == null && parameters.ReadSymbols)
			{
				symbolReaderProvider = new DefaultSymbolReaderProvider();
			}
			if (symbolReaderProvider != null)
			{
				module.SymbolReaderProvider = symbolReaderProvider;
				ISymbolReader symbolReader = ((parameters.SymbolStream != null) ? symbolReaderProvider.GetSymbolReader(module, parameters.SymbolStream) : symbolReaderProvider.GetSymbolReader(module, module.FileName));
				if (symbolReader != null)
				{
					try
					{
						module.ReadSymbols(symbolReader, parameters.ThrowIfSymbolsAreNotMatching);
					}
					catch (Exception)
					{
						symbolReader.Dispose();
						throw;
					}
				}
			}
			if (module.Image.HasDebugTables())
			{
				module.ReadSymbols(new PortablePdbReader(module.Image, module));
			}
		}

		private static void GetMetadataKind(ModuleDefinition module, ReaderParameters parameters)
		{
			if (!parameters.ApplyWindowsRuntimeProjections)
			{
				module.MetadataKind = MetadataKind.Ecma335;
				return;
			}
			string runtimeVersion = module.RuntimeVersion;
			if (!runtimeVersion.Contains("WindowsRuntime"))
			{
				module.MetadataKind = MetadataKind.Ecma335;
			}
			else if (runtimeVersion.Contains("CLR"))
			{
				module.MetadataKind = MetadataKind.ManagedWindowsMetadata;
			}
			else
			{
				module.MetadataKind = MetadataKind.WindowsMetadata;
			}
		}

		private static ModuleReader CreateModuleReader(Image image, ReadingMode mode)
		{
			return mode switch
			{
				ReadingMode.Immediate => new ImmediateModuleReader(image), 
				ReadingMode.Deferred => new DeferredModuleReader(image), 
				_ => throw new ArgumentException(), 
			};
		}
	}
	internal sealed class ImmediateModuleReader : ModuleReader
	{
		private bool resolve_attributes;

		public ImmediateModuleReader(Image image)
			: base(image, ReadingMode.Immediate)
		{
		}

		protected override void ReadModule()
		{
			module.Read(module, delegate(ModuleDefinition module, MetadataReader reader)
			{
				ReadModuleManifest(reader);
				ReadModule(module, resolve_attributes: true);
			});
		}

		public void ReadModule(ModuleDefinition module, bool resolve_attributes)
		{
			this.resolve_attributes = resolve_attributes;
			if (module.HasAssemblyReferences)
			{
				Mixin.Read(module.AssemblyReferences);
			}
			if (module.HasResources)
			{
				Mixin.Read(module.Resources);
			}
			if (module.HasModuleReferences)
			{
				Mixin.Read(module.ModuleReferences);
			}
			if (module.HasTypes)
			{
				ReadTypes(module.Types);
			}
			if (module.HasExportedTypes)
			{
				Mixin.Read(module.ExportedTypes);
			}
			ReadCustomAttributes(module);
			AssemblyDefinition assembly = module.Assembly;
			if (assembly != null)
			{
				ReadCustomAttributes(assembly);
				ReadSecurityDeclarations(assembly);
			}
		}

		private void ReadTypes(Collection<TypeDefinition> types)
		{
			for (int i = 0; i < types.Count; i++)
			{
				ReadType(types[i]);
			}
		}

		private void ReadType(TypeDefinition type)
		{
			ReadGenericParameters(type);
			if (type.HasInterfaces)
			{
				ReadInterfaces(type);
			}
			if (type.HasNestedTypes)
			{
				ReadTypes(type.NestedTypes);
			}
			if (type.HasLayoutInfo)
			{
				Mixin.Read(type.ClassSize);
			}
			if (type.HasFields)
			{
				ReadFields(type);
			}
			if (type.HasMethods)
			{
				ReadMethods(type);
			}
			if (type.HasProperties)
			{
				ReadProperties(type);
			}
			if (type.HasEvents)
			{
				ReadEvents(type);
			}
			ReadSecurityDeclarations(type);
			ReadCustomAttributes(type);
		}

		private void ReadInterfaces(TypeDefinition type)
		{
			Collection<InterfaceImplementation> interfaces = type.Interfaces;
			for (int i = 0; i < interfaces.Count; i++)
			{
				ReadCustomAttributes(interfaces[i]);
			}
		}

		private void ReadGenericParameters(IGenericParameterProvider provider)
		{
			if (!provider.HasGenericParameters)
			{
				return;
			}
			Collection<GenericParameter> genericParameters = provider.GenericParameters;
			for (int i = 0; i < genericParameters.Count; i++)
			{
				GenericParameter genericParameter = genericParameters[i];
				if (genericParameter.HasConstraints)
				{
					Mixin.Read(genericParameter.Constraints);
				}
				ReadCustomAttributes(genericParameter);
			}
		}

		private void ReadSecurityDeclarations(ISecurityDeclarationProvider provider)
		{
			if (!provider.HasSecurityDeclarations)
			{
				return;
			}
			Collection<SecurityDeclaration> securityDeclarations = provider.SecurityDeclarations;
			if (resolve_attributes)
			{
				for (int i = 0; i < securityDeclarations.Count; i++)
				{
					Mixin.Read(securityDeclarations[i].SecurityAttributes);
				}
			}
		}

		private void ReadCustomAttributes(ICustomAttributeProvider provider)
		{
			if (!provider.HasCustomAttributes)
			{
				return;
			}
			Collection<CustomAttribute> customAttributes = provider.CustomAttributes;
			if (resolve_attributes)
			{
				for (int i = 0; i < customAttributes.Count; i++)
				{
					Mixin.Read(customAttributes[i].ConstructorArguments);
				}
			}
		}

		private void ReadFields(TypeDefinition type)
		{
			Collection<FieldDefinition> fields = type.Fields;
			for (int i = 0; i < fields.Count; i++)
			{
				FieldDefinition fieldDefinition = fields[i];
				if (fieldDefinition.HasConstant)
				{
					Mixin.Read(fieldDefinition.Constant);
				}
				if (fieldDefinition.HasLayoutInfo)
				{
					Mixin.Read(fieldDefinition.Offset);
				}
				if (fieldDefinition.RVA > 0)
				{
					Mixin.Read(fieldDefinition.InitialValue);
				}
				if (fieldDefinition.HasMarshalInfo)
				{
					Mixin.Read(fieldDefinition.MarshalInfo);
				}
				ReadCustomAttributes(fieldDefinition);
			}
		}

		private void ReadMethods(TypeDefinition type)
		{
			Collection<MethodDefinition> methods = type.Methods;
			for (int i = 0; i < methods.Count; i++)
			{
				MethodDefinition methodDefinition = methods[i];
				ReadGenericParameters(methodDefinition);
				if (methodDefinition.HasParameters)
				{
					ReadParameters(methodDefinition);
				}
				if (methodDefinition.HasOverrides)
				{
					Mixin.Read(methodDefinition.Overrides);
				}
				if (methodDefinition.IsPInvokeImpl)
				{
					Mixin.Read(methodDefinition.PInvokeInfo);
				}
				ReadSecurityDeclarations(methodDefinition);
				ReadCustomAttributes(methodDefinition);
				MethodReturnType methodReturnType = methodDefinition.MethodReturnType;
				if (methodReturnType.HasConstant)
				{
					Mixin.Read(methodReturnType.Constant);
				}
				if (methodReturnType.HasMarshalInfo)
				{
					Mixin.Read(methodReturnType.MarshalInfo);
				}
				ReadCustomAttributes(methodReturnType);
			}
		}

		private void ReadParameters(MethodDefinition method)
		{
			Collection<ParameterDefinition> parameters = method.Parameters;
			for (int i = 0; i < parameters.Count; i++)
			{
				ParameterDefinition parameterDefinition = parameters[i];
				if (parameterDefinition.HasConstant)
				{
					Mixin.Read(parameterDefinition.Constant);
				}
				if (parameterDefinition.HasMarshalInfo)
				{
					Mixin.Read(parameterDefinition.MarshalInfo);
				}
				ReadCustomAttributes(parameterDefinition);
			}
		}

		private void ReadProperties(TypeDefinition type)
		{
			Collection<PropertyDefinition> properties = type.Properties;
			for (int i = 0; i < properties.Count; i++)
			{
				PropertyDefinition propertyDefinition = properties[i];
				Mixin.Read(propertyDefinition.GetMethod);
				if (propertyDefinition.HasConstant)
				{
					Mixin.Read(propertyDefinition.Constant);
				}
				ReadCustomAttributes(propertyDefinition);
			}
		}

		private void ReadEvents(TypeDefinition type)
		{
			Collection<EventDefinition> events = type.Events;
			for (int i = 0; i < events.Count; i++)
			{
				EventDefinition eventDefinition = events[i];
				Mixin.Read(eventDefinition.AddMethod);
				ReadCustomAttributes(eventDefinition);
			}
		}

		public override void ReadSymbols(ModuleDefinition module)
		{
			if (module.symbol_reader != null)
			{
				ReadTypesSymbols(module.Types, module.symbol_reader);
			}
		}

		private void ReadTypesSymbols(Collection<TypeDefinition> types, ISymbolReader symbol_reader)
		{
			for (int i = 0; i < types.Count; i++)
			{
				TypeDefinition typeDefinition = types[i];
				if (typeDefinition.HasNestedTypes)
				{
					ReadTypesSymbols(typeDefinition.NestedTypes, symbol_reader);
				}
				if (typeDefinition.HasMethods)
				{
					ReadMethodsSymbols(typeDefinition, symbol_reader);
				}
			}
		}

		private void ReadMethodsSymbols(TypeDefinition type, ISymbolReader symbol_reader)
		{
			Collection<MethodDefinition> methods = type.Methods;
			for (int i = 0; i < methods.Count; i++)
			{
				MethodDefinition methodDefinition = methods[i];
				if (methodDefinition.HasBody && methodDefinition.token.RID != 0 && methodDefinition.debug_info == null)
				{
					methodDefinition.debug_info = symbol_reader.Read(methodDefinition);
				}
			}
		}
	}
	internal sealed class DeferredModuleReader : ModuleReader
	{
		public DeferredModuleReader(Image image)
			: base(image, ReadingMode.Deferred)
		{
		}

		protected override void ReadModule()
		{
			module.Read(module, delegate(ModuleDefinition _, MetadataReader reader)
			{
				ReadModuleManifest(reader);
			});
		}

		public override void ReadSymbols(ModuleDefinition module)
		{
		}
	}
	internal sealed class MetadataReader : ByteBuffer
	{
		internal readonly Image image;

		internal readonly ModuleDefinition module;

		internal readonly MetadataSystem metadata;

		internal CodeReader code;

		internal IGenericContext context;

		private readonly MetadataReader metadata_reader;

		public MetadataReader(ModuleDefinition module)
			: base(module.Image.TableHeap.data)
		{
			image = module.Image;
			this.module = module;
			metadata = module.MetadataSystem;
			code = new CodeReader(this);
		}

		public MetadataReader(Image image, ModuleDefinition module, MetadataReader metadata_reader)
			: base(image.TableHeap.data)
		{
			this.image = image;
			this.module = module;
			metadata = module.MetadataSystem;
			this.metadata_reader = metadata_reader;
		}

		private int GetCodedIndexSize(CodedIndex index)
		{
			return image.GetCodedIndexSize(index);
		}

		private uint ReadByIndexSize(int size)
		{
			if (size == 4)
			{
				return ReadUInt32();
			}
			return ReadUInt16();
		}

		private byte[] ReadBlob()
		{
			BlobHeap blobHeap = image.BlobHeap;
			if (blobHeap == null)
			{
				position += 2;
				return Empty<byte>.Array;
			}
			return blobHeap.Read(ReadBlobIndex());
		}

		private byte[] ReadBlob(uint signature)
		{
			BlobHeap blobHeap = image.BlobHeap;
			if (blobHeap == null)
			{
				return Empty<byte>.Array;
			}
			return blobHeap.Read(signature);
		}

		private uint ReadBlobIndex()
		{
			return ReadByIndexSize(image.BlobHeap?.IndexSize ?? 2);
		}

		private void GetBlobView(uint signature, out byte[] blob, out int index, out int count)
		{
			BlobHeap blobHeap = image.BlobHeap;
			if (blobHeap == null)
			{
				blob = null;
				index = (count = 0);
			}
			else
			{
				blobHeap.GetView(signature, out blob, out index, out count);
			}
		}

		private string ReadString()
		{
			return image.StringHeap.Read(ReadByIndexSize(image.StringHeap.IndexSize));
		}

		private uint ReadStringIndex()
		{
			return ReadByIndexSize(image.StringHeap.IndexSize);
		}

		private Guid ReadGuid()
		{
			return image.GuidHeap.Read(ReadByIndexSize(image.GuidHeap.IndexSize));
		}

		private uint ReadTableIndex(Table table)
		{
			return ReadByIndexSize(image.GetTableIndexSize(table));
		}

		private MetadataToken ReadMetadataToken(CodedIndex index)
		{
			return index.GetMetadataToken(ReadByIndexSize(GetCodedIndexSize(index)));
		}

		private int MoveTo(Table table)
		{
			TableInformation tableInformation = image.TableHeap[table];
			if (tableInformation.Length != 0)
			{
				position = (int)tableInformation.Offset;
			}
			return (int)tableInformation.Length;
		}

		private bool MoveTo(Table table, uint row)
		{
			TableInformation tableInformation = image.TableHeap[table];
			uint num = tableInformation.Length;
			if (num == 0 || row > num)
			{
				return false;
			}
			position = (int)(tableInformation.Offset + tableInformation.RowSize * (row - 1));
			return true;
		}

		public AssemblyNameDefinition ReadAssemblyNameDefinition()
		{
			if (MoveTo(Table.Assembly) == 0)
			{
				return null;
			}
			AssemblyNameDefinition assemblyNameDefinition = new AssemblyNameDefinition();
			assemblyNameDefinition.HashAlgorithm = (AssemblyHashAlgorithm)ReadUInt32();
			PopulateVersionAndFlags(assemblyNameDefinition);
			assemblyNameDefinition.PublicKey = ReadBlob();
			PopulateNameAndCulture(assemblyNameDefinition);
			return assemblyNameDefinition;
		}

		public ModuleDefinition Populate(ModuleDefinition module)
		{
			if (MoveTo(Table.Module) == 0)
			{
				return module;
			}
			Advance(2);
			module.Name = ReadString();
			module.Mvid = ReadGuid();
			return module;
		}

		private void InitializeAssemblyReferences()
		{
			if (metadata.AssemblyReferences != null)
			{
				return;
			}
			int num = MoveTo(Table.AssemblyRef);
			AssemblyNameReference[] array = (metadata.AssemblyReferences = new AssemblyNameReference[num]);
			for (uint num2 = 0u; num2 < num; num2++)
			{
				AssemblyNameReference assemblyNameReference = new AssemblyNameReference();
				assemblyNameReference.token = new MetadataToken(TokenType.AssemblyRef, num2 + 1);
				PopulateVersionAndFlags(assemblyNameReference);
				byte[] array2 = ReadBlob();
				if (assemblyNameReference.HasPublicKey)
				{
					assemblyNameReference.PublicKey = array2;
				}
				else
				{
					assemblyNameReference.PublicKeyToken = array2;
				}
				PopulateNameAndCulture(assemblyNameReference);
				assemblyNameReference.Hash = ReadBlob();
				array[num2] = assemblyNameReference;
			}
		}

		public Collection<AssemblyNameReference> ReadAssemblyReferences()
		{
			InitializeAssemblyReferences();
			Collection<AssemblyNameReference> collection = new Collection<AssemblyNameReference>(metadata.AssemblyReferences);
			if (module.IsWindowsMetadata())
			{
				module.Projections.AddVirtualReferences(collection);
			}
			return collection;
		}

		public MethodDefinition ReadEntryPoint()
		{
			if (module.Image.EntryPointToken == 0)
			{
				return null;
			}
			return GetMethodDefinition(new MetadataToken(module.Image.EntryPointToken).RID);
		}

		public Collection<ModuleDefinition> ReadModules()
		{
			Collection<ModuleDefinition> collection = new Collection<ModuleDefinition>(1);
			collection.Add(module);
			int num = MoveTo(Table.File);
			for (uint num2 = 1u; num2 <= num; num2++)
			{
				uint num3 = ReadUInt32();
				string name = ReadString();
				ReadBlobIndex();
				if (num3 == 0)
				{
					ReaderParameters parameters = new ReaderParameters
					{
						ReadingMode = module.ReadingMode,
						SymbolReaderProvider = module.SymbolReaderProvider,
						AssemblyResolver = module.AssemblyResolver
					};
					collection.Add(ModuleDefinition.ReadModule(GetModuleFileName(name), parameters));
				}
			}
			return collection;
		}

		private string GetModuleFileName(string name)
		{
			if (module.FileName == null)
			{
				throw new NotSupportedException();
			}
			return Path.Combine(Path.GetDirectoryName(module.FileName), name);
		}

		private void InitializeModuleReferences()
		{
			if (metadata.ModuleReferences == null)
			{
				int num = MoveTo(Table.ModuleRef);
				ModuleReference[] array = (metadata.ModuleReferences = new ModuleReference[num]);
				for (uint num2 = 0u; num2 < num; num2++)
				{
					ModuleReference moduleReference = new ModuleReference(ReadString());
					moduleReference.token = new MetadataToken(TokenType.ModuleRef, num2 + 1);
					array[num2] = moduleReference;
				}
			}
		}

		public Collection<ModuleReference> ReadModuleReferences()
		{
			InitializeModuleReferences();
			return new Collection<ModuleReference>(metadata.ModuleReferences);
		}

		public bool HasFileResource()
		{
			int num = MoveTo(Table.File);
			if (num == 0)
			{
				return false;
			}
			for (uint num2 = 1u; num2 <= num; num2++)
			{
				if (ReadFileRecord(num2).Col1 == FileAttributes.ContainsNoMetaData)
				{
					return true;
				}
			}
			return false;
		}

		public Collection<Resource> ReadResources()
		{
			int num = MoveTo(Table.ManifestResource);
			Collection<Resource> collection = new Collection<Resource>(num);
			for (int i = 1; i <= num; i++)
			{
				uint offset = ReadUInt32();
				ManifestResourceAttributes manifestResourceAttributes = (ManifestResourceAttributes)ReadUInt32();
				string name = ReadString();
				MetadataToken scope = ReadMetadataToken(CodedIndex.Implementation);
				Resource item;
				if (scope.RID == 0)
				{
					item = new EmbeddedResource(name, manifestResourceAttributes, offset, this);
				}
				else if (scope.TokenType == TokenType.AssemblyRef)
				{
					item = new AssemblyLinkedResource(name, manifestResourceAttributes)
					{
						Assembly = (AssemblyNameReference)GetTypeReferenceScope(scope)
					};
				}
				else
				{
					if (scope.TokenType != TokenType.File)
					{
						continue;
					}
					Row<FileAttributes, string, uint> row = ReadFileRecord(scope.RID);
					item = new LinkedResource(name, manifestResourceAttributes)
					{
						File = row.Col2,
						hash = ReadBlob(row.Col3)
					};
				}
				collection.Add(item);
			}
			return collection;
		}

		private Row<FileAttributes, string, uint> ReadFileRecord(uint rid)
		{
			int num = position;
			if (!MoveTo(Table.File, rid))
			{
				throw new ArgumentException();
			}
			Row<FileAttributes, string, uint> result = new Row<FileAttributes, string, uint>((FileAttributes)ReadUInt32(), ReadString(), ReadBlobIndex());
			position = num;
			return result;
		}

		public byte[] GetManagedResource(uint offset)
		{
			return image.GetReaderAt(image.Resources.VirtualAddress, offset, delegate(uint o, BinaryStreamReader reader)
			{
				reader.Advance((int)o);
				return reader.ReadBytes(reader.ReadInt32());
			}) ?? Empty<byte>.Array;
		}

		private void PopulateVersionAndFlags(AssemblyNameReference name)
		{
			name.Version = new Version(ReadUInt16(), ReadUInt16(), ReadUInt16(), ReadUInt16());
			name.Attributes = (AssemblyAttributes)ReadUInt32();
		}

		private void PopulateNameAndCulture(AssemblyNameReference name)
		{
			name.Name = ReadString();
			name.Culture = ReadString();
		}

		public TypeDefinitionCollection ReadTypes()
		{
			InitializeTypeDefinitions();
			TypeDefinition[] types = metadata.Types;
			int capacity = types.Length - metadata.NestedTypes.Count;
			TypeDefinitionCollection typeDefinitionCollection = new TypeDefinitionCollection(module, capacity);
			foreach (TypeDefinition typeDefinition in types)
			{
				if (!IsNested(typeDefinition.Attributes))
				{
					typeDefinitionCollection.Add(typeDefinition);
				}
			}
			if (image.HasTable(Table.MethodPtr) || image.HasTable(Table.FieldPtr))
			{
				CompleteTypes();
			}
			return typeDefinitionCollection;
		}

		private void CompleteTypes()
		{
			TypeDefinition[] types = metadata.Types;
			foreach (TypeDefinition obj in types)
			{
				Mixin.Read(obj.Fields);
				Mixin.Read(obj.Methods);
			}
		}

		private void InitializeTypeDefinitions()
		{
			if (metadata.Types != null)
			{
				return;
			}
			InitializeNestedTypes();
			InitializeFields();
			InitializeMethods();
			int num = MoveTo(Table.TypeDef);
			TypeDefinition[] array = (metadata.Types = new TypeDefinition[num]);
			for (uint num2 = 0u; num2 < num; num2++)
			{
				if (array[num2] == null)
				{
					array[num2] = ReadType(num2 + 1);
				}
			}
			if (module.IsWindowsMetadata())
			{
				for (uint num3 = 0u; num3 < num; num3++)
				{
					WindowsRuntimeProjections.Project(array[num3]);
				}
			}
		}

		private static bool IsNested(TypeAttributes attributes)
		{
			switch (attributes & TypeAttributes.VisibilityMask)
			{
			case TypeAttributes.NestedPublic:
			case TypeAttributes.NestedPrivate:
			case TypeAttributes.NestedFamily:
			case TypeAttributes.NestedAssembly:
			case TypeAttributes.NestedFamANDAssem:
			case TypeAttributes.VisibilityMask:
				return true;
			default:
				return false;
			}
		}

		public bool HasNestedTypes(TypeDefinition type)
		{
			InitializeNestedTypes();
			if (!metadata.TryGetNestedTypeMapping(type, out var mapping))
			{
				return false;
			}
			return mapping.Count > 0;
		}

		public Collection<TypeDefinition> ReadNestedTypes(TypeDefinition type)
		{
			InitializeNestedTypes();
			if (!metadata.TryGetNestedTypeMapping(type, out var mapping))
			{
				return new MemberDefinitionCollection<TypeDefinition>(type);
			}
			MemberDefinitionCollection<TypeDefinition> memberDefinitionCollection = new MemberDefinitionCollection<TypeDefinition>(type, mapping.Count);
			for (int i = 0; i < mapping.Count; i++)
			{
				TypeDefinition typeDefinition = GetTypeDefinition(mapping[i]);
				if (typeDefinition != null)
				{
					memberDefinitionCollection.Add(typeDefinition);
				}
			}
			metadata.RemoveNestedTypeMapping(type);
			return memberDefinitionCollection;
		}

		private void InitializeNestedTypes()
		{
			if (metadata.NestedTypes != null)
			{
				return;
			}
			int num = MoveTo(Table.NestedClass);
			metadata.NestedTypes = new Dictionary<uint, Collection<uint>>(num);
			metadata.ReverseNestedTypes = new Dictionary<uint, uint>(num);
			if (num != 0)
			{
				for (int i = 1; i <= num; i++)
				{
					uint nested = ReadTableIndex(Table.TypeDef);
					uint declaring = ReadTableIndex(Table.TypeDef);
					AddNestedMapping(declaring, nested);
				}
			}
		}

		private void AddNestedMapping(uint declaring, uint nested)
		{
			metadata.SetNestedTypeMapping(declaring, AddMapping(metadata.NestedTypes, declaring, nested));
			metadata.SetReverseNestedTypeMapping(nested, declaring);
		}

		private static Collection<TValue> AddMapping<TKey, TValue>(Dictionary<TKey, Collection<TValue>> cache, TKey key, TValue value)
		{
			if (!cache.TryGetValue(key, out var value2))
			{
				value2 = new Collection<TValue>();
			}
			value2.Add(value);
			return value2;
		}

		private TypeDefinition ReadType(uint rid)
		{
			if (!MoveTo(Table.TypeDef, rid))
			{
				return null;
			}
			TypeAttributes attributes = (TypeAttributes)ReadUInt32();
			string name = ReadString();
			TypeDefinition typeDefinition = new TypeDefinition(ReadString(), name, attributes);
			typeDefinition.token = new MetadataToken(TokenType.TypeDef, rid);
			typeDefinition.scope = module;
			typeDefinition.module = module;
			metadata.AddTypeDefinition(typeDefinition);
			context = typeDefinition;
			typeDefinition.BaseType = GetTypeDefOrRef(ReadMetadataToken(CodedIndex.TypeDefOrRef));
			typeDefinition.fields_range = ReadListRange(rid, Table.TypeDef, Table.Field);
			typeDefinition.methods_range = ReadListRange(rid, Table.TypeDef, Table.Method);
			if (IsNested(attributes))
			{
				typeDefinition.DeclaringType = GetNestedTypeDeclaringType(typeDefinition);
			}
			return typeDefinition;
		}

		private TypeDefinition GetNestedTypeDeclaringType(TypeDefinition type)
		{
			if (!metadata.TryGetReverseNestedTypeMapping(type, out var declaring))
			{
				return null;
			}
			metadata.RemoveReverseNestedTypeMapping(type);
			return GetTypeDefinition(declaring);
		}

		private Range ReadListRange(uint current_index, Table current, Table target)
		{
			Range result = default(Range);
			uint num = ReadTableIndex(target);
			if (num == 0)
			{
				return result;
			}
			TableInformation tableInformation = image.TableHeap[current];
			uint num2;
			if (current_index == tableInformation.Length)
			{
				num2 = image.TableHeap[target].Length + 1;
			}
			else
			{
				int num3 = position;
				position += (int)(tableInformation.RowSize - image.GetTableIndexSize(target));
				num2 = ReadTableIndex(target);
				position = num3;
			}
			result.Start = num;
			result.Length = num2 - num;
			return result;
		}

		public Row<short, int> ReadTypeLayout(TypeDefinition type)
		{
			InitializeTypeLayouts();
			uint rID = type.token.RID;
			if (!metadata.ClassLayouts.TryGetValue(rID, out var value))
			{
				return new Row<short, int>(-1, -1);
			}
			type.PackingSize = (short)value.Col1;
			type.ClassSize = (int)value.Col2;
			metadata.ClassLayouts.Remove(rID);
			return new Row<short, int>((short)value.Col1, (int)value.Col2);
		}

		private void InitializeTypeLayouts()
		{
			if (metadata.ClassLayouts == null)
			{
				int num = MoveTo(Table.ClassLayout);
				Dictionary<uint, Row<ushort, uint>> dictionary = (metadata.ClassLayouts = new Dictionary<uint, Row<ushort, uint>>(num));
				for (uint num2 = 0u; 

BooBoo Building/BepInEx/core/Mono.Cecil.Mdb.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using Mono.CompilerServices.SymbolWriter;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil.Mdb")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyVersion("0.10.4.0")]
namespace Mono.CompilerServices.SymbolWriter
{
	public class MonoSymbolFileException : Exception
	{
		public MonoSymbolFileException()
		{
		}

		public MonoSymbolFileException(string message, params object[] args)
			: base(string.Format(message, args))
		{
		}

		public MonoSymbolFileException(string message, Exception innerException)
			: base(message, innerException)
		{
		}
	}
	internal sealed class MyBinaryWriter : BinaryWriter
	{
		public MyBinaryWriter(Stream stream)
			: base(stream)
		{
		}

		public void WriteLeb128(int value)
		{
			Write7BitEncodedInt(value);
		}
	}
	internal class MyBinaryReader : BinaryReader
	{
		public MyBinaryReader(Stream stream)
			: base(stream)
		{
		}

		public int ReadLeb128()
		{
			return Read7BitEncodedInt();
		}

		public string ReadString(int offset)
		{
			long position = BaseStream.Position;
			BaseStream.Position = offset;
			string result = ReadString();
			BaseStream.Position = position;
			return result;
		}
	}
	public interface ISourceFile
	{
		SourceFileEntry Entry { get; }
	}
	public interface ICompileUnit
	{
		CompileUnitEntry Entry { get; }
	}
	public interface IMethodDef
	{
		string Name { get; }

		int Token { get; }
	}
	public class MonoSymbolFile : IDisposable
	{
		private List<MethodEntry> methods = new List<MethodEntry>();

		private List<SourceFileEntry> sources = new List<SourceFileEntry>();

		private List<CompileUnitEntry> comp_units = new List<CompileUnitEntry>();

		private Dictionary<int, AnonymousScopeEntry> anonymous_scopes;

		private OffsetTable ot;

		private int last_type_index;

		private int last_method_index;

		private int last_namespace_index;

		public readonly int MajorVersion = 50;

		public readonly int MinorVersion;

		public int NumLineNumbers;

		private MyBinaryReader reader;

		private Dictionary<int, SourceFileEntry> source_file_hash;

		private Dictionary<int, CompileUnitEntry> compile_unit_hash;

		private List<MethodEntry> method_list;

		private Dictionary<int, MethodEntry> method_token_hash;

		private Dictionary<string, int> source_name_hash;

		private Guid guid;

		internal int LineNumberCount;

		internal int LocalCount;

		internal int StringSize;

		internal int LineNumberSize;

		internal int ExtendedLineNumberSize;

		public int CompileUnitCount => ot.CompileUnitCount;

		public int SourceCount => ot.SourceCount;

		public int MethodCount => ot.MethodCount;

		public int TypeCount => ot.TypeCount;

		public int AnonymousScopeCount => ot.AnonymousScopeCount;

		public int NamespaceCount => last_namespace_index;

		public Guid Guid => guid;

		public OffsetTable OffsetTable => ot;

		public SourceFileEntry[] Sources
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				SourceFileEntry[] array = new SourceFileEntry[SourceCount];
				for (int i = 0; i < SourceCount; i++)
				{
					array[i] = GetSourceFile(i + 1);
				}
				return array;
			}
		}

		public CompileUnitEntry[] CompileUnits
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				CompileUnitEntry[] array = new CompileUnitEntry[CompileUnitCount];
				for (int i = 0; i < CompileUnitCount; i++)
				{
					array[i] = GetCompileUnit(i + 1);
				}
				return array;
			}
		}

		public MethodEntry[] Methods
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				lock (this)
				{
					read_methods();
					MethodEntry[] array = new MethodEntry[MethodCount];
					method_list.CopyTo(array, 0);
					return array;
				}
			}
		}

		internal MyBinaryReader BinaryReader
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				return reader;
			}
		}

		public MonoSymbolFile()
		{
			ot = new OffsetTable();
		}

		public int AddSource(SourceFileEntry source)
		{
			sources.Add(source);
			return sources.Count;
		}

		public int AddCompileUnit(CompileUnitEntry entry)
		{
			comp_units.Add(entry);
			return comp_units.Count;
		}

		public void AddMethod(MethodEntry entry)
		{
			methods.Add(entry);
		}

		public MethodEntry DefineMethod(CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, MethodEntry.Flags flags, int namespace_id)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			MethodEntry methodEntry = new MethodEntry(this, comp_unit, token, scope_vars, locals, lines, code_blocks, real_name, flags, namespace_id);
			AddMethod(methodEntry);
			return methodEntry;
		}

		internal void DefineAnonymousScope(int id)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			if (anonymous_scopes == null)
			{
				anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>();
			}
			anonymous_scopes.Add(id, new AnonymousScopeEntry(id));
		}

		internal void DefineCapturedVariable(int scope_id, string name, string captured_name, CapturedVariable.CapturedKind kind)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			anonymous_scopes[scope_id].AddCapturedVariable(name, captured_name, kind);
		}

		internal void DefineCapturedScope(int scope_id, int id, string captured_name)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			anonymous_scopes[scope_id].AddCapturedScope(id, captured_name);
		}

		internal int GetNextTypeIndex()
		{
			return ++last_type_index;
		}

		internal int GetNextMethodIndex()
		{
			return ++last_method_index;
		}

		internal int GetNextNamespaceIndex()
		{
			return ++last_namespace_index;
		}

		private void Write(MyBinaryWriter bw, Guid guid)
		{
			bw.Write(5037318119232611860L);
			bw.Write(MajorVersion);
			bw.Write(MinorVersion);
			bw.Write(guid.ToByteArray());
			long position = bw.BaseStream.Position;
			ot.Write(bw, MajorVersion, MinorVersion);
			methods.Sort();
			for (int i = 0; i < methods.Count; i++)
			{
				methods[i].Index = i + 1;
			}
			ot.DataSectionOffset = (int)bw.BaseStream.Position;
			foreach (SourceFileEntry source in sources)
			{
				source.WriteData(bw);
			}
			foreach (CompileUnitEntry comp_unit in comp_units)
			{
				comp_unit.WriteData(bw);
			}
			foreach (MethodEntry method in methods)
			{
				method.WriteData(this, bw);
			}
			ot.DataSectionSize = (int)bw.BaseStream.Position - ot.DataSectionOffset;
			ot.MethodTableOffset = (int)bw.BaseStream.Position;
			for (int j = 0; j < methods.Count; j++)
			{
				methods[j].Write(bw);
			}
			ot.MethodTableSize = (int)bw.BaseStream.Position - ot.MethodTableOffset;
			ot.SourceTableOffset = (int)bw.BaseStream.Position;
			for (int k = 0; k < sources.Count; k++)
			{
				sources[k].Write(bw);
			}
			ot.SourceTableSize = (int)bw.BaseStream.Position - ot.SourceTableOffset;
			ot.CompileUnitTableOffset = (int)bw.BaseStream.Position;
			for (int l = 0; l < comp_units.Count; l++)
			{
				comp_units[l].Write(bw);
			}
			ot.CompileUnitTableSize = (int)bw.BaseStream.Position - ot.CompileUnitTableOffset;
			ot.AnonymousScopeCount = ((anonymous_scopes != null) ? anonymous_scopes.Count : 0);
			ot.AnonymousScopeTableOffset = (int)bw.BaseStream.Position;
			if (anonymous_scopes != null)
			{
				foreach (AnonymousScopeEntry value in anonymous_scopes.Values)
				{
					value.Write(bw);
				}
			}
			ot.AnonymousScopeTableSize = (int)bw.BaseStream.Position - ot.AnonymousScopeTableOffset;
			ot.TypeCount = last_type_index;
			ot.MethodCount = methods.Count;
			ot.SourceCount = sources.Count;
			ot.CompileUnitCount = comp_units.Count;
			ot.TotalFileSize = (int)bw.BaseStream.Position;
			bw.Seek((int)position, SeekOrigin.Begin);
			ot.Write(bw, MajorVersion, MinorVersion);
			bw.Seek(0, SeekOrigin.End);
		}

		public void CreateSymbolFile(Guid guid, FileStream fs)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			Write(new MyBinaryWriter(fs), guid);
		}

		private MonoSymbolFile(Stream stream)
		{
			reader = new MyBinaryReader(stream);
			try
			{
				long num = reader.ReadInt64();
				int num2 = reader.ReadInt32();
				int num3 = reader.ReadInt32();
				if (num != 5037318119232611860L)
				{
					throw new MonoSymbolFileException("Symbol file is not a valid");
				}
				if (num2 != 50)
				{
					throw new MonoSymbolFileException("Symbol file has version {0} but expected {1}", num2, 50);
				}
				if (num3 != 0)
				{
					throw new MonoSymbolFileException("Symbol file has version {0}.{1} but expected {2}.{3}", num2, num3, 50, 0);
				}
				MajorVersion = num2;
				MinorVersion = num3;
				guid = new Guid(reader.ReadBytes(16));
				ot = new OffsetTable(reader, num2, num3);
			}
			catch (Exception innerException)
			{
				throw new MonoSymbolFileException("Cannot read symbol file", innerException);
			}
			source_file_hash = new Dictionary<int, SourceFileEntry>();
			compile_unit_hash = new Dictionary<int, CompileUnitEntry>();
		}

		public static MonoSymbolFile ReadSymbolFile(Assembly assembly)
		{
			string mdbFilename = assembly.Location + ".mdb";
			Guid moduleVersionId = assembly.GetModules()[0].ModuleVersionId;
			return ReadSymbolFile(mdbFilename, moduleVersionId);
		}

		public static MonoSymbolFile ReadSymbolFile(string mdbFilename)
		{
			return ReadSymbolFile(new FileStream(mdbFilename, FileMode.Open, FileAccess.Read));
		}

		public static MonoSymbolFile ReadSymbolFile(string mdbFilename, Guid assemblyGuid)
		{
			MonoSymbolFile monoSymbolFile = ReadSymbolFile(mdbFilename);
			if (assemblyGuid != monoSymbolFile.guid)
			{
				throw new MonoSymbolFileException("Symbol file `{0}' does not match assembly", mdbFilename);
			}
			return monoSymbolFile;
		}

		public static MonoSymbolFile ReadSymbolFile(Stream stream)
		{
			return new MonoSymbolFile(stream);
		}

		public SourceFileEntry GetSourceFile(int index)
		{
			if (index < 1 || index > ot.SourceCount)
			{
				throw new ArgumentException();
			}
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (source_file_hash.TryGetValue(index, out var value))
				{
					return value;
				}
				long position = reader.BaseStream.Position;
				reader.BaseStream.Position = ot.SourceTableOffset + SourceFileEntry.Size * (index - 1);
				value = new SourceFileEntry(this, reader);
				source_file_hash.Add(index, value);
				reader.BaseStream.Position = position;
				return value;
			}
		}

		public CompileUnitEntry GetCompileUnit(int index)
		{
			if (index < 1 || index > ot.CompileUnitCount)
			{
				throw new ArgumentException();
			}
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (compile_unit_hash.TryGetValue(index, out var value))
				{
					return value;
				}
				long position = reader.BaseStream.Position;
				reader.BaseStream.Position = ot.CompileUnitTableOffset + CompileUnitEntry.Size * (index - 1);
				value = new CompileUnitEntry(this, reader);
				compile_unit_hash.Add(index, value);
				reader.BaseStream.Position = position;
				return value;
			}
		}

		private void read_methods()
		{
			lock (this)
			{
				if (method_token_hash == null)
				{
					method_token_hash = new Dictionary<int, MethodEntry>();
					method_list = new List<MethodEntry>();
					long position = reader.BaseStream.Position;
					reader.BaseStream.Position = ot.MethodTableOffset;
					for (int i = 0; i < MethodCount; i++)
					{
						MethodEntry methodEntry = new MethodEntry(this, reader, i + 1);
						method_token_hash.Add(methodEntry.Token, methodEntry);
						method_list.Add(methodEntry);
					}
					reader.BaseStream.Position = position;
				}
			}
		}

		public MethodEntry GetMethodByToken(int token)
		{
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				read_methods();
				method_token_hash.TryGetValue(token, out var value);
				return value;
			}
		}

		public MethodEntry GetMethod(int index)
		{
			if (index < 1 || index > ot.MethodCount)
			{
				throw new ArgumentException();
			}
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				read_methods();
				return method_list[index - 1];
			}
		}

		public int FindSource(string file_name)
		{
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (source_name_hash == null)
				{
					source_name_hash = new Dictionary<string, int>();
					for (int i = 0; i < ot.SourceCount; i++)
					{
						SourceFileEntry sourceFile = GetSourceFile(i + 1);
						source_name_hash.Add(sourceFile.FileName, i);
					}
				}
				if (!source_name_hash.TryGetValue(file_name, out var value))
				{
					return -1;
				}
				return value;
			}
		}

		public AnonymousScopeEntry GetAnonymousScope(int id)
		{
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (anonymous_scopes != null)
				{
					anonymous_scopes.TryGetValue(id, out var value);
					return value;
				}
				anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>();
				reader.BaseStream.Position = ot.AnonymousScopeTableOffset;
				for (int i = 0; i < ot.AnonymousScopeCount; i++)
				{
					AnonymousScopeEntry value = new AnonymousScopeEntry(reader);
					anonymous_scopes.Add(value.ID, value);
				}
				return anonymous_scopes[id];
			}
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing && reader != null)
			{
				reader.Close();
				reader = null;
			}
		}
	}
	public class OffsetTable
	{
		[Flags]
		public enum Flags
		{
			IsAspxSource = 1,
			WindowsFileNames = 2
		}

		public const int MajorVersion = 50;

		public const int MinorVersion = 0;

		public const long Magic = 5037318119232611860L;

		public int TotalFileSize;

		public int DataSectionOffset;

		public int DataSectionSize;

		public int CompileUnitCount;

		public int CompileUnitTableOffset;

		public int CompileUnitTableSize;

		public int SourceCount;

		public int SourceTableOffset;

		public int SourceTableSize;

		public int MethodCount;

		public int MethodTableOffset;

		public int MethodTableSize;

		public int TypeCount;

		public int AnonymousScopeCount;

		public int AnonymousScopeTableOffset;

		public int AnonymousScopeTableSize;

		public Flags FileFlags;

		public int LineNumberTable_LineBase = -1;

		public int LineNumberTable_LineRange = 8;

		public int LineNumberTable_OpcodeBase = 9;

		internal OffsetTable()
		{
			int platform = (int)Environment.OSVersion.Platform;
			if (platform != 4 && platform != 128)
			{
				FileFlags |= Flags.WindowsFileNames;
			}
		}

		internal OffsetTable(BinaryReader reader, int major_version, int minor_version)
		{
			TotalFileSize = reader.ReadInt32();
			DataSectionOffset = reader.ReadInt32();
			DataSectionSize = reader.ReadInt32();
			CompileUnitCount = reader.ReadInt32();
			CompileUnitTableOffset = reader.ReadInt32();
			CompileUnitTableSize = reader.ReadInt32();
			SourceCount = reader.ReadInt32();
			SourceTableOffset = reader.ReadInt32();
			SourceTableSize = reader.ReadInt32();
			MethodCount = reader.ReadInt32();
			MethodTableOffset = reader.ReadInt32();
			MethodTableSize = reader.ReadInt32();
			TypeCount = reader.ReadInt32();
			AnonymousScopeCount = reader.ReadInt32();
			AnonymousScopeTableOffset = reader.ReadInt32();
			AnonymousScopeTableSize = reader.ReadInt32();
			LineNumberTable_LineBase = reader.ReadInt32();
			LineNumberTable_LineRange = reader.ReadInt32();
			LineNumberTable_OpcodeBase = reader.ReadInt32();
			FileFlags = (Flags)reader.ReadInt32();
		}

		internal void Write(BinaryWriter bw, int major_version, int minor_version)
		{
			bw.Write(TotalFileSize);
			bw.Write(DataSectionOffset);
			bw.Write(DataSectionSize);
			bw.Write(CompileUnitCount);
			bw.Write(CompileUnitTableOffset);
			bw.Write(CompileUnitTableSize);
			bw.Write(SourceCount);
			bw.Write(SourceTableOffset);
			bw.Write(SourceTableSize);
			bw.Write(MethodCount);
			bw.Write(MethodTableOffset);
			bw.Write(MethodTableSize);
			bw.Write(TypeCount);
			bw.Write(AnonymousScopeCount);
			bw.Write(AnonymousScopeTableOffset);
			bw.Write(AnonymousScopeTableSize);
			bw.Write(LineNumberTable_LineBase);
			bw.Write(LineNumberTable_LineRange);
			bw.Write(LineNumberTable_OpcodeBase);
			bw.Write((int)FileFlags);
		}

		public override string ToString()
		{
			return $"OffsetTable [{TotalFileSize} - {DataSectionOffset}:{DataSectionSize} - {SourceCount}:{SourceTableOffset}:{SourceTableSize} - {MethodCount}:{MethodTableOffset}:{MethodTableSize} - {TypeCount}]";
		}
	}
	public class LineNumberEntry
	{
		public sealed class LocationComparer : IComparer<LineNumberEntry>
		{
			public static readonly LocationComparer Default = new LocationComparer();

			public int Compare(LineNumberEntry l1, LineNumberEntry l2)
			{
				if (l1.Row != l2.Row)
				{
					int row = l1.Row;
					return row.CompareTo(l2.Row);
				}
				return l1.Column.CompareTo(l2.Column);
			}
		}

		public readonly int Row;

		public int Column;

		public int EndRow;

		public int EndColumn;

		public readonly int File;

		public readonly int Offset;

		public readonly bool IsHidden;

		public static readonly LineNumberEntry Null = new LineNumberEntry(0, 0, 0, 0);

		public LineNumberEntry(int file, int row, int column, int offset)
			: this(file, row, column, offset, is_hidden: false)
		{
		}

		public LineNumberEntry(int file, int row, int offset)
			: this(file, row, -1, offset, is_hidden: false)
		{
		}

		public LineNumberEntry(int file, int row, int column, int offset, bool is_hidden)
			: this(file, row, column, -1, -1, offset, is_hidden)
		{
		}

		public LineNumberEntry(int file, int row, int column, int end_row, int end_column, int offset, bool is_hidden)
		{
			File = file;
			Row = row;
			Column = column;
			EndRow = end_row;
			EndColumn = end_column;
			Offset = offset;
			IsHidden = is_hidden;
		}

		public override string ToString()
		{
			return $"[Line {File}:{Row},{Column}-{EndRow},{EndColumn}:{Offset}]";
		}
	}
	public class CodeBlockEntry
	{
		public enum Type
		{
			Lexical = 1,
			CompilerGenerated,
			IteratorBody,
			IteratorDispatcher
		}

		public int Index;

		public int Parent;

		public Type BlockType;

		public int StartOffset;

		public int EndOffset;

		public CodeBlockEntry(int index, int parent, Type type, int start_offset)
		{
			Index = index;
			Parent = parent;
			BlockType = type;
			StartOffset = start_offset;
		}

		internal CodeBlockEntry(int index, MyBinaryReader reader)
		{
			Index = index;
			int num = reader.ReadLeb128();
			BlockType = (Type)(num & 0x3F);
			Parent = reader.ReadLeb128();
			StartOffset = reader.ReadLeb128();
			EndOffset = reader.ReadLeb128();
			if (((uint)num & 0x40u) != 0)
			{
				int num2 = reader.ReadInt16();
				reader.BaseStream.Position += num2;
			}
		}

		public void Close(int end_offset)
		{
			EndOffset = end_offset;
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128((int)BlockType);
			bw.WriteLeb128(Parent);
			bw.WriteLeb128(StartOffset);
			bw.WriteLeb128(EndOffset);
		}

		public override string ToString()
		{
			return $"[CodeBlock {Index}:{Parent}:{BlockType}:{StartOffset}:{EndOffset}]";
		}
	}
	public struct LocalVariableEntry
	{
		public readonly int Index;

		public readonly string Name;

		public readonly int BlockIndex;

		public LocalVariableEntry(int index, string name, int block)
		{
			Index = index;
			Name = name;
			BlockIndex = block;
		}

		internal LocalVariableEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			Index = reader.ReadLeb128();
			Name = reader.ReadString();
			BlockIndex = reader.ReadLeb128();
		}

		internal void Write(MonoSymbolFile file, MyBinaryWriter bw)
		{
			bw.WriteLeb128(Index);
			bw.Write(Name);
			bw.WriteLeb128(BlockIndex);
		}

		public override string ToString()
		{
			return $"[LocalVariable {Name}:{Index}:{BlockIndex - 1}]";
		}
	}
	public struct CapturedVariable
	{
		public enum CapturedKind : byte
		{
			Local,
			Parameter,
			This
		}

		public readonly string Name;

		public readonly string CapturedName;

		public readonly CapturedKind Kind;

		public CapturedVariable(string name, string captured_name, CapturedKind kind)
		{
			Name = name;
			CapturedName = captured_name;
			Kind = kind;
		}

		internal CapturedVariable(MyBinaryReader reader)
		{
			Name = reader.ReadString();
			CapturedName = reader.ReadString();
			Kind = (CapturedKind)reader.ReadByte();
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.Write(Name);
			bw.Write(CapturedName);
			bw.Write((byte)Kind);
		}

		public override string ToString()
		{
			return $"[CapturedVariable {Name}:{CapturedName}:{Kind}]";
		}
	}
	public struct CapturedScope
	{
		public readonly int Scope;

		public readonly string CapturedName;

		public CapturedScope(int scope, string captured_name)
		{
			Scope = scope;
			CapturedName = captured_name;
		}

		internal CapturedScope(MyBinaryReader reader)
		{
			Scope = reader.ReadLeb128();
			CapturedName = reader.ReadString();
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128(Scope);
			bw.Write(CapturedName);
		}

		public override string ToString()
		{
			return $"[CapturedScope {Scope}:{CapturedName}]";
		}
	}
	public struct ScopeVariable
	{
		public readonly int Scope;

		public readonly int Index;

		public ScopeVariable(int scope, int index)
		{
			Scope = scope;
			Index = index;
		}

		internal ScopeVariable(MyBinaryReader reader)
		{
			Scope = reader.ReadLeb128();
			Index = reader.ReadLeb128();
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128(Scope);
			bw.WriteLeb128(Index);
		}

		public override string ToString()
		{
			return $"[ScopeVariable {Scope}:{Index}]";
		}
	}
	public class AnonymousScopeEntry
	{
		public readonly int ID;

		private List<CapturedVariable> captured_vars = new List<CapturedVariable>();

		private List<CapturedScope> captured_scopes = new List<CapturedScope>();

		public CapturedVariable[] CapturedVariables
		{
			get
			{
				CapturedVariable[] array = new CapturedVariable[captured_vars.Count];
				captured_vars.CopyTo(array, 0);
				return array;
			}
		}

		public CapturedScope[] CapturedScopes
		{
			get
			{
				CapturedScope[] array = new CapturedScope[captured_scopes.Count];
				captured_scopes.CopyTo(array, 0);
				return array;
			}
		}

		public AnonymousScopeEntry(int id)
		{
			ID = id;
		}

		internal AnonymousScopeEntry(MyBinaryReader reader)
		{
			ID = reader.ReadLeb128();
			int num = reader.ReadLeb128();
			for (int i = 0; i < num; i++)
			{
				captured_vars.Add(new CapturedVariable(reader));
			}
			int num2 = reader.ReadLeb128();
			for (int j = 0; j < num2; j++)
			{
				captured_scopes.Add(new CapturedScope(reader));
			}
		}

		internal void AddCapturedVariable(string name, string captured_name, CapturedVariable.CapturedKind kind)
		{
			captured_vars.Add(new CapturedVariable(name, captured_name, kind));
		}

		internal void AddCapturedScope(int scope, string captured_name)
		{
			captured_scopes.Add(new CapturedScope(scope, captured_name));
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128(ID);
			bw.WriteLeb128(captured_vars.Count);
			foreach (CapturedVariable captured_var in captured_vars)
			{
				captured_var.Write(bw);
			}
			bw.WriteLeb128(captured_scopes.Count);
			foreach (CapturedScope captured_scope in captured_scopes)
			{
				captured_scope.Write(bw);
			}
		}

		public override string ToString()
		{
			return $"[AnonymousScope {ID}]";
		}
	}
	public class CompileUnitEntry : ICompileUnit
	{
		public readonly int Index;

		private int DataOffset;

		private MonoSymbolFile file;

		private SourceFileEntry source;

		private List<SourceFileEntry> include_files;

		private List<NamespaceEntry> namespaces;

		private bool creating;

		public static int Size => 8;

		CompileUnitEntry ICompileUnit.Entry => this;

		public SourceFileEntry SourceFile
		{
			get
			{
				if (creating)
				{
					return source;
				}
				ReadData();
				return source;
			}
		}

		public NamespaceEntry[] Namespaces
		{
			get
			{
				ReadData();
				NamespaceEntry[] array = new NamespaceEntry[namespaces.Count];
				namespaces.CopyTo(array, 0);
				return array;
			}
		}

		public SourceFileEntry[] IncludeFiles
		{
			get
			{
				ReadData();
				if (include_files == null)
				{
					return new SourceFileEntry[0];
				}
				SourceFileEntry[] array = new SourceFileEntry[include_files.Count];
				include_files.CopyTo(array, 0);
				return array;
			}
		}

		public CompileUnitEntry(MonoSymbolFile file, SourceFileEntry source)
		{
			this.file = file;
			this.source = source;
			Index = file.AddCompileUnit(this);
			creating = true;
			namespaces = new List<NamespaceEntry>();
		}

		public void AddFile(SourceFileEntry file)
		{
			if (!creating)
			{
				throw new InvalidOperationException();
			}
			if (include_files == null)
			{
				include_files = new List<SourceFileEntry>();
			}
			include_files.Add(file);
		}

		public int DefineNamespace(string name, string[] using_clauses, int parent)
		{
			if (!creating)
			{
				throw new InvalidOperationException();
			}
			int nextNamespaceIndex = file.GetNextNamespaceIndex();
			NamespaceEntry item = new NamespaceEntry(name, nextNamespaceIndex, using_clauses, parent);
			namespaces.Add(item);
			return nextNamespaceIndex;
		}

		internal void WriteData(MyBinaryWriter bw)
		{
			DataOffset = (int)bw.BaseStream.Position;
			bw.WriteLeb128(source.Index);
			int value = ((include_files != null) ? include_files.Count : 0);
			bw.WriteLeb128(value);
			if (include_files != null)
			{
				foreach (SourceFileEntry include_file in include_files)
				{
					bw.WriteLeb128(include_file.Index);
				}
			}
			bw.WriteLeb128(namespaces.Count);
			foreach (NamespaceEntry @namespace in namespaces)
			{
				@namespace.Write(file, bw);
			}
		}

		internal void Write(BinaryWriter bw)
		{
			bw.Write(Index);
			bw.Write(DataOffset);
		}

		internal CompileUnitEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			this.file = file;
			Index = reader.ReadInt32();
			DataOffset = reader.ReadInt32();
		}

		public void ReadAll()
		{
			ReadData();
		}

		private void ReadData()
		{
			if (creating)
			{
				throw new InvalidOperationException();
			}
			lock (file)
			{
				if (namespaces != null)
				{
					return;
				}
				MyBinaryReader binaryReader = file.BinaryReader;
				int num = (int)binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = DataOffset;
				int index = binaryReader.ReadLeb128();
				source = file.GetSourceFile(index);
				int num2 = binaryReader.ReadLeb128();
				if (num2 > 0)
				{
					include_files = new List<SourceFileEntry>();
					for (int i = 0; i < num2; i++)
					{
						include_files.Add(file.GetSourceFile(binaryReader.ReadLeb128()));
					}
				}
				int num3 = binaryReader.ReadLeb128();
				namespaces = new List<NamespaceEntry>();
				for (int j = 0; j < num3; j++)
				{
					namespaces.Add(new NamespaceEntry(file, binaryReader));
				}
				binaryReader.BaseStream.Position = num;
			}
		}
	}
	public class SourceFileEntry
	{
		public readonly int Index;

		private int DataOffset;

		private MonoSymbolFile file;

		private string file_name;

		private byte[] guid;

		private byte[] hash;

		private bool creating;

		private bool auto_generated;

		private readonly string sourceFile;

		public static int Size => 8;

		public byte[] Checksum => hash;

		public string FileName
		{
			get
			{
				return file_name;
			}
			set
			{
				file_name = value;
			}
		}

		public bool AutoGenerated => auto_generated;

		public SourceFileEntry(MonoSymbolFile file, string file_name)
		{
			this.file = file;
			this.file_name = file_name;
			Index = file.AddSource(this);
			creating = true;
		}

		public SourceFileEntry(MonoSymbolFile file, string sourceFile, byte[] guid, byte[] checksum)
			: this(file, sourceFile, sourceFile, guid, checksum)
		{
		}

		public SourceFileEntry(MonoSymbolFile file, string fileName, string sourceFile, byte[] guid, byte[] checksum)
			: this(file, fileName)
		{
			this.guid = guid;
			hash = checksum;
			this.sourceFile = sourceFile;
		}

		internal void WriteData(MyBinaryWriter bw)
		{
			DataOffset = (int)bw.BaseStream.Position;
			bw.Write(file_name);
			if (guid == null)
			{
				guid = new byte[16];
			}
			if (hash == null)
			{
				try
				{
					using FileStream inputStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
					MD5 mD = MD5.Create();
					hash = mD.ComputeHash(inputStream);
				}
				catch
				{
					hash = new byte[16];
				}
			}
			bw.Write(guid);
			bw.Write(hash);
			bw.Write((byte)(auto_generated ? 1u : 0u));
		}

		internal void Write(BinaryWriter bw)
		{
			bw.Write(Index);
			bw.Write(DataOffset);
		}

		internal SourceFileEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			this.file = file;
			Index = reader.ReadInt32();
			DataOffset = reader.ReadInt32();
			int num = (int)reader.BaseStream.Position;
			reader.BaseStream.Position = DataOffset;
			sourceFile = (file_name = reader.ReadString());
			guid = reader.ReadBytes(16);
			hash = reader.ReadBytes(16);
			auto_generated = reader.ReadByte() == 1;
			reader.BaseStream.Position = num;
		}

		public void SetAutoGenerated()
		{
			if (!creating)
			{
				throw new InvalidOperationException();
			}
			auto_generated = true;
			file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource;
		}

		public bool CheckChecksum()
		{
			try
			{
				using FileStream inputStream = new FileStream(sourceFile, FileMode.Open);
				byte[] array = MD5.Create().ComputeHash(inputStream);
				for (int i = 0; i < 16; i++)
				{
					if (array[i] != hash[i])
					{
						return false;
					}
				}
				return true;
			}
			catch
			{
				return false;
			}
		}

		public override string ToString()
		{
			return $"SourceFileEntry ({Index}:{DataOffset})";
		}
	}
	public class LineNumberTable
	{
		protected LineNumberEntry[] _line_numbers;

		public readonly int LineBase;

		public readonly int LineRange;

		public readonly byte OpcodeBase;

		public readonly int MaxAddressIncrement;

		public const int Default_LineBase = -1;

		public const int Default_LineRange = 8;

		public const byte Default_OpcodeBase = 9;

		public const byte DW_LNS_copy = 1;

		public const byte DW_LNS_advance_pc = 2;

		public const byte DW_LNS_advance_line = 3;

		public const byte DW_LNS_set_file = 4;

		public const byte DW_LNS_const_add_pc = 8;

		public const byte DW_LNE_end_sequence = 1;

		public const byte DW_LNE_MONO_negate_is_hidden = 64;

		internal const byte DW_LNE_MONO__extensions_start = 64;

		internal const byte DW_LNE_MONO__extensions_end = 127;

		public LineNumberEntry[] LineNumbers => _line_numbers;

		protected LineNumberTable(MonoSymbolFile file)
		{
			LineBase = file.OffsetTable.LineNumberTable_LineBase;
			LineRange = file.OffsetTable.LineNumberTable_LineRange;
			OpcodeBase = (byte)file.OffsetTable.LineNumberTable_OpcodeBase;
			MaxAddressIncrement = (255 - OpcodeBase) / LineRange;
		}

		internal LineNumberTable(MonoSymbolFile file, LineNumberEntry[] lines)
			: this(file)
		{
			_line_numbers = lines;
		}

		internal void Write(MonoSymbolFile file, MyBinaryWriter bw, bool hasColumnsInfo, bool hasEndInfo)
		{
			int num = (int)bw.BaseStream.Position;
			bool flag = false;
			int num2 = 1;
			int num3 = 0;
			int num4 = 1;
			for (int i = 0; i < LineNumbers.Length; i++)
			{
				int num5 = LineNumbers[i].Row - num2;
				int num6 = LineNumbers[i].Offset - num3;
				if (LineNumbers[i].File != num4)
				{
					bw.Write((byte)4);
					bw.WriteLeb128(LineNumbers[i].File);
					num4 = LineNumbers[i].File;
				}
				if (LineNumbers[i].IsHidden != flag)
				{
					bw.Write((byte)0);
					bw.Write((byte)1);
					bw.Write((byte)64);
					flag = LineNumbers[i].IsHidden;
				}
				if (num6 >= MaxAddressIncrement)
				{
					if (num6 < 2 * MaxAddressIncrement)
					{
						bw.Write((byte)8);
						num6 -= MaxAddressIncrement;
					}
					else
					{
						bw.Write((byte)2);
						bw.WriteLeb128(num6);
						num6 = 0;
					}
				}
				if (num5 < LineBase || num5 >= LineBase + LineRange)
				{
					bw.Write((byte)3);
					bw.WriteLeb128(num5);
					if (num6 != 0)
					{
						bw.Write((byte)2);
						bw.WriteLeb128(num6);
					}
					bw.Write((byte)1);
				}
				else
				{
					byte value = (byte)(num5 - LineBase + LineRange * num6 + OpcodeBase);
					bw.Write(value);
				}
				num2 = LineNumbers[i].Row;
				num3 = LineNumbers[i].Offset;
			}
			bw.Write((byte)0);
			bw.Write((byte)1);
			bw.Write((byte)1);
			if (hasColumnsInfo)
			{
				for (int j = 0; j < LineNumbers.Length; j++)
				{
					LineNumberEntry lineNumberEntry = LineNumbers[j];
					if (lineNumberEntry.Row >= 0)
					{
						bw.WriteLeb128(lineNumberEntry.Column);
					}
				}
			}
			if (hasEndInfo)
			{
				for (int k = 0; k < LineNumbers.Length; k++)
				{
					LineNumberEntry lineNumberEntry2 = LineNumbers[k];
					if (lineNumberEntry2.EndRow == -1 || lineNumberEntry2.EndColumn == -1 || lineNumberEntry2.Row > lineNumberEntry2.EndRow)
					{
						bw.WriteLeb128(16777215);
						continue;
					}
					bw.WriteLeb128(lineNumberEntry2.EndRow - lineNumberEntry2.Row);
					bw.WriteLeb128(lineNumberEntry2.EndColumn);
				}
			}
			file.ExtendedLineNumberSize += (int)bw.BaseStream.Position - num;
		}

		internal static LineNumberTable Read(MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo, bool readEndInfo)
		{
			LineNumberTable lineNumberTable = new LineNumberTable(file);
			lineNumberTable.DoRead(file, br, readColumnsInfo, readEndInfo);
			return lineNumberTable;
		}

		private void DoRead(MonoSymbolFile file, MyBinaryReader br, bool includesColumns, bool includesEnds)
		{
			List<LineNumberEntry> list = new List<LineNumberEntry>();
			bool flag = false;
			bool flag2 = false;
			int num = 1;
			int num2 = 0;
			int file2 = 1;
			while (true)
			{
				byte b = br.ReadByte();
				if (b == 0)
				{
					byte b2 = br.ReadByte();
					long position = br.BaseStream.Position + b2;
					b = br.ReadByte();
					switch (b)
					{
					case 1:
					{
						if (flag2)
						{
							list.Add(new LineNumberEntry(file2, num, -1, num2, flag));
						}
						_line_numbers = list.ToArray();
						if (includesColumns)
						{
							for (int i = 0; i < _line_numbers.Length; i++)
							{
								LineNumberEntry lineNumberEntry = _line_numbers[i];
								if (lineNumberEntry.Row >= 0)
								{
									lineNumberEntry.Column = br.ReadLeb128();
								}
							}
						}
						if (!includesEnds)
						{
							return;
						}
						for (int j = 0; j < _line_numbers.Length; j++)
						{
							LineNumberEntry lineNumberEntry2 = _line_numbers[j];
							int num3 = br.ReadLeb128();
							if (num3 == 16777215)
							{
								lineNumberEntry2.EndRow = -1;
								lineNumberEntry2.EndColumn = -1;
							}
							else
							{
								lineNumberEntry2.EndRow = lineNumberEntry2.Row + num3;
								lineNumberEntry2.EndColumn = br.ReadLeb128();
							}
						}
						return;
					}
					case 64:
						flag = !flag;
						flag2 = true;
						break;
					default:
						throw new MonoSymbolFileException("Unknown extended opcode {0:x}", b);
					case 65:
					case 66:
					case 67:
					case 68:
					case 69:
					case 70:
					case 71:
					case 72:
					case 73:
					case 74:
					case 75:
					case 76:
					case 77:
					case 78:
					case 79:
					case 80:
					case 81:
					case 82:
					case 83:
					case 84:
					case 85:
					case 86:
					case 87:
					case 88:
					case 89:
					case 90:
					case 91:
					case 92:
					case 93:
					case 94:
					case 95:
					case 96:
					case 97:
					case 98:
					case 99:
					case 100:
					case 101:
					case 102:
					case 103:
					case 104:
					case 105:
					case 106:
					case 107:
					case 108:
					case 109:
					case 110:
					case 111:
					case 112:
					case 113:
					case 114:
					case 115:
					case 116:
					case 117:
					case 118:
					case 119:
					case 120:
					case 121:
					case 122:
					case 123:
					case 124:
					case 125:
					case 126:
					case 127:
						break;
					}
					br.BaseStream.Position = position;
				}
				else if (b < OpcodeBase)
				{
					switch (b)
					{
					case 1:
						list.Add(new LineNumberEntry(file2, num, -1, num2, flag));
						flag2 = false;
						break;
					case 2:
						num2 += br.ReadLeb128();
						flag2 = true;
						break;
					case 3:
						num += br.ReadLeb128();
						flag2 = true;
						break;
					case 4:
						file2 = br.ReadLeb128();
						flag2 = true;
						break;
					case 8:
						num2 += MaxAddressIncrement;
						flag2 = true;
						break;
					default:
						throw new MonoSymbolFileException("Unknown standard opcode {0:x} in LNT", b);
					}
				}
				else
				{
					b -= OpcodeBase;
					num2 += b / LineRange;
					num += LineBase + b % LineRange;
					list.Add(new LineNumberEntry(file2, num, -1, num2, flag));
					flag2 = false;
				}
			}
		}

		public bool GetMethodBounds(out LineNumberEntry start, out LineNumberEntry end)
		{
			if (_line_numbers.Length > 1)
			{
				start = _line_numbers[0];
				end = _line_numbers[_line_numbers.Length - 1];
				return true;
			}
			start = LineNumberEntry.Null;
			end = LineNumberEntry.Null;
			return false;
		}
	}
	public class MethodEntry : IComparable
	{
		[Flags]
		public enum Flags
		{
			LocalNamesAmbiguous = 1,
			ColumnsInfoIncluded = 2,
			EndInfoIncluded = 4
		}

		public readonly int CompileUnitIndex;

		public readonly int Token;

		public readonly int NamespaceID;

		private int DataOffset;

		private int LocalVariableTableOffset;

		private int LineNumberTableOffset;

		private int CodeBlockTableOffset;

		private int ScopeVariableTableOffset;

		private int RealNameOffset;

		private Flags flags;

		private int index;

		public readonly CompileUnitEntry CompileUnit;

		private LocalVariableEntry[] locals;

		private CodeBlockEntry[] code_blocks;

		private ScopeVariable[] scope_vars;

		private LineNumberTable lnt;

		private string real_name;

		public readonly MonoSymbolFile SymbolFile;

		public const int Size = 12;

		public Flags MethodFlags => flags;

		public int Index
		{
			get
			{
				return index;
			}
			set
			{
				index = value;
			}
		}

		internal MethodEntry(MonoSymbolFile file, MyBinaryReader reader, int index)
		{
			SymbolFile = file;
			this.index = index;
			Token = reader.ReadInt32();
			DataOffset = reader.ReadInt32();
			LineNumberTableOffset = reader.ReadInt32();
			long position = reader.BaseStream.Position;
			reader.BaseStream.Position = DataOffset;
			CompileUnitIndex = reader.ReadLeb128();
			LocalVariableTableOffset = reader.ReadLeb128();
			NamespaceID = reader.ReadLeb128();
			CodeBlockTableOffset = reader.ReadLeb128();
			ScopeVariableTableOffset = reader.ReadLeb128();
			RealNameOffset = reader.ReadLeb128();
			flags = (Flags)reader.ReadLeb128();
			reader.BaseStream.Position = position;
			CompileUnit = file.GetCompileUnit(CompileUnitIndex);
		}

		internal MethodEntry(MonoSymbolFile file, CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, Flags flags, int namespace_id)
		{
			SymbolFile = file;
			this.real_name = real_name;
			this.locals = locals;
			this.code_blocks = code_blocks;
			this.scope_vars = scope_vars;
			this.flags = flags;
			index = -1;
			Token = token;
			CompileUnitIndex = comp_unit.Index;
			CompileUnit = comp_unit;
			NamespaceID = namespace_id;
			CheckLineNumberTable(lines);
			lnt = new LineNumberTable(file, lines);
			file.NumLineNumbers += lines.Length;
			int num = ((locals != null) ? locals.Length : 0);
			if (num <= 32)
			{
				for (int i = 0; i < num; i++)
				{
					string name = locals[i].Name;
					for (int j = i + 1; j < num; j++)
					{
						if (locals[j].Name == name)
						{
							flags |= Flags.LocalNamesAmbiguous;
							return;
						}
					}
				}
				return;
			}
			Dictionary<string, LocalVariableEntry> dictionary = new Dictionary<string, LocalVariableEntry>();
			for (int k = 0; k < locals.Length; k++)
			{
				LocalVariableEntry value = locals[k];
				if (dictionary.ContainsKey(value.Name))
				{
					flags |= Flags.LocalNamesAmbiguous;
					break;
				}
				dictionary.Add(value.Name, value);
			}
		}

		private static void CheckLineNumberTable(LineNumberEntry[] line_numbers)
		{
			int num = -1;
			int num2 = -1;
			if (line_numbers == null)
			{
				return;
			}
			foreach (LineNumberEntry lineNumberEntry in line_numbers)
			{
				if (lineNumberEntry.Equals(LineNumberEntry.Null))
				{
					throw new MonoSymbolFileException();
				}
				if (lineNumberEntry.Offset < num)
				{
					throw new MonoSymbolFileException();
				}
				if (lineNumberEntry.Offset > num)
				{
					num2 = lineNumberEntry.Row;
					num = lineNumberEntry.Offset;
				}
				else if (lineNumberEntry.Row > num2)
				{
					num2 = lineNumberEntry.Row;
				}
			}
		}

		internal void Write(MyBinaryWriter bw)
		{
			if (index <= 0 || DataOffset == 0)
			{
				throw new InvalidOperationException();
			}
			bw.Write(Token);
			bw.Write(DataOffset);
			bw.Write(LineNumberTableOffset);
		}

		internal void WriteData(MonoSymbolFile file, MyBinaryWriter bw)
		{
			if (index <= 0)
			{
				throw new InvalidOperationException();
			}
			LocalVariableTableOffset = (int)bw.BaseStream.Position;
			int num = ((locals != null) ? locals.Length : 0);
			bw.WriteLeb128(num);
			for (int i = 0; i < num; i++)
			{
				locals[i].Write(file, bw);
			}
			file.LocalCount += num;
			CodeBlockTableOffset = (int)bw.BaseStream.Position;
			int num2 = ((code_blocks != null) ? code_blocks.Length : 0);
			bw.WriteLeb128(num2);
			for (int j = 0; j < num2; j++)
			{
				code_blocks[j].Write(bw);
			}
			ScopeVariableTableOffset = (int)bw.BaseStream.Position;
			int num3 = ((scope_vars != null) ? scope_vars.Length : 0);
			bw.WriteLeb128(num3);
			for (int k = 0; k < num3; k++)
			{
				scope_vars[k].Write(bw);
			}
			if (real_name != null)
			{
				RealNameOffset = (int)bw.BaseStream.Position;
				bw.Write(real_name);
			}
			LineNumberEntry[] lineNumbers = lnt.LineNumbers;
			foreach (LineNumberEntry lineNumberEntry in lineNumbers)
			{
				if (lineNumberEntry.EndRow != -1 || lineNumberEntry.EndColumn != -1)
				{
					flags |= Flags.EndInfoIncluded;
				}
			}
			LineNumberTableOffset = (int)bw.BaseStream.Position;
			lnt.Write(file, bw, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
			DataOffset = (int)bw.BaseStream.Position;
			bw.WriteLeb128(CompileUnitIndex);
			bw.WriteLeb128(LocalVariableTableOffset);
			bw.WriteLeb128(NamespaceID);
			bw.WriteLeb128(CodeBlockTableOffset);
			bw.WriteLeb128(ScopeVariableTableOffset);
			bw.WriteLeb128(RealNameOffset);
			bw.WriteLeb128((int)flags);
		}

		public void ReadAll()
		{
			GetLineNumberTable();
			GetLocals();
			GetCodeBlocks();
			GetScopeVariables();
			GetRealName();
		}

		public LineNumberTable GetLineNumberTable()
		{
			lock (SymbolFile)
			{
				if (lnt != null)
				{
					return lnt;
				}
				if (LineNumberTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = LineNumberTableOffset;
				lnt = LineNumberTable.Read(SymbolFile, binaryReader, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
				binaryReader.BaseStream.Position = position;
				return lnt;
			}
		}

		public LocalVariableEntry[] GetLocals()
		{
			lock (SymbolFile)
			{
				if (locals != null)
				{
					return locals;
				}
				if (LocalVariableTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = LocalVariableTableOffset;
				int num = binaryReader.ReadLeb128();
				locals = new LocalVariableEntry[num];
				for (int i = 0; i < num; i++)
				{
					locals[i] = new LocalVariableEntry(SymbolFile, binaryReader);
				}
				binaryReader.BaseStream.Position = position;
				return locals;
			}
		}

		public CodeBlockEntry[] GetCodeBlocks()
		{
			lock (SymbolFile)
			{
				if (code_blocks != null)
				{
					return code_blocks;
				}
				if (CodeBlockTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = CodeBlockTableOffset;
				int num = binaryReader.ReadLeb128();
				code_blocks = new CodeBlockEntry[num];
				for (int i = 0; i < num; i++)
				{
					code_blocks[i] = new CodeBlockEntry(i, binaryReader);
				}
				binaryReader.BaseStream.Position = position;
				return code_blocks;
			}
		}

		public ScopeVariable[] GetScopeVariables()
		{
			lock (SymbolFile)
			{
				if (scope_vars != null)
				{
					return scope_vars;
				}
				if (ScopeVariableTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = ScopeVariableTableOffset;
				int num = binaryReader.ReadLeb128();
				scope_vars = new ScopeVariable[num];
				for (int i = 0; i < num; i++)
				{
					scope_vars[i] = new ScopeVariable(binaryReader);
				}
				binaryReader.BaseStream.Position = position;
				return scope_vars;
			}
		}

		public string GetRealName()
		{
			lock (SymbolFile)
			{
				if (real_name != null)
				{
					return real_name;
				}
				if (RealNameOffset == 0)
				{
					return null;
				}
				real_name = SymbolFile.BinaryReader.ReadString(RealNameOffset);
				return real_name;
			}
		}

		public int CompareTo(object obj)
		{
			MethodEntry methodEntry = (MethodEntry)obj;
			if (methodEntry.Token < Token)
			{
				return 1;
			}
			if (methodEntry.Token > Token)
			{
				return -1;
			}
			return 0;
		}

		public override string ToString()
		{
			return $"[Method {index}:{Token:x}:{CompileUnitIndex}:{CompileUnit}]";
		}
	}
	public struct NamespaceEntry
	{
		public readonly string Name;

		public readonly int Index;

		public readonly int Parent;

		public readonly string[] UsingClauses;

		public NamespaceEntry(string name, int index, string[] using_clauses, int parent)
		{
			Name = name;
			Index = index;
			Parent = parent;
			UsingClauses = ((using_clauses != null) ? using_clauses : new string[0]);
		}

		internal NamespaceEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			Name = reader.ReadString();
			Index = reader.ReadLeb128();
			Parent = reader.ReadLeb128();
			int num = reader.ReadLeb128();
			UsingClauses = new string[num];
			for (int i = 0; i < num; i++)
			{
				UsingClauses[i] = reader.ReadString();
			}
		}

		internal void Write(MonoSymbolFile file, MyBinaryWriter bw)
		{
			bw.Write(Name);
			bw.WriteLeb128(Index);
			bw.WriteLeb128(Parent);
			bw.WriteLeb128(UsingClauses.Length);
			string[] usingClauses = UsingClauses;
			foreach (string value in usingClauses)
			{
				bw.Write(value);
			}
		}

		public override string ToString()
		{
			return $"[Namespace {Name}:{Index}:{Parent}]";
		}
	}
	public class MonoSymbolWriter
	{
		private List<SourceMethodBuilder> methods;

		private List<SourceFileEntry> sources;

		private List<CompileUnitEntry> comp_units;

		protected readonly MonoSymbolFile file;

		private string filename;

		private SourceMethodBuilder current_method;

		private Stack<SourceMethodBuilder> current_method_stack = new Stack<SourceMethodBuilder>();

		public MonoSymbolFile SymbolFile => file;

		public MonoSymbolWriter(string filename)
		{
			methods = new List<SourceMethodBuilder>();
			sources = new List<SourceFileEntry>();
			comp_units = new List<CompileUnitEntry>();
			file = new MonoSymbolFile();
			this.filename = filename + ".mdb";
		}

		public void CloseNamespace()
		{
		}

		public void DefineLocalVariable(int index, string name)
		{
			if (current_method != null)
			{
				current_method.AddLocal(index, name);
			}
		}

		public void DefineCapturedLocal(int scope_id, string name, string captured_name)
		{
			file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Local);
		}

		public void DefineCapturedParameter(int scope_id, string name, string captured_name)
		{
			file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Parameter);
		}

		public void DefineCapturedThis(int scope_id, string captured_name)
		{
			file.DefineCapturedVariable(scope_id, "this", captured_name, CapturedVariable.CapturedKind.This);
		}

		public void DefineCapturedScope(int scope_id, int id, string captured_name)
		{
			file.DefineCapturedScope(scope_id, id, captured_name);
		}

		public void DefineScopeVariable(int scope, int index)
		{
			if (current_method != null)
			{
				current_method.AddScopeVariable(scope, index);
			}
		}

		public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden)
		{
			if (current_method != null)
			{
				current_method.MarkSequencePoint(offset, file, line, column, is_hidden);
			}
		}

		public SourceMethodBuilder OpenMethod(ICompileUnit file, int ns_id, IMethodDef method)
		{
			SourceMethodBuilder result = new SourceMethodBuilder(file, ns_id, method);
			current_method_stack.Push(current_method);
			current_method = result;
			methods.Add(current_method);
			return result;
		}

		public void CloseMethod()
		{
			current_method = current_method_stack.Pop();
		}

		public SourceFileEntry DefineDocument(string url)
		{
			SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url);
			sources.Add(sourceFileEntry);
			return sourceFileEntry;
		}

		public SourceFileEntry DefineDocument(string url, byte[] guid, byte[] checksum)
		{
			SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url, guid, checksum);
			sources.Add(sourceFileEntry);
			return sourceFileEntry;
		}

		public CompileUnitEntry DefineCompilationUnit(SourceFileEntry source)
		{
			CompileUnitEntry compileUnitEntry = new CompileUnitEntry(file, source);
			comp_units.Add(compileUnitEntry);
			return compileUnitEntry;
		}

		public int DefineNamespace(string name, CompileUnitEntry unit, string[] using_clauses, int parent)
		{
			if (unit == null || using_clauses == null)
			{
				throw new NullReferenceException();
			}
			return unit.DefineNamespace(name, using_clauses, parent);
		}

		public int OpenScope(int start_offset)
		{
			if (current_method == null)
			{
				return 0;
			}
			current_method.StartBlock(CodeBlockEntry.Type.Lexical, start_offset);
			return 0;
		}

		public void CloseScope(int end_offset)
		{
			if (current_method != null)
			{
				current_method.EndBlock(end_offset);
			}
		}

		public void OpenCompilerGeneratedBlock(int start_offset)
		{
			if (current_method != null)
			{
				current_method.StartBlock(CodeBlockEntry.Type.CompilerGenerated, start_offset);
			}
		}

		public void CloseCompilerGeneratedBlock(int end_offset)
		{
			if (current_method != null)
			{
				current_method.EndBlock(end_offset);
			}
		}

		public void StartIteratorBody(int start_offset)
		{
			current_method.StartBlock(CodeBlockEntry.Type.IteratorBody, start_offset);
		}

		public void EndIteratorBody(int end_offset)
		{
			current_method.EndBlock(end_offset);
		}

		public void StartIteratorDispatcher(int start_offset)
		{
			current_method.StartBlock(CodeBlockEntry.Type.IteratorDispatcher, start_offset);
		}

		public void EndIteratorDispatcher(int end_offset)
		{
			current_method.EndBlock(end_offset);
		}

		public void DefineAnonymousScope(int id)
		{
			file.DefineAnonymousScope(id);
		}

		public void WriteSymbolFile(Guid guid)
		{
			foreach (SourceMethodBuilder method in methods)
			{
				method.DefineMethod(file);
			}
			try
			{
				File.Delete(filename);
			}
			catch
			{
			}
			using FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
			file.CreateSymbolFile(guid, fs);
		}
	}
	public class SourceMethodBuilder
	{
		private List<LocalVariableEntry> _locals;

		private List<CodeBlockEntry> _blocks;

		private List<ScopeVariable> _scope_vars;

		private Stack<CodeBlockEntry> _block_stack;

		private readonly List<LineNumberEntry> method_lines;

		private readonly ICompileUnit _comp_unit;

		private readonly int ns_id;

		private readonly IMethodDef method;

		public CodeBlockEntry[] Blocks
		{
			get
			{
				if (_blocks == null)
				{
					return new CodeBlockEntry[0];
				}
				CodeBlockEntry[] array = new CodeBlockEntry[_blocks.Count];
				_blocks.CopyTo(array, 0);
				return array;
			}
		}

		public CodeBlockEntry CurrentBlock
		{
			get
			{
				if (_block_stack != null && _block_stack.Count > 0)
				{
					return _block_stack.Peek();
				}
				return null;
			}
		}

		public LocalVariableEntry[] Locals
		{
			get
			{
				if (_locals == null)
				{
					return new LocalVariableEntry[0];
				}
				return _locals.ToArray();
			}
		}

		public ICompileUnit SourceFile => _comp_unit;

		public ScopeVariable[] ScopeVariables
		{
			get
			{
				if (_scope_vars == null)
				{
					return new ScopeVariable[0];
				}
				return _scope_vars.ToArray();
			}
		}

		public SourceMethodBuilder(ICompileUnit comp_unit)
		{
			_comp_unit = comp_unit;
			method_lines = new List<LineNumberEntry>();
		}

		public SourceMethodBuilder(ICompileUnit comp_unit, int ns_id, IMethodDef method)
			: this(comp_unit)
		{
			this.ns_id = ns_id;
			this.method = method;
		}

		public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden)
		{
			MarkSequencePoint(offset, file, line, column, -1, -1, is_hidden);
		}

		public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, int end_line, int end_column, bool is_hidden)
		{
			LineNumberEntry lineNumberEntry = new LineNumberEntry(file?.Index ?? 0, line, column, end_line, end_column, offset, is_hidden);
			if (method_lines.Count > 0)
			{
				LineNumberEntry lineNumberEntry2 = method_lines[method_lines.Count - 1];
				if (lineNumberEntry2.Offset == offset)
				{
					if (LineNumberEntry.LocationComparer.Default.Compare(lineNumberEntry, lineNumberEntry2) > 0)
					{
						method_lines[method_lines.Count - 1] = lineNumberEntry;
					}
					return;
				}
			}
			method_lines.Add(lineNumberEntry);
		}

		public void StartBlock(CodeBlockEntry.Type type, int start_offset)
		{
			StartBlock(type, start_offset, (_blocks == null) ? 1 : (_blocks.Count + 1));
		}

		public void StartBlock(CodeBlockEntry.Type type, int start_offset, int scopeIndex)
		{
			if (_block_stack == null)
			{
				_block_stack = new Stack<CodeBlockEntry>();
			}
			if (_blocks == null)
			{
				_blocks = new List<CodeBlockEntry>();
			}
			int parent = ((CurrentBlock != null) ? CurrentBlock.Index : (-1));
			CodeBlockEntry item = new CodeBlockEntry(scopeIndex, parent, type, start_offset);
			_block_stack.Push(item);
			_blocks.Add(item);
		}

		public void EndBlock(int end_offset)
		{
			_block_stack.Pop().Close(end_offset);
		}

		public void AddLocal(int index, string name)
		{
			if (_locals == null)
			{
				_locals = new List<LocalVariableEntry>();
			}
			int block = ((CurrentBlock != null) ? CurrentBlock.Index : 0);
			_locals.Add(new LocalVariableEntry(index, name, block));
		}

		public void AddScopeVariable(int scope, int index)
		{
			if (_scope_vars == null)
			{
				_scope_vars = new List<ScopeVariable>();
			}
			_scope_vars.Add(new ScopeVariable(scope, index));
		}

		public void DefineMethod(MonoSymbolFile file)
		{
			DefineMethod(file, method.Token);
		}

		public void DefineMethod(MonoSymbolFile file, int token)
		{
			CodeBlockEntry[] array = Blocks;
			if (array.Length != 0)
			{
				List<CodeBlockEntry> list = new List<CodeBlockEntry>(array.Length);
				int num = 0;
				for (int i = 0; i < array.Length; i++)
				{
					num = Math.Max(num, array[i].Index);
				}
				for (int j = 0; j < num; j++)
				{
					int num2 = j + 1;
					if (j < array.Length && array[j].Index == num2)
					{
						list.Add(array[j]);
						continue;
					}
					bool flag = false;
					for (int k = 0; k < array.Length; k++)
					{
						if (array[k].Index == num2)
						{
							list.Add(array[k]);
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						list.Add(new CodeBlockEntry(num2, -1, CodeBlockEntry.Type.CompilerGenerated, 0));
					}
				}
				array = list.ToArray();
			}
			MethodEntry entry = new MethodEntry(file, _comp_unit.Entry, token, ScopeVariables, Locals, method_lines.ToArray(), array, null, MethodEntry.Flags.ColumnsInfoIncluded, ns_id);
			file.AddMethod(entry);
		}
	}
	public class SymbolWriterImpl : ISymbolWriter
	{
		private MonoSymbolWriter msw;

		private int nextLocalIndex;

		private int currentToken;

		private string methodName;

		private Stack namespaceStack = new Stack();

		private bool methodOpened;

		private Hashtable documents = new Hashtable();

		private Guid guid;

		public SymbolWriterImpl(Guid guid)
		{
			this.guid = guid;
		}

		public void Close()
		{
			msw.WriteSymbolFile(guid);
		}

		public void CloseMethod()
		{
			if (methodOpened)
			{
				methodOpened = false;
				nextLocalIndex = 0;
				msw.CloseMethod();
			}
		}

		public void CloseNamespace()
		{
			namespaceStack.Pop();
			msw.CloseNamespace();
		}

		public void CloseScope(int endOffset)
		{
			msw.CloseScope(endOffset);
		}

		public ISymbolDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType)
		{
			SymbolDocumentWriterImpl symbolDocumentWriterImpl = (SymbolDocumentWriterImpl)documents[url];
			if (symbolDocumentWriterImpl == null)
			{
				SourceFileEntry source = msw.DefineDocument(url);
				symbolDocumentWriterImpl = new SymbolDocumentWriterImpl(msw.DefineCompilationUnit(source));
				documents[url] = symbolDocumentWriterImpl;
			}
			return symbolDocumentWriterImpl;
		}

		public void DefineField(SymbolToken parent, string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3)
		{
		}

		public void DefineGlobalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3)
		{
		}

		public void DefineLocalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset)
		{
			msw.DefineLocalVariable(nextLocalIndex++, name);
		}

		public void DefineParameter(string name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3)
		{
		}

		public void DefineSequencePoints(ISymbolDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns)
		{
			SourceFileEntry file = ((SymbolDocumentWriterImpl)document)?.Entry.SourceFile;
			for (int i = 0; i < offsets.Length; i++)
			{
				if (i <= 0 || offsets[i] != offsets[i - 1] || lines[i] != lines[i - 1] || columns[i] != columns[i - 1])
				{
					msw.MarkSequencePoint(offsets[i], file, lines[i], columns[i], is_hidden: false);
				}
			}
		}

		public void Initialize(IntPtr emitter, string filename, bool fFullBuild)
		{
			msw = new MonoSymbolWriter(filename);
		}

		public void OpenMethod(SymbolToken method)
		{
			currentToken = method.GetToken();
		}

		public void OpenNamespace(string name)
		{
			NamespaceInfo namespaceInfo = new NamespaceInfo();
			namespaceInfo.NamespaceID = -1;
			namespaceInfo.Name = name;
			namespaceStack.Push(namespaceInfo);
		}

		public int OpenScope(int startOffset)
		{
			return msw.OpenScope(startOffset);
		}

		public void SetMethodSourceRange(ISymbolDocumentWriter startDoc, int startLine, int startColumn, ISymbolDocumentWriter endDoc, int endLine, int endColumn)
		{
			int currentNamespace = GetCurrentNamespace(startDoc);
			SourceMethodImpl method = new SourceMethodImpl(methodName, currentToken, currentNamespace);
			msw.OpenMethod(((ICompileUnit)startDoc).Entry, currentNamespace, method);
			methodOpened = true;
		}

		public void SetScopeRange(int scopeID, int startOffset, int endOffset)
		{
		}

		public void SetSymAttribute(SymbolToken parent, string name, byte[] data)
		{
			if (name == "__name")
			{
				methodName = Encoding.UTF8.GetString(data);
			}
		}

		public void SetUnderlyingWriter(IntPtr underlyingWriter)
		{
		}

		public void SetUserEntryPoint(SymbolToken entryMethod)
		{
		}

		public void UsingNamespace(string fullName)
		{
			if (namespaceStack.Count == 0)
			{
				OpenNamespace("");
			}
			NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek();
			if (namespaceInfo.NamespaceID != -1)
			{
				NamespaceInfo namespaceInfo2 = namespaceInfo;
				CloseNamespace();
				OpenNamespace(namespaceInfo2.Name);
				namespaceInfo = (NamespaceInfo)namespaceStack.Peek();
				namespaceInfo.UsingClauses = namespaceInfo2.UsingClauses;
			}
			namespaceInfo.UsingClauses.Add(fullName);
		}

		private int GetCurrentNamespace(ISymbolDocumentWriter doc)
		{
			if (namespaceStack.Count == 0)
			{
				OpenNamespace("");
			}
			NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek();
			if (namespaceInfo.NamespaceID == -1)
			{
				string[] using_clauses = (string[])namespaceInfo.UsingClauses.ToArray(typeof(string));
				int parent = 0;
				if (namespaceStack.Count > 1)
				{
					namespaceStack.Pop();
					parent = ((NamespaceInfo)namespaceStack.Peek()).NamespaceID;
					namespaceStack.Push(namespaceInfo);
				}
				namespaceInfo.NamespaceID = msw.DefineNamespace(namespaceInfo.Name, ((ICompileUnit)doc).Entry, using_clauses, parent);
			}
			return namespaceInfo.NamespaceID;
		}
	}
	internal class SymbolDocumentWriterImpl : ISymbolDocumentWriter, ISourceFile, ICompileUnit
	{
		private CompileUnitEntry comp_unit;

		SourceFileEntry ISourceFile.Entry => comp_unit.SourceFile;

		public CompileUnitEntry Entry => comp_unit;

		public SymbolDocumentWriterImpl(CompileUnitEntry comp_unit)
		{
			this.comp_unit = comp_unit;
		}

		public void SetCheckSum(Guid algorithmId, byte[] checkSum)
		{
		}

		public void SetSource(byte[] source)
		{
		}
	}
	internal class SourceMethodImpl : IMethodDef
	{
		private string name;

		private int token;

		private int namespaceID;

		public string Name => name;

		public int NamespaceID => namespaceID;

		public int Token => token;

		public SourceMethodImpl(string name, int token, int namespaceID)
		{
			this.name = name;
			this.token = token;
			this.namespaceID = namespaceID;
		}
	}
	internal class NamespaceInfo
	{
		public string Name;

		public int NamespaceID;

		public ArrayList UsingClauses = new ArrayList();
	}
}
namespace Mono.Cecil.Mdb
{
	public sealed class MdbReaderProvider : ISymbolReaderProvider
	{
		public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
		{
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(Mixin.GetMdbFileName(fileName)));
		}

		public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
		{
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(symbolStream));
		}
	}
	public sealed class MdbReader : ISymbolReader, IDisposable
	{
		private readonly ModuleDefinition module;

		private readonly MonoSymbolFile symbol_file;

		private readonly Dictionary<string, Document> documents;

		public MdbReader(ModuleDefinition module, MonoSymbolFile symFile)
		{
			this.module = module;
			symbol_file = symFile;
			documents = new Dictionary<string, Document>();
		}

		public ISymbolWriterProvider GetWriterProvider()
		{
			return (ISymbolWriterProvider)(object)new MdbWriterProvider();
		}

		public bool ProcessDebugHeader(ImageDebugHeader header)
		{
			return symbol_file.Guid == module.Mvid;
		}

		public MethodDebugInformation Read(MethodDefinition method)
		{
			//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_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			MetadataToken metadataToken = ((MemberReference)method).MetadataToken;
			MethodEntry methodByToken = symbol_file.GetMethodByToken(((MetadataToken)(ref metadataToken)).ToInt32());
			if (methodByToken == null)
			{
				return null;
			}
			MethodDebugInformation val = new MethodDebugInformation(method);
			val.code_size = ReadCodeSize(method);
			ScopeDebugInformation[] scopes = ReadScopes(methodByToken, val);
			ReadLineNumbers(methodByToken, val);
			ReadLocalVariables(methodByToken, scopes);
			return val;
		}

		private static int ReadCodeSize(MethodDefinition method)
		{
			return ((MemberReference)method).Module.Read<MethodDefinition, int>(method, (Func<MethodDefinition, MetadataReader, int>)((MethodDefinition m, MetadataReader reader) => reader.ReadCodeSize(m)));
		}

		private static void ReadLocalVariables(MethodEntry entry, ScopeDebugInformation[] scopes)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			LocalVariableEntry[] locals = entry.GetLocals();
			for (int i = 0; i < locals.Length; i++)
			{
				LocalVariableEntry localVariableEntry = locals[i];
				VariableDebugInformation val = new VariableDebugInformation(localVariableEntry.Index, localVariableEntry.Name);
				int blockIndex = localVariableEntry.BlockIndex;
				if (blockIndex >= 0 && blockIndex < scopes.Length)
				{
					ScopeDebugInformation val2 = scopes[blockIndex];
					if (val2 != null)
					{
						val2.Variables.Add(val);
					}
				}
			}
		}

		private void ReadLineNumbers(MethodEntry entry, MethodDebugInformation info)
		{
			LineNumberTable lineNumberTable = entry.GetLineNumberTable();
			info.sequence_points = new Collection<SequencePoint>(lineNumberTable.LineNumbers.Length);
			for (int i = 0; i < lineNumberTable.LineNumbers.Length; i++)
			{
				LineNumberEntry lineNumberEntry = lineNumberTable.LineNumbers[i];
				if (i <= 0 || lineNumberTable.LineNumbers[i - 1].Offset != lineNumberEntry.Offset)
				{
					info.sequence_points.Add(LineToSequencePoint(lineNumberEntry));
				}
			}
		}

		private Document GetDocument(SourceFileEntry file)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			string fileName = file.FileName;
			if (documents.TryGetValue(fileName, out var value))
			{
				return value;
			}
			value = new Document(fileName)
			{
				Hash = file.Checksum
			};
			documents.Add(fileName, value);
			return value;
		}

		private static ScopeDebugInformation[] ReadScopes(MethodEntry entry, MethodDebugInformation info)
		{
			//IL_0014: 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_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_002c: 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_0038: Expected O, but got Unknown
			//IL_0039: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_006d: 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)
			CodeBlockEntry[] codeBlocks = entry.GetCodeBlocks();
			ScopeDebugInformation[] array = (ScopeDebugInformation[])(object)new ScopeDebugInformation[codeBlocks.Length + 1];
			ScopeDebugInformation val = new ScopeDebugInformation
			{
				Start = new InstructionOffset(0),
				End = new InstructionOffset(info.code_size)
			};
			ScopeDebugInformation scope = val;
			array[0] = val;
			info.scope = scope;
			CodeBlockEntry[] array2 = codeBlocks;
			foreach (CodeBlockEntry codeBlockEntry in array2)
			{
				if (codeBlockEntry.BlockType == CodeBlockEntry.Type.Lexical || codeBlockEntry.BlockType == CodeBlockEntry.Type.CompilerGenerated)
				{
					ScopeDebugInformation val2 = new ScopeDebugInformation();
					val2.Start = new InstructionOffset(codeBlockEntry.StartOffset);
					val2.End = new InstructionOffset(codeBlockEntry.EndOffset);
					array[codeBlockEntry.Index + 1] = val2;
					if (!AddScope(info.scope.Scopes, val2))
					{
						info.scope.Scopes.Add(val2);
					}
				}
			}
			return array;
		}

		private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope)
		{
			//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_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_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_004a: 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_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)
			Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ScopeDebugInformation current = enumerator.Current;
					if (current.HasScopes && AddScope(current.Scopes, scope))
					{
						return true;
					}
					InstructionOffset val = scope.Start;
					int offset = ((InstructionOffset)(ref val)).Offset;
					val = current.Start;
					if (offset >= ((InstructionOffset)(ref val)).Offset)
					{
						val = scope.End;
						int offset2 = ((InstructionOffset)(ref val)).Offset;
						val = current.End;
						if (offset2 <= ((InstructionOffset)(ref val)).Offset)
						{
							current.Scopes.Add(scope);
							return true;
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return false;
		}

		private SequencePoint LineToSequencePoint(LineNumberEntry line)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			SourceFileEntry sourceFile = symbol_file.GetSourceFile(line.File);
			return new SequencePoint(line.Offset, GetDocument(sourceFile))
			{
				StartLine = line.Row,
				EndLine = line.EndRow,
				StartColumn = line.Column,
				EndColumn = line.EndColumn
			};
		}

		public void Dispose()
		{
			symbol_file.Dispose();
		}
	}
	internal static class MethodEntryExtensions
	{
		public static bool HasColumnInfo(this MethodEntry entry)
		{
			return (entry.MethodFlags & MethodEntry.Flags.ColumnsInfoIncluded) != 0;
		}

		public static bool HasEndInfo(this MethodEntry entry)
		{
			return (entry.MethodFlags & MethodEntry.Flags.EndInfoIncluded) != 0;
		}
	}
	public sealed class MdbWriterProvider : ISymbolWriterProvider
	{
		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName)
		{
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolWriter)(object)new MdbWriter(module.Mvid, fileName);
		}

		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream)
		{
			throw new NotImplementedException();
		}
	}
	public sealed class MdbWriter : ISymbolWriter, IDisposable
	{
		private class SourceFile : ISourceFile
		{
			private readonly CompileUnitEntry compilation_unit;

			private readonly SourceFileEntry entry;

			public SourceFileEntry Entry => entry;

			public CompileUnitEntry CompilationUnit => compilation_unit;

			public SourceFile(CompileUnitEntry comp_unit, SourceFileEntry entry)
			{
				compilation_unit = comp_unit;
				this.entry = entry;
			}
		}

		private class SourceMethod : IMethodDef
		{
			private readonly MethodDefinition method;

			public string Name => ((MemberReference)method).Name;

			public int Token
			{
				get
				{
					//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)
					MetadataToken metadataToken = ((MemberReference)method).MetadataToken;
					return ((MetadataToken)(ref metadataToken)).ToInt32();
				}
			}

			public SourceMethod(MethodDefinition method)
			{
				this.method = method;
			}
		}

		private readonly Guid mvid;

		private readonly MonoSymbolWriter writer;

		private readonly Dictionary<string, SourceFile> source_files;

		public MdbWriter(Guid mvid, string assembly)
		{
			this.mvid = mvid;
			writer = new MonoSymbolWriter(assembly);
			source_files = new Dictionary<string, SourceFile>();
		}

		public ISymbolReaderProvider GetReaderProvider()
		{
			return (ISymbolReaderProvider)(object)new MdbReaderProvider();
		}

		private SourceFile GetSourceFile(Document document)
		{
			string url = document.Url;
			if (source_files.TryGetValue(url, out var value))
			{
				return value;
			}
			SourceFileEntry sourceFileEntry = writer.DefineDocument(url, null, (document.Hash != null && document.Hash.Length == 16) ? document.Hash : null);
			value = new SourceFile(writer.DefineCompilationUnit(sourceFileEntry), sourceFileEntry);
			source_files.Add(url, value);
			return value;
		}

		private void Populate(Collection<SequencePoint> sequencePoints, int[] offsets, int[] startRows, int[] endRows, int[] startCols, int[] endCols, out SourceFile file)
		{
			SourceFile sourceFile = null;
			for (int i = 0; i < sequencePoints.Count; i++)
			{
				SequencePoint val = sequencePoints[i];
				offsets[i] = val.Offset;
				if (sourceFile == null)
				{
					sourceFile = GetSourceFile(val.Document);
				}
				startRows[i] = val.StartLine;
				endRows[i] = val.EndLine;
				startCols[i] = val.StartColumn;
				endCols[i] = val.EndColumn;
			}
			file = sourceFile;
		}

		public void Write(MethodDebugInformation info)
		{
			SourceMethod method = new SourceMethod(info.method);
			Collection<SequencePoint> sequencePoints = info.SequencePoints;
			int count = sequencePoints.Count;
			if (count != 0)
			{
				int[] array = new int[count];
				int[] array2 = new int[count];
				int[] array3 = new int[count];
				int[] array4 = new int[count];
				int[] array5 = new int[count];
				Populate(sequencePoints, array, array2, array3, array4, array5, out var file);
				SourceMethodBuilder sourceMethodBuilder = writer.OpenMethod(file.CompilationUnit, 0, method);
				for (int i = 0; i < count; i++)
				{
					sourceMethodBuilder.MarkSequencePoint(array[i], file.CompilationUnit.SourceFile, array2[i], array4[i], array3[i], array5[i], is_hidden: false);
				}
				if (info.scope != null)
				{
					WriteRootScope(info.scope, info);
				}
				writer.CloseMethod();
			}
		}

		private void WriteRootScope(ScopeDebugInformation scope, MethodDebugInformation info)
		{
			WriteScopeVariables(scope);
			if (scope.HasScopes)
			{
				WriteScopes(scope.Scopes, info);
			}
		}

		private void WriteScope(ScopeDebugInformation scope, MethodDebugInformation info)
		{
			//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_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_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			MonoSymbolWriter monoSymbolWriter = writer;
			InstructionOffset val = scope.Start;
			monoSymbolWriter.OpenScope(((InstructionOffset)(ref val)).Offset);
			WriteScopeVariables(scope);
			if (scope.HasScopes)
			{
				WriteScopes(scope.Scopes, info);
			}
			MonoSymbolWriter monoSymbolWriter2 = writer;
			val = scope.End;
			int end_offset;
			if (!((InstructionOffset)(ref val)).IsEndOfMethod)
			{
				val = scope.End;
				end_offset = ((InstructionOffset)(ref val)).Offset;
			}
			else
			{
				end_offset = info.code_size;
			}
			monoSymbolWriter2.CloseScope(end_offset);
		}

		private void WriteScopes(Collection<ScopeDebugInformation> scopes, MethodDebugInformation info)
		{
			for (int i = 0; i < scopes.Count; i++)
			{
				WriteScope(scopes[i], info);
			}
		}

		private void WriteScopeVariables(ScopeDebugInformation scope)
		{
			//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)
			if (!scope.HasVariables)
			{
				return;
			}
			Enumerator<VariableDebugInformation> enumerator = scope.variables.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					VariableDebugInformation current = enumerator.Current;
					if (!string.IsNullOrEmpty(current.Name))
					{
						writer.DefineLocalVariable(current.Index, current.Name);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public ImageDebugHeader GetDebugHeader()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			return new ImageDebugHeader();
		}

		public void Dispose()
		{
			writer.WriteSymbolFile(mvid);
		}
	}
}

BooBoo Building/BepInEx/core/Mono.Cecil.Pdb.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.InteropServices.ComTypes;
using System.Text;
using Microsoft.Cci;
using Microsoft.Cci.Pdb;
using Mono.Cecil.Cil;
using Mono.Cecil.PE;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil.Pdb")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyVersion("0.10.4.0")]
namespace Mono.Cecil.Pdb
{
	[ComImport]
	[Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface ISymUnmanagedDocumentWriter
	{
	}
	[ComImport]
	[Guid("0B97726E-9E6D-4f05-9A26-424022093CAA")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface ISymUnmanagedWriter2
	{
		void DefineDocument([In][MarshalAs(UnmanagedType.LPWStr)] string url, [In] ref Guid langauge, [In] ref Guid languageVendor, [In] ref Guid documentType, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedDocumentWriter pRetVal);

		void SetUserEntryPoint([In] int methodToken);

		void OpenMethod([In] int methodToken);

		void CloseMethod();

		void OpenScope([In] int startOffset, out int pRetVal);

		void CloseScope([In] int endOffset);

		void SetScopeRange_Placeholder();

		void DefineLocalVariable_Placeholder();

		void DefineParameter_Placeholder();

		void DefineField_Placeholder();

		void DefineGlobalVariable_Placeholder();

		void Close();

		void SetSymAttribute(uint parent, string name, uint data, IntPtr signature);

		void OpenNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string name);

		void CloseNamespace();

		void UsingNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string fullName);

		void SetMethodSourceRange_Placeholder();

		void Initialize([In][MarshalAs(UnmanagedType.IUnknown)] object emitter, [In][MarshalAs(UnmanagedType.LPWStr)] string filename, [In] IStream pIStream, [In] bool fFullBuild);

		void GetDebugInfo(out ImageDebugDirectory pIDD, [In] int cData, out int pcData, [In][Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data);

		void DefineSequencePoints([In][MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter document, [In] int spCount, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns);

		void RemapToken_Placeholder();

		void Initialize2_Placeholder();

		void DefineConstant_Placeholder();

		void Abort_Placeholder();

		void DefineLocalVariable2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In] int attributes, [In] int sigToken, [In] int addrKind, [In] int addr1, [In] int addr2, [In] int addr3, [In] int startOffset, [In] int endOffset);

		void DefineGlobalVariable2_Placeholder();

		void DefineConstant2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In][MarshalAs(UnmanagedType.Struct)] object variant, [In] int sigToken);
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")]
	internal interface IMetaDataEmit
	{
		void SetModuleProps(string szName);

		void Save(string szFile, uint dwSaveFlags);

		void SaveToStream(IntPtr pIStream, uint dwSaveFlags);

		uint GetSaveSize(uint fSave);

		uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements);

		uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser);

		void SetHandler([In][MarshalAs(UnmanagedType.IUnknown)] object pUnk);

		uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags);

		void DefineMethodImpl(uint td, uint tkBody, uint tkDecl);

		uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName);

		uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit);

		uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob);

		uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent);

		uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods);

		void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize);

		void DeleteClassLayout(uint td);

		void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType);

		void DeleteFieldMarshal(uint tk);

		uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission);

		void SetRVA(uint md, uint ulRVA);

		uint GetTokenFromSig(IntPtr pvSig, uint cbSig);

		uint DefineModuleRef(string szName);

		void SetParent(uint mr, uint tk);

		uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig);

		void SaveToMemory(IntPtr pbData, uint cbData);

		uint DefineUserString(string szString, uint cchString);

		void DeleteToken(uint tkObj);

		void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags);

		void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements);

		void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods);

		uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission);

		void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);

		void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);

		void DeletePinvokeMap(uint tk);

		uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute);

		void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute);

		uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods);

		uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods);

		void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs);

		void ApplyEditAndContinue([MarshalAs(UnmanagedType.IUnknown)] object pImport);

		uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax);

		void SetMethodImplFlags(uint md, uint dwImplFlags);

		void SetFieldRVA(uint fd, uint ulRVA);

		void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, [MarshalAs(UnmanagedType.IUnknown)] object pHandler);

		void MergeEnd();
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44")]
	internal interface IMetaDataImport
	{
		[PreserveSig]
		void CloseEnum(uint hEnum);

		uint CountEnum(uint hEnum);

		void ResetEnum(uint hEnum, uint ulPos);

		uint EnumTypeDefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeDefs, uint cMax);

		uint EnumInterfaceImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rImpls, uint cMax);

		uint EnumTypeRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeRefs, uint cMax);

		uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass);

		Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName);

		uint GetModuleFromScope();

		uint GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags);

		uint GetInterfaceImplProps(uint iiImpl, out uint pClass);

		uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName);

		uint ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIScope);

		uint EnumMembers(ref uint phEnum, uint cl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMembers, uint cMax);

		uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMembers, uint cMax);

		uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax);

		uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethods, uint cMax);

		uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax);

		uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rFields, uint cMax);

		uint EnumParams(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rParams, uint cMax);

		uint EnumMemberRefs(ref uint phEnum, uint tkParent, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMemberRefs, uint cMax);

		uint EnumMethodImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodBody, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodDecl, uint cMax);

		uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rPermission, uint cMax);

		uint FindMember(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint FindMethod(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint FindField(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint FindMemberRef(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA);

		uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob);

		uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax);

		uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax);

		uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 11)] uint[] rmdOtherMethod, uint cMax);

		uint EnumMethodSemantics(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rEventProp, uint cMax);

		uint GetMethodSemantics(uint mb, uint tkEventProp);

		uint GetClassLayout(uint td, out uint pdwPackSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset);

		uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType);

		uint GetRVA(uint tk, out uint pulCodeRVA);

		uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission);

		uint GetSigFromToken(uint mdSig, out IntPtr ppvSig);

		uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName);

		uint EnumModuleRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rModuleRefs, uint cmax);

		uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig);

		uint GetNameFromToken(uint tk);

		uint EnumUnresolvedMethods(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rMethods, uint cMax);

		uint GetUserString(uint stk, StringBuilder szString, uint cchString);

		uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName);

		uint EnumSignatures(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rSignatures, uint cmax);

		uint EnumTypeSpecs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeSpecs, uint cmax);

		uint EnumUserStrings(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rStrings, uint cmax);

		[PreserveSig]
		int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam);

		uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rCustomAttributes, uint cMax);

		uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob);

		uint FindTypeRef(uint tkResolutionScope, string szName);

		uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue);

		uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue);

		uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 14)] uint[] rmdOtherMethod, uint cMax);

		uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue);

		uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData);

		[PreserveSig]
		[return: MarshalAs(UnmanagedType.Bool)]
		bool IsValidToken(uint tk);

		uint GetNestedClassProps(uint tdNestedClass);

		uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig);

		int IsGlobal(uint pd);
	}
	internal class ModuleMetadata : IMetaDataEmit, IMetaDataImport
	{
		private readonly ModuleDefinition module;

		private Dictionary<uint, TypeDefinition> types;

		private Dictionary<uint, MethodDefinition> methods;

		public ModuleMetadata(ModuleDefinition module)
		{
			this.module = module;
		}

		private bool TryGetType(uint token, out TypeDefinition type)
		{
			if (types == null)
			{
				InitializeMetadata(module);
			}
			return types.TryGetValue(token, out type);
		}

		private bool TryGetMethod(uint token, out MethodDefinition method)
		{
			if (methods == null)
			{
				InitializeMetadata(module);
			}
			return methods.TryGetValue(token, out method);
		}

		private void InitializeMetadata(ModuleDefinition module)
		{
			//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)
			types = new Dictionary<uint, TypeDefinition>();
			methods = new Dictionary<uint, MethodDefinition>();
			foreach (TypeDefinition type in module.GetTypes())
			{
				Dictionary<uint, TypeDefinition> dictionary = types;
				MetadataToken metadataToken = ((MemberReference)type).MetadataToken;
				dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), type);
				InitializeMethods(type);
			}
		}

		private void InitializeMethods(TypeDefinition type)
		{
			//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_0022: 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;
					Dictionary<uint, MethodDefinition> dictionary = methods;
					MetadataToken metadataToken = ((MemberReference)current).MetadataToken;
					dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public void SetModuleProps(string szName)
		{
			throw new NotImplementedException();
		}

		public void Save(string szFile, uint dwSaveFlags)
		{
			throw new NotImplementedException();
		}

		public void SaveToStream(IntPtr pIStream, uint dwSaveFlags)
		{
			throw new NotImplementedException();
		}

		public uint GetSaveSize(uint fSave)
		{
			throw new NotImplementedException();
		}

		public uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements)
		{
			throw new NotImplementedException();
		}

		public uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser)
		{
			throw new NotImplementedException();
		}

		public void SetHandler(object pUnk)
		{
			throw new NotImplementedException();
		}

		public uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags)
		{
			throw new NotImplementedException();
		}

		public void DefineMethodImpl(uint td, uint tkBody, uint tkDecl)
		{
			throw new NotImplementedException();
		}

		public uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName)
		{
			throw new NotImplementedException();
		}

		public uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit)
		{
			throw new NotImplementedException();
		}

		public uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent)
		{
			throw new NotImplementedException();
		}

		public uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize)
		{
			throw new NotImplementedException();
		}

		public void DeleteClassLayout(uint td)
		{
			throw new NotImplementedException();
		}

		public void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType)
		{
			throw new NotImplementedException();
		}

		public void DeleteFieldMarshal(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission)
		{
			throw new NotImplementedException();
		}

		public void SetRVA(uint md, uint ulRVA)
		{
			throw new NotImplementedException();
		}

		public uint GetTokenFromSig(IntPtr pvSig, uint cbSig)
		{
			throw new NotImplementedException();
		}

		public uint DefineModuleRef(string szName)
		{
			throw new NotImplementedException();
		}

		public void SetParent(uint mr, uint tk)
		{
			throw new NotImplementedException();
		}

		public uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig)
		{
			throw new NotImplementedException();
		}

		public void SaveToMemory(IntPtr pbData, uint cbData)
		{
			throw new NotImplementedException();
		}

		public uint DefineUserString(string szString, uint cchString)
		{
			throw new NotImplementedException();
		}

		public void DeleteToken(uint tkObj)
		{
			throw new NotImplementedException();
		}

		public void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags)
		{
			throw new NotImplementedException();
		}

		public void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements)
		{
			throw new NotImplementedException();
		}

		public void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission)
		{
			throw new NotImplementedException();
		}

		public void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL)
		{
			throw new NotImplementedException();
		}

		public void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL)
		{
			throw new NotImplementedException();
		}

		public void DeletePinvokeMap(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute)
		{
			throw new NotImplementedException();
		}

		public void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute)
		{
			throw new NotImplementedException();
		}

		public uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs)
		{
			throw new NotImplementedException();
		}

		public void ApplyEditAndContinue(object pImport)
		{
			throw new NotImplementedException();
		}

		public uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax)
		{
			throw new NotImplementedException();
		}

		public void SetMethodImplFlags(uint md, uint dwImplFlags)
		{
			throw new NotImplementedException();
		}

		public void SetFieldRVA(uint fd, uint ulRVA)
		{
			throw new NotImplementedException();
		}

		public void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, object pHandler)
		{
			throw new NotImplementedException();
		}

		public void MergeEnd()
		{
			throw new NotImplementedException();
		}

		public void CloseEnum(uint hEnum)
		{
			throw new NotImplementedException();
		}

		public uint CountEnum(uint hEnum)
		{
			throw new NotImplementedException();
		}

		public void ResetEnum(uint hEnum, uint ulPos)
		{
			throw new NotImplementedException();
		}

		public uint EnumTypeDefs(ref uint phEnum, uint[] rTypeDefs, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumInterfaceImpls(ref uint phEnum, uint td, uint[] rImpls, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumTypeRefs(ref uint phEnum, uint[] rTypeRefs, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass)
		{
			throw new NotImplementedException();
		}

		public Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName)
		{
			throw new NotImplementedException();
		}

		public uint GetModuleFromScope()
		{
			throw new NotImplementedException();
		}

		public uint GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected I4, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGetType(td, out var type))
			{
				Marshal.WriteInt16(szTypeDef, 0);
				pchTypeDef = 1u;
				return 0u;
			}
			WriteString(((TypeReference)type).IsNested ? ((MemberReference)type).Name : ((MemberReference)type).FullName, szTypeDef, cchTypeDef, out pchTypeDef);
			WriteIntPtr(pdwTypeDefFlags, (uint)(int)type.Attributes);
			if (type.BaseType == null)
			{
				return 0u;
			}
			MetadataToken metadataToken = ((MemberReference)type.BaseType).MetadataToken;
			return ((MetadataToken)(ref metadataToken)).ToUInt32();
		}

		private static void WriteIntPtr(IntPtr ptr, uint value)
		{
			if (!(ptr == IntPtr.Zero))
			{
				Marshal.WriteInt32(ptr, (int)value);
			}
		}

		private static void WriteString(string str, IntPtr buffer, uint bufferSize, out uint chars)
		{
			uint num = ((str.Length + 1 >= bufferSize) ? (bufferSize - 1) : ((uint)str.Length));
			chars = num + 1;
			int num2 = 0;
			for (int i = 0; i < num; i++)
			{
				Marshal.WriteInt16(buffer, num2, str[i]);
				num2 += 2;
			}
			Marshal.WriteInt16(buffer, num2, 0);
		}

		public uint GetInterfaceImplProps(uint iiImpl, out uint pClass)
		{
			throw new NotImplementedException();
		}

		public uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName)
		{
			throw new NotImplementedException();
		}

		public uint ResolveTypeRef(uint tr, ref Guid riid, out object ppIScope)
		{
			throw new NotImplementedException();
		}

		public uint EnumMembers(ref uint phEnum, uint cl, uint[] rMembers, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, uint[] rMembers, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, uint[] rMethods, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, uint[] rFields, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumParams(ref uint phEnum, uint mb, uint[] rParams, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMemberRefs(ref uint phEnum, uint tkParent, uint[] rMemberRefs, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethodImpls(ref uint phEnum, uint td, uint[] rMethodBody, uint[] rMethodDecl, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, uint[] rPermission, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint FindMember(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindMethod(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindField(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindMemberRef(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA)
		{
			//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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected I4, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected I4, but got Unknown
			if (!TryGetMethod(mb, out var method))
			{
				Marshal.WriteInt16(szMethod, 0);
				pchMethod = 1u;
				pClass = 0u;
				return 0u;
			}
			MetadataToken metadataToken = ((MemberReference)method.DeclaringType).MetadataToken;
			pClass = ((MetadataToken)(ref metadataToken)).ToUInt32();
			WriteString(((MemberReference)method).Name, szMethod, cchMethod, out pchMethod);
			WriteIntPtr(pdwAttr, (uint)(int)method.Attributes);
			WriteIntPtr(pulCodeRVA, (uint)method.RVA);
			return (uint)(int)method.ImplAttributes;
		}

		public uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, uint[] rmdOtherMethod, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethodSemantics(ref uint phEnum, uint mb, uint[] rEventProp, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetMethodSemantics(uint mb, uint tkEventProp)
		{
			throw new NotImplementedException();
		}

		public uint GetClassLayout(uint td, out uint pdwPackSize, IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset)
		{
			throw new NotImplementedException();
		}

		public uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType)
		{
			throw new NotImplementedException();
		}

		public uint GetRVA(uint tk, out uint pulCodeRVA)
		{
			throw new NotImplementedException();
		}

		public uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission)
		{
			throw new NotImplementedException();
		}

		public uint GetSigFromToken(uint mdSig, out IntPtr ppvSig)
		{
			throw new NotImplementedException();
		}

		public uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName)
		{
			throw new NotImplementedException();
		}

		public uint EnumModuleRefs(ref uint phEnum, uint[] rModuleRefs, uint cmax)
		{
			throw new NotImplementedException();
		}

		public uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig)
		{
			throw new NotImplementedException();
		}

		public uint GetNameFromToken(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint EnumUnresolvedMethods(ref uint phEnum, uint[] rMethods, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetUserString(uint stk, StringBuilder szString, uint cchString)
		{
			throw new NotImplementedException();
		}

		public uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName)
		{
			throw new NotImplementedException();
		}

		public uint EnumSignatures(ref uint phEnum, uint[] rSignatures, uint cmax)
		{
			throw new NotImplementedException();
		}

		public uint EnumTypeSpecs(ref uint phEnum, uint[] rTypeSpecs, uint cmax)
		{
			throw new NotImplementedException();
		}

		public uint EnumUserStrings(ref uint phEnum, uint[] rStrings, uint cmax)
		{
			throw new NotImplementedException();
		}

		public int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam)
		{
			throw new NotImplementedException();
		}

		public uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, uint[] rCustomAttributes, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindTypeRef(uint tkResolutionScope, string szName)
		{
			throw new NotImplementedException();
		}

		public uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
		{
			throw new NotImplementedException();
		}

		public uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
		{
			throw new NotImplementedException();
		}

		public uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, uint[] rmdOtherMethod, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
		{
			throw new NotImplementedException();
		}

		public uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData)
		{
			throw new NotImplementedException();
		}

		public bool IsValidToken(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint GetNestedClassProps(uint tdNestedClass)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGetType(tdNestedClass, out var type))
			{
				return 0u;
			}
			if (!((TypeReference)type).IsNested)
			{
				return 0u;
			}
			MetadataToken metadataToken = ((MemberReference)type.DeclaringType).MetadataToken;
			return ((MetadataToken)(ref metadataToken)).ToUInt32();
		}

		public uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig)
		{
			throw new NotImplementedException();
		}

		public int IsGlobal(uint pd)
		{
			throw new NotImplementedException();
		}
	}
	public class NativePdbReader : ISymbolReader, IDisposable
	{
		private int age;

		private Guid guid;

		private readonly Disposable<Stream> pdb_file;

		private readonly Dictionary<string, Document> documents = new Dictionary<string, Document>();

		private readonly Dictionary<uint, PdbFunction> functions = new Dictionary<uint, PdbFunction>();

		private readonly Dictionary<PdbScope, ImportDebugInformation> imports = new Dictionary<PdbScope, ImportDebugInformation>();

		internal NativePdbReader(Disposable<Stream> file)
		{
			//IL_0028: 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)
			pdb_file = file;
		}

		public ISymbolWriterProvider GetWriterProvider()
		{
			return (ISymbolWriterProvider)(object)new NativePdbWriterProvider();
		}

		public bool ProcessDebugHeader(ImageDebugHeader header)
		{
			//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_0022: Invalid comparison between Unknown and I4
			if (!header.HasEntries)
			{
				return false;
			}
			ImageDebugHeaderEntry codeViewEntry = Mixin.GetCodeViewEntry(header);
			if (codeViewEntry == null)
			{
				return false;
			}
			if ((int)codeViewEntry.Directory.Type != 2)
			{
				return false;
			}
			byte[] data = codeViewEntry.Data;
			if (data.Length < 24)
			{
				return false;
			}
			if (ReadInt32(data, 0) != 1396986706)
			{
				return false;
			}
			byte[] array = new byte[16];
			Buffer.BlockCopy(data, 4, array, 0, 16);
			guid = new Guid(array);
			age = ReadInt32(data, 20);
			return PopulateFunctions();
		}

		private static int ReadInt32(byte[] bytes, int start)
		{
			return bytes[start] | (bytes[start + 1] << 8) | (bytes[start + 2] << 16) | (bytes[start + 3] << 24);
		}

		private bool PopulateFunctions()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			Disposable<Stream> val = pdb_file;
			try
			{
				Dictionary<uint, PdbTokenLine> tokenToSourceMapping;
				string sourceServerData;
				int num;
				Guid guid;
				PdbFunction[] array = PdbFile.LoadFunctions(pdb_file.value, out tokenToSourceMapping, out sourceServerData, out num, out guid);
				if (this.guid != guid)
				{
					return false;
				}
				PdbFunction[] array2 = array;
				foreach (PdbFunction pdbFunction in array2)
				{
					functions.Add(pdbFunction.token, pdbFunction);
				}
			}
			finally
			{
				((IDisposable)val).Dispose();
			}
			return true;
		}

		public MethodDebugInformation Read(MethodDefinition method)
		{
			//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_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//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_0043: 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_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Expected O, but got Unknown
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Expected O, but got Unknown
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Expected O, but got Unknown
			MetadataToken metadataToken = ((MemberReference)method).MetadataToken;
			if (!functions.TryGetValue(((MetadataToken)(ref metadataToken)).ToUInt32(), out var value))
			{
				return null;
			}
			MethodDebugInformation val = new MethodDebugInformation(method);
			ReadSequencePoints(value, val);
			val.scope = (ScopeDebugInformation)((!Mixin.IsNullOrEmpty<PdbScope>(value.scopes)) ? ((object)ReadScopeAndLocals(value.scopes[0], val)) : ((object)new ScopeDebugInformation
			{
				Start = new InstructionOffset(0),
				End = new InstructionOffset((int)value.length)
			}));
			uint tokenOfMethodWhoseUsingInfoAppliesToThisMethod = value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod;
			MetadataToken metadataToken2 = ((MemberReference)method).MetadataToken;
			if (tokenOfMethodWhoseUsingInfoAppliesToThisMethod != ((MetadataToken)(ref metadataToken2)).ToUInt32() && value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod != 0)
			{
				val.scope.import = GetImport(value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod, ((MemberReference)method).Module);
			}
			if (value.scopes.Length > 1)
			{
				for (int i = 1; i < value.scopes.Length; i++)
				{
					ScopeDebugInformation val2 = ReadScopeAndLocals(value.scopes[i], val);
					if (!AddScope(val.scope.Scopes, val2))
					{
						val.scope.Scopes.Add(val2);
					}
				}
			}
			if (value.iteratorScopes != null)
			{
				StateMachineScopeDebugInformation val3 = new StateMachineScopeDebugInformation();
				foreach (ILocalScope iteratorScope in value.iteratorScopes)
				{
					val3.Scopes.Add(new StateMachineScope((int)iteratorScope.Offset, (int)(iteratorScope.Offset + iteratorScope.Length + 1)));
				}
				((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val3);
			}
			if (value.synchronizationInformation != null)
			{
				AsyncMethodBodyDebugInformation val4 = new AsyncMethodBodyDebugInformation((int)value.synchronizationInformation.GeneratedCatchHandlerOffset);
				PdbSynchronizationPoint[] synchronizationPoints = value.synchronizationInformation.synchronizationPoints;
				foreach (PdbSynchronizationPoint pdbSynchronizationPoint in synchronizationPoints)
				{
					val4.Yields.Add(new InstructionOffset((int)pdbSynchronizationPoint.SynchronizeOffset));
					val4.Resumes.Add(new InstructionOffset((int)pdbSynchronizationPoint.ContinuationOffset));
					val4.ResumeMethods.Add(method);
				}
				((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val4);
				val.StateMachineKickOffMethod = (MethodDefinition)((MemberReference)method).Module.LookupToken((int)value.synchronizationInformation.kickoffMethodToken);
			}
			return val;
		}

		private Collection<ScopeDebugInformation> ReadScopeAndLocals(PdbScope[] scopes, MethodDebugInformation info)
		{
			Collection<ScopeDebugInformation> val = new Collection<ScopeDebugInformation>(scopes.Length);
			foreach (PdbScope pdbScope in scopes)
			{
				if (pdbScope != null)
				{
					val.Add(ReadScopeAndLocals(pdbScope, info));
				}
			}
			return val;
		}

		private ScopeDebugInformation ReadScopeAndLocals(PdbScope scope, MethodDebugInformation info)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_000d: 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_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			ScopeDebugInformation val = new ScopeDebugInformation();
			val.Start = new InstructionOffset((int)scope.offset);
			val.End = new InstructionOffset((int)(scope.offset + scope.length));
			if (!Mixin.IsNullOrEmpty<PdbSlot>(scope.slots))
			{
				val.variables = new Collection<VariableDebugInformation>(scope.slots.Length);
				PdbSlot[] slots = scope.slots;
				foreach (PdbSlot pdbSlot in slots)
				{
					if ((pdbSlot.flags & 1) == 0)
					{
						VariableDebugInformation val2 = new VariableDebugInformation((int)pdbSlot.slot, pdbSlot.name);
						if ((pdbSlot.flags & 4u) != 0)
						{
							val2.IsDebuggerHidden = true;
						}
						val.variables.Add(val2);
					}
				}
			}
			if (!Mixin.IsNullOrEmpty<PdbConstant>(scope.constants))
			{
				val.constants = new Collection<ConstantDebugInformation>(scope.constants.Length);
				PdbConstant[] constants = scope.constants;
				foreach (PdbConstant pdbConstant in constants)
				{
					TypeReference val3 = ((MemberReference)info.Method).Module.Read<PdbConstant, TypeReference>(pdbConstant, (Func<PdbConstant, MetadataReader, TypeReference>)((PdbConstant c, MetadataReader r) => r.ReadConstantSignature(new MetadataToken(c.token))));
					object obj = pdbConstant.value;
					if (val3 != null && !val3.IsValueType && obj is int && (int)obj == 0)
					{
						obj = null;
					}
					val.constants.Add(new ConstantDebugInformation(pdbConstant.name, val3, obj));
				}
			}
			if (!Mixin.IsNullOrEmpty<string>(scope.usedNamespaces))
			{
				if (imports.TryGetValue(scope, out var value))
				{
					val.import = value;
				}
				else
				{
					value = GetImport(scope, ((MemberReference)info.Method).Module);
					imports.Add(scope, value);
					val.import = value;
				}
			}
			val.scopes = ReadScopeAndLocals(scope.scopes, info);
			return val;
		}

		private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope)
		{
			//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_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_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_004a: 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_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)
			Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ScopeDebugInformation current = enumerator.Current;
					if (current.HasScopes && AddScope(current.Scopes, scope))
					{
						return true;
					}
					InstructionOffset val = scope.Start;
					int offset = ((InstructionOffset)(ref val)).Offset;
					val = current.Start;
					if (offset >= ((InstructionOffset)(ref val)).Offset)
					{
						val = scope.End;
						int offset2 = ((InstructionOffset)(ref val)).Offset;
						val = current.End;
						if (offset2 <= ((InstructionOffset)(ref val)).Offset)
						{
							current.Scopes.Add(scope);
							return true;
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return false;
		}

		private ImportDebugInformation GetImport(uint token, ModuleDefinition module)
		{
			if (!functions.TryGetValue(token, out var value))
			{
				return null;
			}
			if (value.scopes.Length != 1)
			{
				return null;
			}
			PdbScope pdbScope = value.scopes[0];
			if (imports.TryGetValue(pdbScope, out var value2))
			{
				return value2;
			}
			value2 = GetImport(pdbScope, module);
			imports.Add(pdbScope, value2);
			return value2;
		}

		private static ImportDebugInformation GetImport(PdbScope scope, ModuleDefinition module)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//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_015d: Expected O, but got Unknown
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//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: Expected O, but got Unknown
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			//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)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			if (Mixin.IsNullOrEmpty<string>(scope.usedNamespaces))
			{
				return null;
			}
			ImportDebugInformation val = new ImportDebugInformation();
			string[] usedNamespaces = scope.usedNamespaces;
			foreach (string text in usedNamespaces)
			{
				if (string.IsNullOrEmpty(text))
				{
					continue;
				}
				ImportTarget val2 = null;
				string text2 = text.Substring(1);
				switch (text[0])
				{
				case 'U':
					val2 = new ImportTarget((ImportTargetKind)1)
					{
						@namespace = text2
					};
					break;
				case 'T':
				{
					TypeReference val4 = TypeParser.ParseType(module, text2, false);
					if (val4 != null)
					{
						val2 = new ImportTarget((ImportTargetKind)3)
						{
							type = val4
						};
					}
					break;
				}
				case 'A':
				{
					int num = text.IndexOf(' ');
					if (num < 0)
					{
						val2 = new ImportTarget((ImportTargetKind)1)
						{
							@namespace = text
						};
						break;
					}
					string alias = text.Substring(1, num - 1);
					string text3 = text.Substring(num + 2);
					switch (text[num + 1])
					{
					case 'U':
						val2 = new ImportTarget((ImportTargetKind)7)
						{
							alias = alias,
							@namespace = text3
						};
						break;
					case 'T':
					{
						TypeReference val3 = TypeParser.ParseType(module, text3, false);
						if (val3 != null)
						{
							val2 = new ImportTarget((ImportTargetKind)9)
							{
								alias = alias,
								type = val3
							};
						}
						break;
					}
					}
					break;
				}
				case '*':
					val2 = new ImportTarget((ImportTargetKind)1)
					{
						@namespace = text2
					};
					break;
				case '@':
					if (!text2.StartsWith("P:"))
					{
						continue;
					}
					val2 = new ImportTarget((ImportTargetKind)1)
					{
						@namespace = text2.Substring(2)
					};
					break;
				}
				if (val2 != null)
				{
					val.Targets.Add(val2);
				}
			}
			return val;
		}

		private void ReadSequencePoints(PdbFunction function, MethodDebugInformation info)
		{
			if (function.lines != null)
			{
				info.sequence_points = new Collection<SequencePoint>();
				PdbLines[] lines = function.lines;
				foreach (PdbLines lines2 in lines)
				{
					ReadLines(lines2, info);
				}
			}
		}

		private void ReadLines(PdbLines lines, MethodDebugInformation info)
		{
			Document document = GetDocument(lines.file);
			PdbLine[] lines2 = lines.lines;
			for (int i = 0; i < lines2.Length; i++)
			{
				ReadLine(lines2[i], document, info);
			}
		}

		private static void ReadLine(PdbLine line, Document document, MethodDebugInformation info)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			SequencePoint val = new SequencePoint((int)line.offset, document);
			val.StartLine = (int)line.lineBegin;
			val.StartColumn = line.colBegin;
			val.EndLine = (int)line.lineEnd;
			val.EndColumn = line.colEnd;
			info.sequence_points.Add(val);
		}

		private Document GetDocument(PdbSource source)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			string name = source.name;
			if (documents.TryGetValue(name, out var value))
			{
				return value;
			}
			value = new Document(name)
			{
				Language = PdbGuidMapping.ToLanguage(source.language),
				LanguageVendor = PdbGuidMapping.ToVendor(source.vendor),
				Type = PdbGuidMapping.ToType(source.doctype)
			};
			documents.Add(name, value);
			return value;
		}

		public void Dispose()
		{
			//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)
			pdb_file.Dispose();
		}
	}
	public class NativePdbWriter : ISymbolWriter, IDisposable
	{
		private readonly ModuleDefinition module;

		private readonly MetadataBuilder metadata;

		private readonly SymWriter writer;

		private readonly Dictionary<string, SymDocumentWriter> documents;

		private readonly Dictionary<ImportDebugInformation, MetadataToken> import_info_to_parent;

		internal NativePdbWriter(ModuleDefinition module, SymWriter writer)
		{
			this.module = module;
			metadata = module.metadata_builder;
			this.writer = writer;
			documents = new Dictionary<string, SymDocumentWriter>();
			import_info_to_parent = new Dictionary<ImportDebugInformation, MetadataToken>();
		}

		public ISymbolReaderProvider GetReaderProvider()
		{
			return (ISymbolReaderProvider)(object)new NativePdbReaderProvider();
		}

		public ImageDebugHeader GetDebugHeader()
		{
			//IL_0020: 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: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			ImageDebugDirectory idd;
			byte[] debugInfo = writer.GetDebugInfo(out idd);
			idd.TimeDateStamp = (int)module.timestamp;
			return new ImageDebugHeader(new ImageDebugHeaderEntry(idd, debugInfo));
		}

		public void Write(MethodDebugInformation info)
		{
			//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_005c: 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)
			MetadataToken metadataToken = ((MemberReference)info.method).MetadataToken;
			int methodToken = ((MetadataToken)(ref metadataToken)).ToInt32();
			if (info.HasSequencePoints || info.scope != null || ((DebugInformation)info).HasCustomDebugInformations || info.StateMachineKickOffMethod != null)
			{
				writer.OpenMethod(methodToken);
				if (!Mixin.IsNullOrEmpty<SequencePoint>(info.sequence_points))
				{
					DefineSequencePoints(info.sequence_points);
				}
				MetadataToken import_parent = default(MetadataToken);
				if (info.scope != null)
				{
					DefineScope(info.scope, info, out import_parent);
				}
				DefineCustomMetadata(info, import_parent);
				writer.CloseMethod();
			}
		}

		private void DefineCustomMetadata(MethodDebugInformation info, MetadataToken import_parent)
		{
			//IL_0016: 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_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			CustomMetadataWriter customMetadataWriter = new CustomMetadataWriter(writer);
			if (((MetadataToken)(ref import_parent)).RID != 0)
			{
				customMetadataWriter.WriteForwardInfo(import_parent);
			}
			else if (info.scope != null && info.scope.Import != null && info.scope.Import.HasTargets)
			{
				customMetadataWriter.WriteUsingInfo(info.scope.Import);
			}
			if (info.Method.HasCustomAttributes)
			{
				Enumerator<CustomAttribute> enumerator = info.Method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						TypeReference attributeType = current.AttributeType;
						if (Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "IteratorStateMachineAttribute") || Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute"))
						{
							CustomAttributeArgument val = current.ConstructorArguments[0];
							object value = ((CustomAttributeArgument)(ref val)).Value;
							TypeReference val2 = (TypeReference)((value is TypeReference) ? value : null);
							if (val2 != null)
							{
								customMetadataWriter.WriteForwardIterator(val2);
							}
						}
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			}
			if (((DebugInformation)info).HasCustomDebugInformations)
			{
				CustomDebugInformation? obj = ((IEnumerable<CustomDebugInformation>)((DebugInformation)info).CustomDebugInformations).FirstOrDefault((Func<CustomDebugInformation, bool>)((CustomDebugInformation cdi) => (int)cdi.Kind == 1));
				StateMachineScopeDebugInformation val3 = (StateMachineScopeDebugInformation)(object)((obj is StateMachineScopeDebugInformation) ? obj : null);
				if (val3 != null)
				{
					customMetadataWriter.WriteIteratorScopes(val3, info);
				}
			}
			customMetadataWriter.WriteCustomMetadata();
			DefineAsyncCustomMetadata(info);
		}

		private void DefineAsyncCustomMetadata(MethodDebugInformation info)
		{
			//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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_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_00d0: 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)
			if (!((DebugInformation)info).HasCustomDebugInformations)
			{
				return;
			}
			Enumerator<CustomDebugInformation> enumerator = ((DebugInformation)info).CustomDebugInformations.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomDebugInformation current = enumerator.Current;
					AsyncMethodBodyDebugInformation val = (AsyncMethodBodyDebugInformation)(object)((current is AsyncMethodBodyDebugInformation) ? current : null);
					if (val == null)
					{
						continue;
					}
					using MemoryStream memoryStream = new MemoryStream();
					BinaryStreamWriter val2 = new BinaryStreamWriter((Stream)memoryStream);
					int num;
					MetadataToken metadataToken;
					if (info.StateMachineKickOffMethod == null)
					{
						num = 0;
					}
					else
					{
						metadataToken = ((MemberReference)info.StateMachineKickOffMethod).MetadataToken;
						num = (int)((MetadataToken)(ref metadataToken)).ToUInt32();
					}
					val2.WriteUInt32((uint)num);
					InstructionOffset val3 = val.CatchHandler;
					val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset);
					val2.WriteUInt32((uint)val.Resumes.Count);
					for (int i = 0; i < val.Resumes.Count; i++)
					{
						val3 = val.Yields[i];
						val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset);
						metadataToken = ((MemberReference)val.resume_methods[i]).MetadataToken;
						val2.WriteUInt32(((MetadataToken)(ref metadataToken)).ToUInt32());
						val3 = val.Resumes[i];
						val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset);
					}
					writer.DefineCustomMetadata("asyncMethodInfo", memoryStream.ToArray());
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		private void DefineScope(ScopeDebugInformation scope, MethodDebugInformation info, out MetadataToken import_parent)
		{
			//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_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_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_0038: 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_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_00a8: 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_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Invalid comparison between Unknown and I4
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Invalid comparison between Unknown and I4
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Invalid comparison between Unknown and I4
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Invalid comparison between Unknown and I4
			InstructionOffset val = scope.Start;
			int offset = ((InstructionOffset)(ref val)).Offset;
			val = scope.End;
			int num;
			if (!((InstructionOffset)(ref val)).IsEndOfMethod)
			{
				val = scope.End;
				num = ((InstructionOffset)(ref val)).Offset;
			}
			else
			{
				num = info.code_size;
			}
			int num2 = num;
			import_parent = new MetadataToken(0u);
			writer.OpenScope(offset);
			if (scope.Import != null && scope.Import.HasTargets && !import_info_to_parent.TryGetValue(info.scope.Import, out import_parent))
			{
				Enumerator<ImportTarget> enumerator = scope.Import.Targets.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						ImportTarget current = enumerator.Current;
						ImportTargetKind kind = current.Kind;
						if ((int)kind <= 3)
						{
							if ((int)kind != 1)
							{
								if ((int)kind == 3)
								{
									writer.UsingNamespace("T" + TypeParser.ToParseable(current.type, true));
								}
							}
							else
							{
								writer.UsingNamespace("U" + current.@namespace);
							}
						}
						else if ((int)kind != 7)
						{
							if ((int)kind == 9)
							{
								writer.UsingNamespace("A" + current.Alias + " T" + TypeParser.ToParseable(current.type, true));
							}
						}
						else
						{
							writer.UsingNamespace("A" + current.Alias + " U" + current.@namespace);
						}
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				import_info_to_parent.Add(info.scope.Import, ((MemberReference)info.method).MetadataToken);
			}
			int local_var_token = ((MetadataToken)(ref info.local_var_token)).ToInt32();
			if (!Mixin.IsNullOrEmpty<VariableDebugInformation>(scope.variables))
			{
				for (int i = 0; i < scope.variables.Count; i++)
				{
					VariableDebugInformation variable = scope.variables[i];
					DefineLocalVariable(variable, local_var_token, offset, num2);
				}
			}
			if (!Mixin.IsNullOrEmpty<ConstantDebugInformation>(scope.constants))
			{
				for (int j = 0; j < scope.constants.Count; j++)
				{
					ConstantDebugInformation constant = scope.constants[j];
					DefineConstant(constant);
				}
			}
			if (!Mixin.IsNullOrEmpty<ScopeDebugInformation>(scope.scopes))
			{
				for (int k = 0; k < scope.scopes.Count; k++)
				{
					DefineScope(scope.scopes[k], info, out var _);
				}
			}
			writer.CloseScope(num2);
		}

		private void DefineSequencePoints(Collection<SequencePoint> sequence_points)
		{
			for (int i = 0; i < sequence_points.Count; i++)
			{
				SequencePoint val = sequence_points[i];
				writer.DefineSequencePoints(GetDocument(val.Document), new int[1] { val.Offset }, new int[1] { val.StartLine }, new int[1] { val.StartColumn }, new int[1] { val.EndLine }, new int[1] { val.EndColumn });
			}
		}

		private void DefineLocalVariable(VariableDebugInformation variable, int local_var_token, int start_offset, int end_offset)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			writer.DefineLocalVariable2(variable.Name, variable.Attributes, local_var_token, variable.Index, 0, 0, start_offset, end_offset);
		}

		private void DefineConstant(ConstantDebugInformation constant)
		{
			uint num = metadata.AddStandAloneSignature(metadata.GetConstantTypeBlobIndex(constant.ConstantType));
			MetadataToken val = default(MetadataToken);
			((MetadataToken)(ref val))..ctor((TokenType)285212672, num);
			writer.DefineConstant2(constant.Name, constant.Value, ((MetadataToken)(ref val)).ToInt32());
		}

		private SymDocumentWriter GetDocument(Document document)
		{
			if (document == null)
			{
				return null;
			}
			if (documents.TryGetValue(document.Url, out var value))
			{
				return value;
			}
			value = writer.DefineDocument(document.Url, document.LanguageGuid, document.LanguageVendorGuid, document.TypeGuid);
			documents[document.Url] = value;
			return value;
		}

		public void Dispose()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			MethodDefinition entryPoint = module.EntryPoint;
			if (entryPoint != null)
			{
				SymWriter symWriter = writer;
				MetadataToken metadataToken = ((MemberReference)entryPoint).MetadataToken;
				symWriter.SetUserEntryPoint(((MetadataToken)(ref metadataToken)).ToInt32());
			}
			writer.Close();
		}
	}
	internal enum CustomMetadataType : byte
	{
		UsingInfo = 0,
		ForwardInfo = 1,
		IteratorScopes = 3,
		ForwardIterator = 4
	}
	internal class CustomMetadataWriter : IDisposable
	{
		private readonly SymWriter sym_writer;

		private readonly MemoryStream stream;

		private readonly BinaryStreamWriter writer;

		private int count;

		private const byte version = 4;

		public CustomMetadataWriter(SymWriter sym_writer)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			this.sym_writer = sym_writer;
			stream = new MemoryStream();
			writer = new BinaryStreamWriter((Stream)stream);
			writer.WriteByte((byte)4);
			writer.WriteByte((byte)0);
			writer.Align(4);
		}

		public void WriteUsingInfo(ImportDebugInformation import_info)
		{
			Write(CustomMetadataType.UsingInfo, delegate
			{
				writer.WriteUInt16((ushort)1);
				writer.WriteUInt16((ushort)import_info.Targets.Count);
			});
		}

		public void WriteForwardInfo(MetadataToken import_parent)
		{
			//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)
			Write(CustomMetadataType.ForwardInfo, delegate
			{
				writer.WriteUInt32(((MetadataToken)(ref import_parent)).ToUInt32());
			});
		}

		public void WriteIteratorScopes(StateMachineScopeDebugInformation state_machine, MethodDebugInformation debug_info)
		{
			Write(CustomMetadataType.IteratorScopes, delegate
			{
				//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_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_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_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				Collection<StateMachineScope> scopes = state_machine.Scopes;
				writer.WriteInt32(scopes.Count);
				Enumerator<StateMachineScope> enumerator = scopes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						StateMachineScope current = enumerator.Current;
						InstructionOffset val = current.Start;
						int offset = ((InstructionOffset)(ref val)).Offset;
						val = current.End;
						int num;
						if (!((InstructionOffset)(ref val)).IsEndOfMethod)
						{
							val = current.End;
							num = ((InstructionOffset)(ref val)).Offset;
						}
						else
						{
							num = debug_info.code_size;
						}
						int num2 = num;
						writer.WriteInt32(offset);
						writer.WriteInt32(num2 - 1);
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			});
		}

		public void WriteForwardIterator(TypeReference type)
		{
			Write(CustomMetadataType.ForwardIterator, delegate
			{
				writer.WriteBytes(Encoding.Unicode.GetBytes(((MemberReference)type).Name));
			});
		}

		private void Write(CustomMetadataType type, Action write)
		{
			count++;
			writer.WriteByte((byte)4);
			writer.WriteByte((byte)type);
			writer.Align(4);
			int position = writer.Position;
			writer.WriteUInt32(0u);
			write();
			writer.Align(4);
			int position2 = writer.Position;
			int num = position2 - position + 4;
			writer.Position = position;
			writer.WriteInt32(num);
			writer.Position = position2;
		}

		public void WriteCustomMetadata()
		{
			if (count != 0)
			{
				((BinaryWriter)(object)writer).BaseStream.Position = 1L;
				writer.WriteByte((byte)count);
				((BinaryWriter)(object)writer).Flush();
				sym_writer.DefineCustomMetadata("MD2", stream.ToArray());
			}
		}

		public void Dispose()
		{
			stream.Dispose();
		}
	}
	public sealed class NativePdbReaderProvider : ISymbolReaderProvider
	{
		public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolReader)(object)new NativePdbReader(Disposable.Owned<Stream>((Stream)File.OpenRead(Mixin.GetPdbFileName(fileName))));
		}

		public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			return (ISymbolReader)(object)new NativePdbReader(Disposable.NotOwned<Stream>(symbolStream));
		}
	}
	public sealed class PdbReaderProvider : ISymbolReaderProvider
	{
		public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
		{
			//IL_0048: 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)
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			if (module.HasDebugHeader && Mixin.GetEmbeddedPortablePdbEntry(module.GetDebugHeader()) != null)
			{
				return new EmbeddedPortablePdbReaderProvider().GetSymbolReader(module, fileName);
			}
			if (!Mixin.IsPortablePdb(Mixin.GetPdbFileName(fileName)))
			{
				return new NativePdbReaderProvider().GetSymbolReader(module, fileName);
			}
			return new PortablePdbReaderProvider().GetSymbolReader(module, fileName);
		}

		public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			Mixin.CheckReadSeek(symbolStream);
			if (!Mixin.IsPortablePdb(symbolStream))
			{
				return new NativePdbReaderProvider().GetSymbolReader(module, symbolStream);
			}
			return new PortablePdbReaderProvider().GetSymbolReader(module, symbolStream);
		}
	}
	public sealed class NativePdbWriterProvider : ISymbolWriterProvider
	{
		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName)
		{
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolWriter)(object)new NativePdbWriter(module, CreateWriter(module, Mixin.GetPdbFileName(fileName)));
		}

		private static SymWriter CreateWriter(ModuleDefinition module, string pdb)
		{
			SymWriter symWriter = new SymWriter();
			if (File.Exists(pdb))
			{
				File.Delete(pdb);
			}
			symWriter.Initialize(new ModuleMetadata(module), pdb, fFullBuild: true);
			return symWriter;
		}

		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream)
		{
			throw new NotImplementedException();
		}
	}
	public sealed class PdbWriterProvider : ISymbolWriterProvider
	{
		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			if (HasPortablePdbSymbols(module))
			{
				return new PortablePdbWriterProvider().GetSymbolWriter(module, fileName);
			}
			return new NativePdbWriterProvider().GetSymbolWriter(module, fileName);
		}

		private static bool HasPortablePdbSymbols(ModuleDefinition module)
		{
			if (module.symbol_reader != null)
			{
				return module.symbol_reader is PortablePdbReader;
			}
			return false;
		}

		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			Mixin.CheckReadSeek(symbolStream);
			if (HasPortablePdbSymbols(module))
			{
				return new PortablePdbWriterProvider().GetSymbolWriter(module, symbolStream);
			}
			return new NativePdbWriterProvider().GetSymbolWriter(module, symbolStream);
		}
	}
	internal class SymDocumentWriter
	{
		private readonly ISymUnmanagedDocumentWriter m_unmanagedDocumentWriter;

		public SymDocumentWriter(ISymUnmanagedDocumentWriter unmanagedDocumentWriter)
		{
			m_unmanagedDocumentWriter = unmanagedDocumentWriter;
		}

		public ISymUnmanagedDocumentWriter GetUnmanaged()
		{
			return m_unmanagedDocumentWriter;
		}
	}
	internal class SymWriter
	{
		private static Guid s_symUnmangedWriterIID = new Guid("0b97726e-9e6d-4f05-9a26-424022093caa");

		private static Guid s_CorSymWriter_SxS_ClassID = new Guid("108296c1-281e-11d3-bd22-0000f80849bd");

		private readonly ISymUnmanagedWriter2 m_writer;

		private readonly Collection<ISymUnmanagedDocumentWriter> documents;

		[DllImport("ole32.dll")]
		private static extern int CoCreateInstance([In] ref Guid rclsid, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, [In] uint dwClsContext, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppv);

		public SymWriter()
		{
			CoCreateInstance(ref s_CorSymWriter_SxS_ClassID, null, 1u, ref s_symUnmangedWriterIID, out var ppv);
			m_writer = (ISymUnmanagedWriter2)ppv;
			documents = new Collection<ISymUnmanagedDocumentWriter>();
		}

		public byte[] GetDebugInfo(out ImageDebugDirectory idd)
		{
			m_writer.GetDebugInfo(out idd, 0, out var pcData, null);
			byte[] array = new byte[pcData];
			m_writer.GetDebugInfo(out idd, pcData, out pcData, array);
			return array;
		}

		public void DefineLocalVariable2(string name, VariableAttributes attributes, int sigToken, int addr1, int addr2, int addr3, int startOffset, int endOffset)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected I4, but got Unknown
			m_writer.DefineLocalVariable2(name, (int)attributes, sigToken, 1, addr1, addr2, addr3, startOffset, endOffset);
		}

		public void DefineConstant2(string name, object value, int sigToken)
		{
			if (value == null)
			{
				m_writer.DefineConstant2(name, 0, sigToken);
			}
			else
			{
				m_writer.DefineConstant2(name, value, sigToken);
			}
		}

		public void Close()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			m_writer.Close();
			Marshal.ReleaseComObject(m_writer);
			Enumerator<ISymUnmanagedDocumentWriter> enumerator = documents.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					Marshal.ReleaseComObject(enumerator.Current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public void CloseMethod()
		{
			m_writer.CloseMethod();
		}

		public void CloseNamespace()
		{
			m_writer.CloseNamespace();
		}

		public void CloseScope(int endOffset)
		{
			m_writer.CloseScope(endOffset);
		}

		public SymDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType)
		{
			m_writer.DefineDocument(url, ref language, ref languageVendor, ref documentType, out var pRetVal);
			documents.Add(pRetVal);
			return new SymDocumentWriter(pRetVal);
		}

		public void DefineSequencePoints(SymDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns)
		{
			m_writer.DefineSequencePoints(document.GetUnmanaged(), offsets.Length, offsets, lines, columns, endLines, endColumns);
		}

		public void Initialize(object emitter, string filename, bool fFullBuild)
		{
			m_writer.Initialize(emitter, filename, null, fFullBuild);
		}

		public void SetUserEntryPoint(int methodToken)
		{
			m_writer.SetUserEntryPoint(methodToken);
		}

		public void OpenMethod(int methodToken)
		{
			m_writer.OpenMethod(methodToken);
		}

		public void OpenNamespace(string name)
		{
			m_writer.OpenNamespace(name);
		}

		public int OpenScope(int startOffset)
		{
			m_writer.OpenScope(startOffset, out var pRetVal);
			return pRetVal;
		}

		public void UsingNamespace(string fullName)
		{
			m_writer.UsingNamespace(fullName);
		}

		public void DefineCustomMetadata(string name, byte[] metadata)
		{
			GCHandle gCHandle = GCHandle.Alloc(metadata, GCHandleType.Pinned);
			m_writer.SetSymAttribute(0u, name, (uint)metadata.Length, gCHandle.AddrOfPinnedObject());
			gCHandle.Free();
		}
	}
}
namespace Microsoft.Cci
{
	public interface ILocalScope
	{
		uint Offset { get; }

		uint Length { get; }
	}
	public interface INamespaceScope
	{
		IEnumerable<IUsedNamespace> UsedNamespaces { get; }
	}
	public interface IUsedNamespace
	{
		IName Alias { get; }

		IName NamespaceName { get; }
	}
	public interface IName
	{
		int UniqueKey { get; }

		int UniqueKeyIgnoringCase { get; }

		string Value { get; }
	}
	internal sealed class PdbIteratorScope : ILocalScope
	{
		private uint offset;

		private uint length;

		public uint Offset => offset;

		public uint Length => length;

		internal PdbIteratorScope(uint offset, uint length)
		{
			this.offset = offset;
			this.length = length;
		}
	}
}
namespace Microsoft.Cci.Pdb
{
	internal class BitAccess
	{
		private byte[] buffer;

		private int offset;

		internal byte[] Buffer => buffer;

		internal int Position
		{
			get
			{
				return offset;
			}
			set
			{
				offset = value;
			}
		}

		internal BitAccess(int capacity)
		{
			buffer = new byte[capacity];
		}

		internal void FillBuffer(Stream stream, int capacity)
		{
			MinCapacity(capacity);
			stream.Read(buffer, 0, capacity);
			offset = 0;
		}

		internal void Append(Stream stream, int count)
		{
			int num = offset + count;
			if (buffer.Length < num)
			{
				byte[] destinationArray = new byte[num];
				Array.Copy(buffer, destinationArray, buffer.Length);
				buffer = destinationArray;
			}
			stream.Read(buffer, offset, count);
			offset += count;
		}

		internal void MinCapacity(int capacity)
		{
			if (buffer.Length < capacity)
			{
				buffer = new byte[capacity];
			}
			offset = 0;
		}

		internal void Align(int alignment)
		{
			while (offset % alignment != 0)
			{
				offset++;
			}
		}

		internal void ReadInt16(out short value)
		{
			value = (short)((buffer[offset] & 0xFF) | (buffer[offset + 1] << 8));
			offset += 2;
		}

		internal void ReadInt8(out sbyte value)
		{
			value = (sbyte)buffer[offset];
			offset++;
		}

		internal void ReadInt32(out int value)
		{
			value = (buffer[offset] & 0xFF) | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24);
			offset += 4;
		}

		internal void ReadInt64(out long value)
		{
			value = ((long)buffer[offset] & 0xFFL) | (long)((ulong)buffer[offset + 1] << 8) | (long)((ulong)buffer[offset + 2] << 16) | (long)((ulong)buffer[offset + 3] << 24) | (long)((ulong)buffer[offset + 4] << 32) | (long)((ulong)buffer[offset + 5] << 40) | (long)((ulong)buffer[offset + 6] << 48) | (long)((ulong)buffer[offset + 7] << 56);
			offset += 8;
		}

		internal void ReadUInt16(out ushort value)
		{
			value = (ushort)((buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8));
			offset += 2;
		}

		internal void ReadUInt8(out byte value)
		{
			value = (byte)(buffer[offset] & 0xFFu);
			offset++;
		}

		internal void ReadUInt32(out uint value)
		{
			value = (buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8) | (uint)(buffer[offset + 2] << 16) | (uint)(buffer[offset + 3] << 24);
			offset += 4;
		}

		internal void ReadUInt64(out ulong value)
		{
			value = ((ulong)buffer[offset] & 0xFFuL) | ((ulong)buffer[offset + 1] << 8) | ((ulong)buffer[offset + 2] << 16) | ((ulong)buffer[offset + 3] << 24) | ((ulong)buffer[offset + 4] << 32) | ((ulong)buffer[offset + 5] << 40) | ((ulong)buffer[offset + 6] << 48) | ((ulong)buffer[offset + 7] << 56);
			offset += 8;
		}

		internal void ReadInt32(int[] values)
		{
			for (int i = 0; i < values.Length; i++)
			{
				ReadInt32(out values[i]);
			}
		}

		internal void ReadUInt32(uint[] values)
		{
			for (int i = 0; i < values.Length; i++)
			{
				ReadUInt32(out values[i]);
			}
		}

		internal void ReadBytes(byte[] bytes)
		{
			for (int i = 0; i < bytes.Length; i++)
			{
				bytes[i] = buffer[offset++];
			}
		}

		internal float ReadFloat()
		{
			float result = BitConverter.ToSingle(buffer, offset);
			offset += 4;
			return result;
		}

		internal double ReadDouble()
		{
			double result = BitConverter.ToDouble(buffer, offset);
			offset += 8;
			return result;
		}

		internal decimal ReadDecimal()
		{
			int[] array = new int[4];
			ReadInt32(array);
			return new decimal(array[2], array[3], array[1], array[0] < 0, (byte)((array[0] & 0xFF0000) >> 16));
		}

		internal void ReadBString(out string value)
		{
			ReadUInt16(out var value2);
			value = Encoding.UTF8.GetString(buffer, offset, value2);
			offset += value2;
		}

		internal string ReadBString(int len)
		{
			string @string = Encoding.UTF8.GetString(buffer, offset, len);
			offset += len;
			return @string;
		}

		internal void ReadCString(out string value)
		{
			int i;
			for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++)
			{
			}
			value = Encoding.UTF8.GetString(buffer, offset, i);
			offset += i + 1;
		}

		internal void SkipCString(out string value)
		{
			int i;
			for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++)
			{
			}
			offset += i + 1;
			value = null;
		}

		internal void ReadGuid(out Guid guid)
		{
			ReadUInt32(out var value);
			ReadUInt16(out var value2);
			ReadUInt16(out var value3);
			ReadUInt8(out var value4);
			ReadUInt8(out var value5);
			ReadUInt8(out var value6);
			ReadUInt8(out var value7);
			ReadUInt8(out var value8);
			ReadUInt8(out var value9);
			ReadUInt8(out var value10);
			ReadUInt8(out var value11);
			guid = new Guid(value, value2, value3, value4, value5, value6, value7, value8, value9, value10, value11);
		}

		internal string ReadString()
		{
			int i;
			for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i += 2)
			{
			}
			string @string = Encoding.Unicode.GetString(buffer, offset, i);
			offset += i + 2;
			return @string;
		}
	}
	internal struct BitSet
	{
		private int size;

		private uint[] words;

		internal bool IsEmpty => size == 0;

		internal BitSet(BitAccess bits)
		{
			bits.ReadInt32(out size);
			words = new uint[size];
			bits.ReadUInt32(words);
		}

		internal bool IsSet(int index)
		{
			int num = index / 32;
			if (num >= size)
			{
				return false;
			}
			return (words[num] & GetBit(index)) != 0;
		}

		private static uint GetBit(int index)
		{
			return (uint)(1 << index % 32);
		}
	}
	internal struct FLOAT10
	{
		internal byte Data_0;

		internal byte Data_1;

		internal byte Data_2;

		internal byte Data_3;

		internal byte Data_4;

		internal byte Data_5;

		internal byte Data_6;

		internal byte Data_7;

		internal byte Data_8;

		internal byte Data_9;
	}
	internal enum CV_SIGNATURE
	{
		C6 = 0,
		C7 = 1,
		C11 = 2,
		C13 = 4,
		RESERVERD = 5
	}
	internal enum CV_prmode
	{
		CV_TM_DIRECT = 0,
		CV_TM_NPTR32 = 4,
		CV_TM_NPTR64 = 6,
		CV_TM_NPTR128 = 7
	}
	internal enum CV_type
	{
		CV_SPECIAL = 0,
		CV_SIGNED = 1,
		CV_UNSIGNED = 2,
		CV_BOOLEAN = 3,
		CV_REAL = 4,
		CV_COMPLEX = 5,
		CV_SPECIAL2 = 6,
		CV_INT = 7,
		CV_CVRESERVED = 15
	}
	internal enum CV_special
	{
		CV_SP_NOTYPE,
		CV_SP_ABS,
		CV_SP_SEGMENT,
		CV_SP_VOID,
		CV_SP_CURRENCY,
		CV_SP_NBASICSTR,
		CV_SP_FBASICSTR,
		CV_SP_NOTTRANS,
		CV_SP_HRESULT
	}
	internal enum CV_special2
	{
		CV_S2_BIT,
		CV_S2_PASCHAR
	}
	internal enum CV_integral
	{
		CV_IN_1BYTE,
		CV_IN_2BYTE,
		CV_IN_4BYTE,
		CV_IN_8BYTE,
		CV_IN_16BYTE
	}
	internal enum CV_real
	{
		CV_RC_REAL32,
		CV_RC_REAL64,
		CV_RC_REAL80,
		CV_RC_REAL128
	}
	internal enum CV_int
	{
		CV_RI_CHAR = 0,
		CV_RI_INT1 = 0,
		CV_RI_WCHAR = 1,
		CV_RI_UINT1 = 1,
		CV_RI_INT2 = 2,
		CV_RI_UINT2 = 3,
		CV_RI_INT4 = 4,
		CV_RI_UINT4 = 5,
		CV_RI_INT8 = 6,
		CV_RI_UINT8 = 7,
		CV_RI_INT16 = 8,
		CV_RI_UINT16 = 9
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	internal struct CV_PRIMITIVE_TYPE
	{
		private const uint CV_MMASK = 1792u;

		private const uint CV_TMASK = 240u;

		private const uint CV_SMASK = 15u;

		private const int CV_MSHIFT = 8;

		private const int CV_TSHIFT = 4;

		private const int CV_SSHIFT = 0;

		private const uint CV_FIRST_NONPRIM = 4096u;
	}
	internal enum TYPE_ENUM
	{
		T_NOTYPE = 0,
		T_ABS = 1,
		T_SEGMENT = 2,
		T_VOID = 3,
		T_HRESULT = 8,
		T_32PHRESULT = 1032,
		T_64PHRESULT = 1544,
		T_PVOID = 259,
		T_PFVOID = 515,
		T_PHVOID = 771,
		T_32PVOID = 1027,
		T_64PVOID = 1539,
		T_CURRENCY = 4,
		T_NOTTRANS = 7,
		T_BIT = 96,
		T_PASCHAR = 97,
		T_CHAR = 16,
		T_32PCHAR = 1040,
		T_64PCHAR = 1552,
		T_UCHAR = 32,
		T_32PUCHAR = 1056,
		T_64PUCHAR = 1568,
		T_RCHAR = 112,
		T_32PRCHAR = 1136,
		T_64PRCHAR = 1648,
		T_WCHAR = 113,
		T_32PWCHAR = 1137,
		T_64PWCHAR = 1649,
		T_INT1 = 104,
		T_32PINT1 = 1128,
		T_64PINT1 = 1640,
		T_UINT1 = 105,
		T_32PUINT1 = 1129,
		T_64PUINT1 = 1641,
		T_SHORT = 17,
		T_32PSHORT = 1041,
		T_64PSHORT = 1553,
		T_USHORT = 33,
		T_32PUSHORT = 1057,
		T_64PUSHORT = 1569,
		T_INT2 = 114,
		T_32PINT2 = 1138,
		T_64PINT2 = 1650,
		T_UINT2 = 115,
		T_32PUINT2 = 1139,
		T_64PUINT2 = 1651,
		T_LONG = 18,
		T_ULONG = 34,
		T_32PLONG = 1042,
		T_32PULONG = 1058,
		T_64PLONG = 1554,
		T_64PULONG = 1570,
		T_INT4 = 116,
		T_32PINT4 = 1140,
		T_64PINT4 = 1652,
		T_UINT4 = 117,
		T_32PUINT4 = 1141,
		T_64PUINT4 = 1653,
		T_QUAD = 19,
		T_32PQUAD = 1043,
		T_64PQUAD = 1555,
		T_UQUAD = 35,
		T_32PUQUAD = 1059,
		T_64PUQUAD = 1571,
		T_INT8 = 118,
		T_32PINT8 = 1142,
		T_64PINT8 = 1654,
		T_UINT8 = 119,
		T_32PUINT8 = 1143,
		T_64PUINT8 = 1655,
		T_OCT = 20,
		T_32POCT = 1044,
		T_64POCT = 1556,
		T_UOCT = 36,
		T_32PUOCT = 1060,
		T_64PUOCT = 1572,
		T_INT16 = 120,
		T_32PINT16 = 1144,
		T_64PINT16 = 1656,
		T_UINT16 = 121,
		T_32PUINT16 = 1145,
		T_64PUINT16 = 1657,
		T_REAL32 = 64,
		T_32PREAL32 = 1088,
		T_64PREAL32 = 1600,
		T_REAL64 = 65,
		T_32PREAL64 = 1089,
		T_64PREAL64 = 1601,
		T_REAL80 = 66,
		T_32PREAL80 = 1090,
		T_64PREAL80 = 1602,
		T_REAL128 = 67,
		T_32PREAL128 = 1091,
		T_64PREAL128 = 1603,
		T_CPLX32 = 80,
		T_32PCPLX32 = 1104,
		T_64PCPLX32 = 1616,
		T_CPLX64 = 81,
		T_32PCPLX64 = 1105,
		T_64PCPLX64 = 1617,
		T_CPLX80 = 82,
		T_32PCPLX80 = 1106,
		T_64PCPLX80 = 1618,
		T_CPLX128 = 83,
		T_32PCPLX128 = 1107,
		T_64PCPLX128 = 1619,
		T_BOOL08 = 48,
		T_32PBOOL08 = 1072,
		T_64PBOOL08 = 1584,
		T_BOOL16 = 49,
		T_32PBOOL16 = 1073,
		T_64PBOOL16 = 1585,
		T_BOOL32 = 50,
		T_32PBOOL32 = 1074,
		T_64PBOOL32 = 1586,
		T_BOOL64 = 51,
		T_32PBOOL64 = 1075,
		T_64PBOOL64 = 1587
	}
	internal enum LEAF
	{
		LF_VTSHAPE = 10,
		LF_COBOL1 = 12,
		LF_LABEL = 14,
		LF_NULL = 15,
		LF_NOTTRAN = 16,
		LF_ENDPRECOMP = 20,
		LF_TYPESERVER_ST = 22,
		LF_LIST = 515,
		LF_REFSYM = 524,
		LF_ENUMERATE_ST = 1027,
		LF_TI16_MAX = 4096,
		LF_MODIFIER = 4097,
		LF_POINTER = 4098,
		LF_ARRAY_ST = 4099,
		LF_CLASS_ST = 4100,
		LF_STRUCTURE_ST = 4101,
		LF_UNION_ST = 4102,
		LF_ENUM_ST = 4103,
		LF_PROCEDURE = 4104,
		LF_MFUNCTION = 4105,
		LF_COBOL0 = 4106,
		LF_BARRAY = 4107,
		LF_DIMARRAY_ST = 4108,
		LF_VFTPATH = 4109,
		LF_PRECOMP_ST = 4110,
		LF_OEM = 4111,
		LF_ALIAS_ST = 4112,
		LF_OEM2 = 4113,
		LF_SKIP = 4608,
		LF_ARGLIST = 4609,
		LF_DEFARG_ST = 4610,
		LF_FIELDLIST = 4611,
		LF_DERIVED = 4612,
		LF_BITFIELD = 4613,
		LF_METHODLIST = 4614,
		LF_DIMCONU = 4615,
		LF_DIMCONLU = 4616,
		LF_DIMVARU = 4617,
		LF_DIMVARLU = 4618,
		LF_BCLASS = 5120,
		LF_VBCLASS = 5121,
		LF_IVBCLASS = 5122,
		LF_FRIENDFCN_ST = 5123,
		LF_INDEX = 5124,
		LF_MEMBER_ST = 5125,
		LF_STMEMBER_ST = 5126,
		LF_METHOD_ST = 5127,
		LF_NESTTYPE_ST = 5128,
		LF_VFUNCTAB = 5129,
		LF_FRIENDCLS = 5130,
		LF_ONEMETHOD_ST = 5131,
		LF_VFUNCOFF = 5132,
		LF_NESTTYPEEX_ST = 5133,
		LF_MEMBERMODIFY_ST = 5134,
		LF_MANAGED_ST = 5135,
		LF_ST_MAX = 5376,
		LF_TYPESERVER = 5377,
		LF_ENUMERATE = 5378,
		LF_ARRAY = 5379,
		LF_CLASS = 5380,
		LF_STRUCTURE = 5381,
		LF_UNION = 5382,
		LF_ENUM = 5383,
		LF_DIMARRAY = 5384,
		LF_PRECOMP = 5385,
		LF_ALIAS = 5386,
		LF_DEFARG = 5387,
		LF_FRIENDFCN = 5388,
		LF_MEMBER = 5389,
		LF_STMEMBER = 5390,
		LF_METHOD = 5391,
		LF_NESTTYPE = 5392,
		LF_ONEMETHOD = 5393,
		LF_NESTTYPEEX = 5394,
		LF_MEMBERMODIFY = 5395,
		LF_MANAGED = 5396,
		LF_TYPESERVER2 = 5397,
		LF_NUMERIC = 32768,
		LF_CHAR = 32768,
		LF_SHORT = 32769,
		LF_USHORT = 32770,
		LF_LONG = 32771,
		LF_ULONG = 32772,
		LF_REAL32 = 32773,
		LF_REAL64 = 32774,
		LF_REAL80 = 32775,
		LF_REAL128 = 32776,
		LF_QUADWORD = 32777,
		LF_UQUADWORD = 32778,
		LF_COMPLEX32 = 32780,
		LF_COMPLEX64 = 32781,
		LF_COMPLEX80 = 32782,
		LF_COMPLEX128 = 32783,
		LF_VARSTRING = 32784,
		LF_OCTWORD = 32791,
		LF_UOCTWORD = 32792,
		LF_DECIMAL = 32793,
		LF_DATE = 32794,
		LF_UTF8STRING = 32795,
		LF_PAD0 = 240,
		LF_PAD1 = 241,
		LF_PAD2 = 242,
		LF_PAD3 = 243,
		LF_PAD4 = 244,
		LF_PAD5 = 245,
		LF_PAD6 = 246,
		LF_PAD7 = 247,
		LF_PAD8 = 248,
		LF_PAD9 = 249,
		LF_PAD10 = 250,
		LF_PAD11 = 251,
		LF_PAD12 = 252,
		LF_PAD13 = 253,
		LF_PAD14 = 254,
		LF_PAD15 = 255
	}
	internal enum CV_ptrtype
	{
		CV_PTR_BASE_SEG = 3,
		CV_PTR_BASE_VAL = 4,
		CV_PTR_BASE_SEGVAL = 5,
		CV_PTR_BASE_ADDR = 6,
		CV_PTR_BASE_SEGADDR = 7,
		CV_PTR_BASE_TYPE = 8,
		CV_PTR_BASE_SELF = 9,
		CV_PTR_NEAR32 = 10,
		CV_PTR_64 = 12,
		CV_PTR_UNUSEDPTR = 13
	}
	internal enum CV_ptrmode
	{
		CV_PTR_MODE_PTR,
		CV_PTR_MODE_REF,
		CV_PTR_MODE_PMEM,
		CV_PTR_MODE_PMFUNC,
		CV_PTR_MODE_RESERVED
	}
	internal enum CV_pmtype
	{
		CV_PMTYPE_Undef,
		CV_PMTYPE_D_Single,
		CV_PMTYPE_D_Multiple,
		CV_PMTYPE_D_Virtual,
		CV_PMTYPE_D_General,
		CV_PMTYPE_F_Single,
		CV_PMTYPE_F_Multiple,
		CV_PMTYPE_F_Virtual,
		CV_PMTYPE_F_General
	}
	internal enum CV_methodprop
	{
		CV_MTvanilla,
		CV_MTvirtual,
		CV_MTstatic,
		CV_MTfriend,
		CV_MTintro,
		CV_MTpurevirt,
		CV_MTpureintro
	}
	internal enum CV_VTS_desc
	{
		CV_VTS_near,
		CV_VTS_far,
		CV_VTS_thin,
		CV_VTS_outer,
		CV_VTS_meta,
		CV_VTS_near32,
		CV_VTS_far32,
		CV_VTS_unused
	}
	internal enum CV_LABEL_TYPE
	{
		CV_LABEL_NEAR = 0,
		CV_LABEL_FAR = 4
	}
	[Flags]
	internal enum CV_modifier : ushort
	{
		MOD_const = 1,
		MOD_volatile = 2,
		MOD_unaligned = 4
	}
	[Flags]
	internal enum CV_prop : ushort
	{
		packed = 1,
		ctor = 2,
		ovlops = 4,
		isnested = 8,
		cnested = 0x10,
		opassign = 0x20,
		opcast = 0x40,
		fwdref = 0x80,
		scoped = 0x100
	}
	[Flags]
	internal enum CV_fldattr
	{
		access = 3,
		mprop = 0x1C,
		pseudo = 0x20,
		noinherit = 0x40,
		noconstruct = 0x80,
		compgenx = 0x100
	}
	internal struct TYPTYPE
	{
		internal ushort len;

		internal ushort leaf;
	}
	internal struct CV_PDMR32_NVVFCN
	{
		internal int mdisp;
	}
	internal struct CV_PDMR32_VBASE
	{
		internal int mdisp;

		internal int pdisp;

		internal int vdisp;
	}
	internal struct CV_PMFR32_NVSA
	{
		internal uint off;
	}
	internal struct CV_PMFR32_NVMA
	{
		internal uint off;

		internal int disp;
	}
	internal struct CV_PMFR32_VBASE
	{
		internal uint off;

		internal int mdisp;

		internal int pdisp;

		internal int vdisp;
	}
	internal struct LeafModifier
	{
		internal uint type;

		internal CV_modifier attr;
	}
	[Flags]
	internal enum LeafPointerAttr : uint
	{
		ptrtype = 0x1Fu,
		ptrmode = 0xE0u,
		isflat32 = 0x100u,
		isvolatile = 0x200u,
		isconst = 0x400u,
		isunaligned = 0x800u,
		isrestrict = 0x1000u
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	internal struct LeafPointer
	{
		internal struct LeafPointerBody
		{
			internal uint utype;

			internal LeafPointerAttr attr;
		}
	}
	internal struct LeafArray
	{
		internal uint elemtype;

		internal uint idxtype;

		internal byte[] data;

		internal string name;
	}
	internal struct LeafClass
	{
		internal ushort count;

		internal ushort property;

		internal uint field;

		internal uint derived;

		internal uint vshape;

		internal byte[] data;

		internal string name;
	}
	internal struct LeafUnion
	{
		internal ushort count;

		internal ushort property;

		internal uint field;

		internal byte[] data;

		internal string name;
	}
	internal struct LeafAlias
	{
		internal uint utype;

		internal string name;
	}
	internal struct LeafManaged
	{
		internal string name;
	}
	internal struct LeafEnum
	{
		internal ushort count;

		internal ushort property;

		internal uint utype;

		internal uint field;

		internal string name;
	}
	internal struct LeafProc
	{
		internal uint rvtype;

		internal byte calltype;

		internal byte reserved;

		internal ushort parmcount;

		internal uint arglist;
	}
	internal struct LeafMFunc
	{
		internal uint rvtype;

		internal uint classtype;

		internal uint thistype;

		internal byte calltype;

		internal byte reserved;

		internal ushort parmcount;

		internal uint arglist;

		internal int thisadjust;
	}
	internal struct LeafVTShape
	{
		internal ushort count;

		internal byte[] desc;
	}
	internal struct LeafCobol0
	{
		internal uint type;

		internal byte[] data;
	}
	internal struct LeafCobol1
	{
		internal byte[] data;
	}
	internal struct LeafBArray
	{
		internal uint utype;
	}
	internal struct LeafLabel
	{
		internal ushort mode;
	}
	internal struct LeafDimArray
	{
		internal uint utype;

		internal uint diminfo;

		internal string name;
	}
	internal struct LeafVFTPath
	{
		internal uint count;

		internal uint[] bases;
	}
	internal struct LeafPreComp
	{
		internal uint start;

		internal uint count;

		internal uint signature;

		internal string name;
	}
	internal struct LeafEndPreComp
	{
		internal uint signature;
	}
	internal struct LeafOEM
	{
		internal ushort cvOEM;

		internal ushort recOEM;

		internal uint count;

		internal uint[] index;
	}
	internal enum OEM_ID
	{
		OEM_MS_FORTRAN90 = 61584,
		OEM_ODI = 16,
		OEM_THOMSON_SOFTWARE = 21587,
		OEM_ODI_REC_BASELIST = 0
	}
	internal struct LeafOEM2
	{
		internal Guid idOem;

		internal uint count;

		internal uint[] index;
	}
	internal struct LeafTypeServer
	{
		internal uint signature;

		internal uint age;

		internal string name;
	}
	internal struct LeafTypeServer2
	{
		internal Guid sig70;

		internal uint age;

		internal string name;
	}
	internal struct LeafSkip
	{
		internal uint type;

		internal byte[] data;
	}
	internal struct LeafArgList
	{
		internal uint count;

		internal uint[] arg;
	}
	internal struct LeafDerived
	{
		internal uint count;

		internal uint[] drvdcls;
	}
	internal struct LeafDefArg
	{
		internal uint type;

		internal byte[] expr;
	}
	internal struct LeafList
	{
		internal byte[] data;
	}
	internal struct LeafFieldList
	{
		internal char[] data;
	}
	internal struct mlMethod
	{
		internal ushort attr;

		internal ushort pad0;

		internal uint index;

		internal uint[] vbaseoff;
	}
	internal struct LeafMethodList
	{
		internal byte[] mList;
	}
	internal struct LeafBitfield
	{
		internal uint type;

		internal byte length;

		internal byte position;
	}
	internal struct LeafDimCon
	{
		internal uint typ;

		internal ushort rank;

		internal byte[] dim;
	}
	internal struct LeafDimVar
	{
		internal uint rank;

		internal uint typ;

		internal uint[] dim;
	}
	internal struct LeafRefSym
	{
		internal byte[] Sym;
	}
	internal struct LeafChar
	{
		internal sbyte val;
	}
	internal struct LeafShort
	{
		internal short val;
	}
	internal struct LeafUShort
	{
		internal ushort val;
	}
	internal struct LeafLong
	{
		internal int val;
	}
	internal struct LeafULong
	{
		internal uint val;
	}
	internal struct LeafQuad
	{
		internal long val;
	}
	internal struct LeafUQuad
	{
		internal ulong val;
	}
	internal struct LeafOct
	{
		internal ulong val0;

		internal ulong val1;
	}
	internal struct LeafUOct
	{
		internal ulong val0;

		internal ulong val1;
	}
	internal struct LeafReal32
	{
		internal float val;
	}
	internal struct LeafReal64
	{
		internal double val;
	}
	internal struct LeafReal80
	{
		internal FLOAT10 val;
	}
	internal struct LeafReal128
	{
		internal ulong val0;

		internal ulong val1;
	}
	internal struct LeafCmplx32
	{
		internal float val_real;

		internal float val_imag;
	}
	internal struct LeafCmplx64
	{
		internal double val_real;

		internal double val_imag;
	}
	internal struct LeafCmplx80
	{
		internal FLOAT10 val_real;

		internal FLOAT10 val_imag;
	}
	internal struct LeafCmplx128
	{
		internal ulong val0_real;

		internal ulong val1_real;

		internal ulong val0_imag;

		internal ulong val1_imag;
	}
	internal struct LeafVarString
	{
		internal ushort len;

		internal byte[] value;
	}
	internal struct LeafIndex
	{
		internal ushort pad0;

		internal uint index;
	}
	internal struct LeafBClass
	{
		internal ushort attr;

		internal uint index;

		internal byte[] offset;
	}
	internal struct LeafVBClass
	{
		internal ushort attr;

		internal uint index;

		internal uint vbptr;

		internal byte[] vbpoff;
	}
	internal struct LeafFriendCls
	{
		internal ushort pad0;

		internal uint index;
	}
	internal struct LeafFriendFcn
	{
		internal ushort pad0;

		internal uint index;

		internal string name;
	}
	internal struct LeafMember
	{
		internal ushort attr;

		internal uint index;

		internal byte[] offset;

		internal string name;
	}
	internal struct LeafSTMember
	{
		internal ushort attr;

		internal uint index;

		internal string name;
	}
	internal struct LeafVFuncTab
	{
		internal ushort pad0;

		internal uint type;
	}
	internal struct LeafVFuncOff
	{
		internal ushort pad0;

		internal uint type;

		internal int offset;
	}
	internal struct LeafMethod
	{
		internal ushort count;

		internal uint mList;

		internal string name;
	}
	internal struct LeafOneMethod
	{
		internal ushort attr;

		internal uint index;

		internal uint[] vbaseoff;

		internal string name;
	}
	internal struct LeafEnumerate
	{
		internal ushort attr;

		internal byte[] value;

		internal string name;
	}
	internal struct LeafNestType
	{
		internal ushort pad0;

		internal uint index;

		internal string name;
	}
	internal struct LeafNestTypeEx
	{
		internal ushort attr;

		internal uint index;

		internal string name;
	}
	internal struct LeafMemberModify
	{
		internal ushort

BooBoo Building/BepInEx/core/Mono.Cecil.Rocks.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using Mono.Cecil.Cil;
using Mono.Cecil.PE;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil.Rocks")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyVersion("0.10.4.0")]
namespace Mono.Cecil.Rocks;

public class DocCommentId
{
	private StringBuilder id;

	private DocCommentId()
	{
		id = new StringBuilder();
	}

	private void WriteField(FieldDefinition field)
	{
		WriteDefinition('F', (IMemberDefinition)(object)field);
	}

	private void WriteEvent(EventDefinition @event)
	{
		WriteDefinition('E', (IMemberDefinition)(object)@event);
	}

	private void WriteType(TypeDefinition type)
	{
		id.Append('T').Append(':');
		WriteTypeFullName((TypeReference)(object)type);
	}

	private void WriteMethod(MethodDefinition method)
	{
		WriteDefinition('M', (IMemberDefinition)(object)method);
		if (((MethodReference)method).HasGenericParameters)
		{
			id.Append('`').Append('`');
			id.Append(((MethodReference)method).GenericParameters.Count);
		}
		if (((MethodReference)method).HasParameters)
		{
			WriteParameters((IList<ParameterDefinition>)((MethodReference)method).Parameters);
		}
		if (IsConversionOperator(method))
		{
			WriteReturnType(method);
		}
	}

	private static bool IsConversionOperator(MethodDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (self.IsSpecialName)
		{
			if (!(((MemberReference)self).Name == "op_Explicit"))
			{
				return ((MemberReference)self).Name == "op_Implicit";
			}
			return true;
		}
		return false;
	}

	private void WriteReturnType(MethodDefinition method)
	{
		id.Append('~');
		WriteTypeSignature(((MethodReference)method).ReturnType);
	}

	private void WriteProperty(PropertyDefinition property)
	{
		WriteDefinition('P', (IMemberDefinition)(object)property);
		if (property.HasParameters)
		{
			WriteParameters((IList<ParameterDefinition>)((PropertyReference)property).Parameters);
		}
	}

	private void WriteParameters(IList<ParameterDefinition> parameters)
	{
		id.Append('(');
		WriteList(parameters, delegate(ParameterDefinition p)
		{
			WriteTypeSignature(((ParameterReference)p).ParameterType);
		});
		id.Append(')');
	}

	private void WriteTypeSignature(TypeReference type)
	{
		//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_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_002c: Expected I4, but got Unknown
		//IL_010c: 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_00ae: 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_005e: Expected O, but got Unknown
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Expected O, but got Unknown
		//IL_002c: 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_004d: Expected I4, but got Unknown
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Expected O, but got Unknown
		//IL_00db: 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_0109: Expected O, but got Unknown
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Expected O, but got Unknown
		MetadataType metadataType = type.MetadataType;
		switch (metadataType - 15)
		{
		default:
			switch (metadataType - 27)
			{
			case 0:
				WriteFunctionPointerTypeSignature((FunctionPointerType)type);
				return;
			case 3:
				id.Append('`').Append('`');
				id.Append(((GenericParameter)type).Position);
				return;
			case 5:
				WriteModiferTypeSignature((IModifierType)(OptionalModifierType)type, '!');
				return;
			case 4:
				WriteModiferTypeSignature((IModifierType)(RequiredModifierType)type, '|');
				return;
			}
			break;
		case 5:
			WriteArrayTypeSignature((ArrayType)type);
			return;
		case 1:
			WriteTypeSignature(((TypeSpecification)(ByReferenceType)type).ElementType);
			id.Append('@');
			return;
		case 6:
			WriteGenericInstanceTypeSignature((GenericInstanceType)type);
			return;
		case 4:
			id.Append('`');
			id.Append(((GenericParameter)type).Position);
			return;
		case 0:
			WriteTypeSignature(((TypeSpecification)(PointerType)type).ElementType);
			id.Append('*');
			return;
		case 2:
		case 3:
			break;
		}
		WriteTypeFullName(type);
	}

	private void WriteGenericInstanceTypeSignature(GenericInstanceType type)
	{
		if (Mixin.IsTypeSpecification(((TypeSpecification)type).ElementType))
		{
			throw new NotSupportedException();
		}
		WriteTypeFullName(((TypeSpecification)type).ElementType, stripGenericArity: true);
		id.Append('{');
		WriteList((IList<TypeReference>)type.GenericArguments, WriteTypeSignature);
		id.Append('}');
	}

	private void WriteList<T>(IList<T> list, Action<T> action)
	{
		for (int i = 0; i < list.Count; i++)
		{
			if (i > 0)
			{
				id.Append(',');
			}
			action(list[i]);
		}
	}

	private void WriteModiferTypeSignature(IModifierType type, char id)
	{
		WriteTypeSignature(type.ElementType);
		this.id.Append(id);
		WriteTypeSignature(type.ModifierType);
	}

	private void WriteFunctionPointerTypeSignature(FunctionPointerType type)
	{
		id.Append("=FUNC:");
		WriteTypeSignature(type.ReturnType);
		if (type.HasParameters)
		{
			WriteParameters((IList<ParameterDefinition>)type.Parameters);
		}
	}

	private void WriteArrayTypeSignature(ArrayType type)
	{
		WriteTypeSignature(((TypeSpecification)type).ElementType);
		if (type.IsVector)
		{
			id.Append("[]");
			return;
		}
		id.Append("[");
		WriteList((IList<ArrayDimension>)type.Dimensions, delegate(ArrayDimension dimension)
		{
			if (((ArrayDimension)(ref dimension)).LowerBound.HasValue)
			{
				id.Append(((ArrayDimension)(ref dimension)).LowerBound.Value);
			}
			id.Append(':');
			if (((ArrayDimension)(ref dimension)).UpperBound.HasValue)
			{
				id.Append(((ArrayDimension)(ref dimension)).UpperBound.Value - (((ArrayDimension)(ref dimension)).LowerBound.GetValueOrDefault() + 1));
			}
		});
		id.Append("]");
	}

	private void WriteDefinition(char id, IMemberDefinition member)
	{
		this.id.Append(id).Append(':');
		WriteTypeFullName((TypeReference)(object)member.DeclaringType);
		this.id.Append('.');
		WriteItemName(member.Name);
	}

	private void WriteTypeFullName(TypeReference type, bool stripGenericArity = false)
	{
		if (((MemberReference)type).DeclaringType != null)
		{
			WriteTypeFullName(((MemberReference)type).DeclaringType);
			id.Append('.');
		}
		if (!string.IsNullOrEmpty(type.Namespace))
		{
			id.Append(type.Namespace);
			id.Append('.');
		}
		string text = ((MemberReference)type).Name;
		if (stripGenericArity)
		{
			int num = text.LastIndexOf('`');
			if (num > 0)
			{
				text = text.Substring(0, num);
			}
		}
		id.Append(text);
	}

	private void WriteItemName(string name)
	{
		id.Append(name.Replace('.', '#').Replace('<', '{').Replace('>', '}'));
	}

	public override string ToString()
	{
		return id.ToString();
	}

	public static string GetDocCommentId(IMemberDefinition member)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Invalid comparison between Unknown and I4
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Invalid comparison between Unknown and I4
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Invalid comparison between Unknown and I4
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Expected O, but got Unknown
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Invalid comparison between Unknown and I4
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Expected O, but got Unknown
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Invalid comparison between Unknown and I4
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Expected O, but got Unknown
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Invalid comparison between Unknown and I4
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Expected O, but got Unknown
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Expected O, but got Unknown
		if (member == null)
		{
			throw new ArgumentNullException("member");
		}
		DocCommentId docCommentId = new DocCommentId();
		MetadataToken metadataToken = ((IMetadataTokenProvider)member).MetadataToken;
		TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType;
		if ((int)tokenType <= 67108864)
		{
			if ((int)tokenType != 33554432)
			{
				if ((int)tokenType != 67108864)
				{
					goto IL_009d;
				}
				docCommentId.WriteField((FieldDefinition)member);
			}
			else
			{
				docCommentId.WriteType((TypeDefinition)member);
			}
		}
		else if ((int)tokenType != 100663296)
		{
			if ((int)tokenType != 335544320)
			{
				if ((int)tokenType != 385875968)
				{
					goto IL_009d;
				}
				docCommentId.WriteProperty((PropertyDefinition)member);
			}
			else
			{
				docCommentId.WriteEvent((EventDefinition)member);
			}
		}
		else
		{
			docCommentId.WriteMethod((MethodDefinition)member);
		}
		return docCommentId.ToString();
		IL_009d:
		throw new NotSupportedException(member.FullName);
	}
}
internal static class Functional
{
	public static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f)
	{
		Func<A, R> g = null;
		g = f((A a) => g(a));
		return g;
	}

	public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource element)
	{
		if (source == null)
		{
			throw new ArgumentNullException("source");
		}
		return PrependIterator(source, element);
	}

	private static IEnumerable<TSource> PrependIterator<TSource>(IEnumerable<TSource> source, TSource element)
	{
		yield return element;
		foreach (TSource item in source)
		{
			yield return item;
		}
	}
}
public interface IILVisitor
{
	void OnInlineNone(OpCode opcode);

	void OnInlineSByte(OpCode opcode, sbyte value);

	void OnInlineByte(OpCode opcode, byte value);

	void OnInlineInt32(OpCode opcode, int value);

	void OnInlineInt64(OpCode opcode, long value);

	void OnInlineSingle(OpCode opcode, float value);

	void OnInlineDouble(OpCode opcode, double value);

	void OnInlineString(OpCode opcode, string value);

	void OnInlineBranch(OpCode opcode, int offset);

	void OnInlineSwitch(OpCode opcode, int[] offsets);

	void OnInlineVariable(OpCode opcode, VariableDefinition variable);

	void OnInlineArgument(OpCode opcode, ParameterDefinition parameter);

	void OnInlineSignature(OpCode opcode, CallSite callSite);

	void OnInlineType(OpCode opcode, TypeReference type);

	void OnInlineField(OpCode opcode, FieldReference field);

	void OnInlineMethod(OpCode opcode, MethodReference method);
}
public static class ILParser
{
	private class ParseContext
	{
		public CodeReader Code { get; set; }

		public int Position { get; set; }

		public MetadataReader Metadata { get; set; }

		public Collection<VariableDefinition> Variables { get; set; }

		public IILVisitor Visitor { get; set; }
	}

	public static void Parse(MethodDefinition method, IILVisitor visitor)
	{
		if (method == null)
		{
			throw new ArgumentNullException("method");
		}
		if (visitor == null)
		{
			throw new ArgumentNullException("visitor");
		}
		if (!method.HasBody || !((MemberReference)method).HasImage)
		{
			throw new ArgumentException();
		}
		((MemberReference)method).Module.Read<MethodDefinition, bool>(method, (Func<MethodDefinition, MetadataReader, bool>)delegate(MethodDefinition m, MetadataReader _)
		{
			ParseMethod(m, visitor);
			return true;
		});
	}

	private static void ParseMethod(MethodDefinition method, IILVisitor visitor)
	{
		ParseContext parseContext = CreateContext(method, visitor);
		CodeReader code = parseContext.Code;
		byte b = ((BinaryReader)(object)code).ReadByte();
		switch (b & 3)
		{
		case 2:
			ParseCode(b >> 2, parseContext);
			break;
		case 3:
			((BinaryStreamReader)code).Advance(-1);
			ParseFatMethod(parseContext);
			break;
		default:
			throw new NotSupportedException();
		}
		code.MoveBackTo(parseContext.Position);
	}

	private static ParseContext CreateContext(MethodDefinition method, IILVisitor visitor)
	{
		CodeReader val = ((MemberReference)method).Module.Read<MethodDefinition, CodeReader>(method, (Func<MethodDefinition, MetadataReader, CodeReader>)((MethodDefinition _, MetadataReader reader) => reader.code));
		int position = val.MoveTo(method);
		return new ParseContext
		{
			Code = val,
			Position = position,
			Metadata = val.reader,
			Visitor = visitor
		};
	}

	private static void ParseFatMethod(ParseContext context)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: 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_002a: Unknown result type (might be due to invalid IL or missing references)
		CodeReader code = context.Code;
		((BinaryStreamReader)code).Advance(4);
		int code_size = ((BinaryReader)(object)code).ReadInt32();
		MetadataToken val = code.ReadToken();
		if (val != MetadataToken.Zero)
		{
			context.Variables = (Collection<VariableDefinition>)(object)code.ReadVariables(val);
		}
		ParseCode(code_size, context);
	}

	private static void ParseCode(int code_size, ParseContext context)
	{
		//IL_004d: 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_0052: 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_005b: 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_00b4: Expected I4, but got Unknown
		//IL_0116: 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_024e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0253: Unknown result type (might be due to invalid IL or missing references)
		//IL_0257: 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_025e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0265: Invalid comparison between Unknown and I4
		//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_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: 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_01ad: 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_01c6: 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)
		//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0183: Unknown result type (might be due to invalid IL or missing references)
		//IL_020d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01db: Unknown result type (might be due to invalid IL or missing references)
		//IL_0287: Unknown result type (might be due to invalid IL or missing references)
		//IL_028e: Invalid comparison between Unknown and I4
		//IL_0267: Unknown result type (might be due to invalid IL or missing references)
		//IL_026e: Invalid comparison between Unknown and I4
		//IL_014a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ab: Invalid comparison between Unknown and I4
		//IL_0290: Unknown result type (might be due to invalid IL or missing references)
		//IL_0297: Invalid comparison between Unknown and I4
		//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c7: Expected O, but got Unknown
		//IL_0270: Unknown result type (might be due to invalid IL or missing references)
		//IL_0277: Invalid comparison between Unknown and I4
		//IL_00f4: 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_02b4: Invalid comparison between Unknown and I4
		//IL_02ca: 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_0299: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a0: Invalid comparison between Unknown and I4
		//IL_0279: Unknown result type (might be due to invalid IL or missing references)
		//IL_0280: Invalid comparison between Unknown and I4
		//IL_02db: 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_02e9: Expected O, but got Unknown
		//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0312: Unknown result type (might be due to invalid IL or missing references)
		CodeReader code = context.Code;
		MetadataReader metadata = context.Metadata;
		IILVisitor visitor = context.Visitor;
		int num = ((BinaryStreamReader)code).Position + code_size;
		while (((BinaryStreamReader)code).Position < num)
		{
			byte b = ((BinaryReader)(object)code).ReadByte();
			OpCode val = ((b != 254) ? OpCodes.OneByteOpCode[b] : OpCodes.TwoBytesOpCode[((BinaryReader)(object)code).ReadByte()]);
			OperandType operandType = ((OpCode)(ref val)).OperandType;
			IMetadataTokenProvider val2;
			switch ((int)operandType)
			{
			case 5:
				visitor.OnInlineNone(val);
				break;
			case 10:
			{
				int num2 = ((BinaryReader)(object)code).ReadInt32();
				int[] array = new int[num2];
				for (int i = 0; i < num2; i++)
				{
					array[i] = ((BinaryReader)(object)code).ReadInt32();
				}
				visitor.OnInlineSwitch(val, array);
				break;
			}
			case 15:
				visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadSByte());
				break;
			case 0:
				visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadInt32());
				break;
			case 16:
				if (val == OpCodes.Ldc_I4_S)
				{
					visitor.OnInlineSByte(val, ((BinaryReader)(object)code).ReadSByte());
				}
				else
				{
					visitor.OnInlineByte(val, ((BinaryReader)(object)code).ReadByte());
				}
				break;
			case 2:
				visitor.OnInlineInt32(val, ((BinaryReader)(object)code).ReadInt32());
				break;
			case 3:
				visitor.OnInlineInt64(val, ((BinaryReader)(object)code).ReadInt64());
				break;
			case 17:
				visitor.OnInlineSingle(val, ((BinaryReader)(object)code).ReadSingle());
				break;
			case 7:
				visitor.OnInlineDouble(val, ((BinaryReader)(object)code).ReadDouble());
				break;
			case 8:
				visitor.OnInlineSignature(val, code.GetCallSite(code.ReadToken()));
				break;
			case 9:
				visitor.OnInlineString(val, code.GetString(code.ReadToken()));
				break;
			case 19:
				visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadByte()));
				break;
			case 14:
				visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadInt16()));
				break;
			case 18:
				visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadByte()));
				break;
			case 13:
				visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadInt16()));
				break;
			case 1:
			case 4:
			case 11:
			case 12:
				{
					val2 = metadata.LookupToken(code.ReadToken());
					MetadataToken metadataToken = val2.MetadataToken;
					TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType;
					if ((int)tokenType <= 67108864)
					{
						if ((int)tokenType != 16777216 && (int)tokenType != 33554432)
						{
							if ((int)tokenType == 67108864)
							{
								visitor.OnInlineField(val, (FieldReference)val2);
							}
							break;
						}
						goto IL_02b8;
					}
					if ((int)tokenType <= 167772160)
					{
						if ((int)tokenType != 100663296)
						{
							if ((int)tokenType != 167772160)
							{
								break;
							}
							FieldReference val3 = (FieldReference)(object)((val2 is FieldReference) ? val2 : null);
							if (val3 != null)
							{
								visitor.OnInlineField(val, val3);
								break;
							}
							MethodReference val4 = (MethodReference)(object)((val2 is MethodReference) ? val2 : null);
							if (val4 != null)
							{
								visitor.OnInlineMethod(val, val4);
								break;
							}
							throw new InvalidOperationException();
						}
					}
					else
					{
						if ((int)tokenType == 452984832)
						{
							goto IL_02b8;
						}
						if ((int)tokenType != 721420288)
						{
							break;
						}
					}
					visitor.OnInlineMethod(val, (MethodReference)val2);
					break;
				}
				IL_02b8:
				visitor.OnInlineType(val, (TypeReference)val2);
				break;
			}
		}
	}

	private static VariableDefinition GetVariable(ParseContext context, int index)
	{
		return context.Variables[index];
	}
}
public static class MethodBodyRocks
{
	public static void SimplifyMacros(this MethodBody self)
	{
		//IL_0014: 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_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Invalid comparison between Unknown and I4
		//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_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_004a: 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_0126: Expected I4, but got Unknown
		//IL_0137: 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_0165: 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_0193: Unknown result type (might be due to invalid IL or missing references)
		//IL_01af: 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_01e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0203: 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)
		//IL_023b: 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_0273: 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_0293: 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_02b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e9: 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_0315: Unknown result type (might be due to invalid IL or missing references)
		//IL_032b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0341: 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_036d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0383: Unknown result type (might be due to invalid IL or missing references)
		//IL_0399: 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_03cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_03df: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ef: 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_040f: Unknown result type (might be due to invalid IL or missing references)
		//IL_041c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0429: 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)
		//IL_0443: 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_045d: Unknown result type (might be due to invalid IL or missing references)
		//IL_046a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0477: 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: Invalid comparison between Unknown and I4
		//IL_0484: Unknown result type (might be due to invalid IL or missing references)
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				OpCode opCode = current.OpCode;
				if ((int)((OpCode)(ref opCode)).OpCodeType != 1)
				{
					continue;
				}
				opCode = current.OpCode;
				Code code = ((OpCode)(ref opCode)).Code;
				switch (code - 2)
				{
				case 0:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 0));
					continue;
				case 1:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 1));
					continue;
				case 2:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 2));
					continue;
				case 3:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 3));
					continue;
				case 4:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[0]);
					continue;
				case 5:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[1]);
					continue;
				case 6:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[2]);
					continue;
				case 7:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[3]);
					continue;
				case 8:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[0]);
					continue;
				case 9:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[1]);
					continue;
				case 10:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[2]);
					continue;
				case 11:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[3]);
					continue;
				case 12:
					current.OpCode = OpCodes.Ldarg;
					continue;
				case 13:
					current.OpCode = OpCodes.Ldarga;
					continue;
				case 14:
					current.OpCode = OpCodes.Starg;
					continue;
				case 15:
					current.OpCode = OpCodes.Ldloc;
					continue;
				case 16:
					current.OpCode = OpCodes.Ldloca;
					continue;
				case 17:
					current.OpCode = OpCodes.Stloc;
					continue;
				case 19:
					ExpandMacro(current, OpCodes.Ldc_I4, -1);
					continue;
				case 20:
					ExpandMacro(current, OpCodes.Ldc_I4, 0);
					continue;
				case 21:
					ExpandMacro(current, OpCodes.Ldc_I4, 1);
					continue;
				case 22:
					ExpandMacro(current, OpCodes.Ldc_I4, 2);
					continue;
				case 23:
					ExpandMacro(current, OpCodes.Ldc_I4, 3);
					continue;
				case 24:
					ExpandMacro(current, OpCodes.Ldc_I4, 4);
					continue;
				case 25:
					ExpandMacro(current, OpCodes.Ldc_I4, 5);
					continue;
				case 26:
					ExpandMacro(current, OpCodes.Ldc_I4, 6);
					continue;
				case 27:
					ExpandMacro(current, OpCodes.Ldc_I4, 7);
					continue;
				case 28:
					ExpandMacro(current, OpCodes.Ldc_I4, 8);
					continue;
				case 29:
					ExpandMacro(current, OpCodes.Ldc_I4, (int)(sbyte)current.Operand);
					continue;
				case 40:
					current.OpCode = OpCodes.Br;
					continue;
				case 41:
					current.OpCode = OpCodes.Brfalse;
					continue;
				case 42:
					current.OpCode = OpCodes.Brtrue;
					continue;
				case 43:
					current.OpCode = OpCodes.Beq;
					continue;
				case 44:
					current.OpCode = OpCodes.Bge;
					continue;
				case 45:
					current.OpCode = OpCodes.Bgt;
					continue;
				case 46:
					current.OpCode = OpCodes.Ble;
					continue;
				case 47:
					current.OpCode = OpCodes.Blt;
					continue;
				case 48:
					current.OpCode = OpCodes.Bne_Un;
					continue;
				case 49:
					current.OpCode = OpCodes.Bge_Un;
					continue;
				case 50:
					current.OpCode = OpCodes.Bgt_Un;
					continue;
				case 51:
					current.OpCode = OpCodes.Ble_Un;
					continue;
				case 52:
					current.OpCode = OpCodes.Blt_Un;
					continue;
				case 18:
				case 30:
				case 31:
				case 32:
				case 33:
				case 34:
				case 35:
				case 36:
				case 37:
				case 38:
				case 39:
					continue;
				}
				if ((int)code == 188)
				{
					current.OpCode = OpCodes.Leave;
				}
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static void ExpandMacro(Instruction instruction, OpCode opcode, object operand)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		instruction.OpCode = opcode;
		instruction.Operand = operand;
	}

	private static void MakeMacro(Instruction instruction, OpCode opcode)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		instruction.OpCode = opcode;
		instruction.Operand = null;
	}

	public static void Optimize(this MethodBody self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		self.OptimizeLongs();
		self.OptimizeMacros();
	}

	private static void OptimizeLongs(this MethodBody self)
	{
		//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_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Invalid comparison between Unknown and I4
		//IL_0042: 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)
		for (int i = 0; i < self.Instructions.Count; i++)
		{
			Instruction val = self.Instructions[i];
			OpCode opCode = val.OpCode;
			if ((int)((OpCode)(ref opCode)).Code == 33)
			{
				long num = (long)val.Operand;
				if (num < int.MaxValue && num > int.MinValue)
				{
					ExpandMacro(val, OpCodes.Ldc_I4, (int)num);
					self.Instructions.Insert(++i, Instruction.Create(OpCodes.Conv_I8));
				}
			}
		}
	}

	public static void OptimizeMacros(this MethodBody self)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: 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_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Invalid comparison between Unknown and I4
		//IL_0048: 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_006d: Expected I4, but got Unknown
		//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_030a: Unknown result type (might be due to invalid IL or missing references)
		//IL_031a: 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_0334: 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_034e: 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_0368: 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_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0238: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_028c: 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_0148: 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_0168: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a1: 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_01e2: 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_0202: 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)
		//IL_00be: 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_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_0271: Unknown result type (might be due to invalid IL or missing references)
		//IL_0193: Unknown result type (might be due to invalid IL or missing references)
		//IL_021d: 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)
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		MethodDefinition method = self.Method;
		Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				OpCode opCode = current.OpCode;
				Code code = ((OpCode)(ref opCode)).Code;
				if ((int)code != 32)
				{
					switch (code - 199)
					{
					case 0:
					{
						int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index;
						if (index == -1 && current.Operand == self.ThisParameter)
						{
							index = 0;
						}
						else if (((MethodReference)method).HasThis)
						{
							index++;
						}
						switch (index)
						{
						case 0:
							MakeMacro(current, OpCodes.Ldarg_0);
							break;
						case 1:
							MakeMacro(current, OpCodes.Ldarg_1);
							break;
						case 2:
							MakeMacro(current, OpCodes.Ldarg_2);
							break;
						case 3:
							MakeMacro(current, OpCodes.Ldarg_3);
							break;
						default:
							if (index < 256)
							{
								ExpandMacro(current, OpCodes.Ldarg_S, current.Operand);
							}
							break;
						}
						break;
					}
					case 3:
					{
						int index = ((VariableReference)(VariableDefinition)current.Operand).Index;
						switch (index)
						{
						case 0:
							MakeMacro(current, OpCodes.Ldloc_0);
							break;
						case 1:
							MakeMacro(current, OpCodes.Ldloc_1);
							break;
						case 2:
							MakeMacro(current, OpCodes.Ldloc_2);
							break;
						case 3:
							MakeMacro(current, OpCodes.Ldloc_3);
							break;
						default:
							if (index < 256)
							{
								ExpandMacro(current, OpCodes.Ldloc_S, current.Operand);
							}
							break;
						}
						break;
					}
					case 5:
					{
						int index = ((VariableReference)(VariableDefinition)current.Operand).Index;
						switch (index)
						{
						case 0:
							MakeMacro(current, OpCodes.Stloc_0);
							break;
						case 1:
							MakeMacro(current, OpCodes.Stloc_1);
							break;
						case 2:
							MakeMacro(current, OpCodes.Stloc_2);
							break;
						case 3:
							MakeMacro(current, OpCodes.Stloc_3);
							break;
						default:
							if (index < 256)
							{
								ExpandMacro(current, OpCodes.Stloc_S, current.Operand);
							}
							break;
						}
						break;
					}
					case 1:
					{
						int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index;
						if (index == -1 && current.Operand == self.ThisParameter)
						{
							index = 0;
						}
						else if (((MethodReference)method).HasThis)
						{
							index++;
						}
						if (index < 256)
						{
							ExpandMacro(current, OpCodes.Ldarga_S, current.Operand);
						}
						break;
					}
					case 4:
						if (((VariableReference)(VariableDefinition)current.Operand).Index < 256)
						{
							ExpandMacro(current, OpCodes.Ldloca_S, current.Operand);
						}
						break;
					}
					continue;
				}
				int num = (int)current.Operand;
				switch (num)
				{
				case -1:
					MakeMacro(current, OpCodes.Ldc_I4_M1);
					continue;
				case 0:
					MakeMacro(current, OpCodes.Ldc_I4_0);
					continue;
				case 1:
					MakeMacro(current, OpCodes.Ldc_I4_1);
					continue;
				case 2:
					MakeMacro(current, OpCodes.Ldc_I4_2);
					continue;
				case 3:
					MakeMacro(current, OpCodes.Ldc_I4_3);
					continue;
				case 4:
					MakeMacro(current, OpCodes.Ldc_I4_4);
					continue;
				case 5:
					MakeMacro(current, OpCodes.Ldc_I4_5);
					continue;
				case 6:
					MakeMacro(current, OpCodes.Ldc_I4_6);
					continue;
				case 7:
					MakeMacro(current, OpCodes.Ldc_I4_7);
					continue;
				case 8:
					MakeMacro(current, OpCodes.Ldc_I4_8);
					continue;
				}
				if (num >= -128 && num < 128)
				{
					ExpandMacro(current, OpCodes.Ldc_I4_S, (sbyte)num);
				}
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
		OptimizeBranches(self);
	}

	private static void OptimizeBranches(MethodBody body)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		ComputeOffsets(body);
		Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				OpCode opCode = current.OpCode;
				if ((int)((OpCode)(ref opCode)).OperandType == 0 && OptimizeBranch(current))
				{
					ComputeOffsets(body);
				}
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static bool OptimizeBranch(Instruction instruction)
	{
		//IL_0006: 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_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_003e: 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_0044: 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_0081: Expected I4, but got Unknown
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: 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_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: 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_0106: 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_0120: 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_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Invalid comparison between Unknown and I4
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		int offset = ((Instruction)instruction.Operand).Offset;
		int offset2 = instruction.Offset;
		OpCode opCode = instruction.OpCode;
		int num = offset - (offset2 + ((OpCode)(ref opCode)).Size + 4);
		if (num < -128 || num > 127)
		{
			return false;
		}
		opCode = instruction.OpCode;
		Code code = ((OpCode)(ref opCode)).Code;
		switch (code - 55)
		{
		default:
			if ((int)code == 187)
			{
				instruction.OpCode = OpCodes.Leave_S;
			}
			break;
		case 0:
			instruction.OpCode = OpCodes.Br_S;
			break;
		case 1:
			instruction.OpCode = OpCodes.Brfalse_S;
			break;
		case 2:
			instruction.OpCode = OpCodes.Brtrue_S;
			break;
		case 3:
			instruction.OpCode = OpCodes.Beq_S;
			break;
		case 4:
			instruction.OpCode = OpCodes.Bge_S;
			break;
		case 5:
			instruction.OpCode = OpCodes.Bgt_S;
			break;
		case 6:
			instruction.OpCode = OpCodes.Ble_S;
			break;
		case 7:
			instruction.OpCode = OpCodes.Blt_S;
			break;
		case 8:
			instruction.OpCode = OpCodes.Bne_Un_S;
			break;
		case 9:
			instruction.OpCode = OpCodes.Bge_Un_S;
			break;
		case 10:
			instruction.OpCode = OpCodes.Bgt_Un_S;
			break;
		case 11:
			instruction.OpCode = OpCodes.Ble_Un_S;
			break;
		case 12:
			instruction.OpCode = OpCodes.Blt_Un_S;
			break;
		}
		return true;
	}

	private static void ComputeOffsets(MethodBody body)
	{
		//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)
		int num = 0;
		Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				current.Offset = num;
				num += current.GetSize();
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}
}
public static class MethodDefinitionRocks
{
	public static MethodDefinition GetBaseMethod(this MethodDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.IsVirtual)
		{
			return self;
		}
		if (self.IsNewSlot)
		{
			return self;
		}
		for (TypeDefinition val = ResolveBaseType(self.DeclaringType); val != null; val = ResolveBaseType(val))
		{
			MethodDefinition matchingMethod = GetMatchingMethod(val, self);
			if (matchingMethod != null)
			{
				return matchingMethod;
			}
		}
		return self;
	}

	public static MethodDefinition GetOriginalBaseMethod(this MethodDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		while (true)
		{
			MethodDefinition baseMethod = self.GetBaseMethod();
			if (baseMethod == self)
			{
				break;
			}
			self = baseMethod;
		}
		return self;
	}

	private static TypeDefinition ResolveBaseType(TypeDefinition type)
	{
		if (type == null)
		{
			return null;
		}
		TypeReference baseType = type.BaseType;
		if (baseType == null)
		{
			return null;
		}
		return baseType.Resolve();
	}

	private static MethodDefinition GetMatchingMethod(TypeDefinition type, MethodDefinition method)
	{
		return MetadataResolver.GetMethod(type.Methods, (MethodReference)(object)method);
	}
}
public static class ModuleDefinitionRocks
{
	public static IEnumerable<TypeDefinition> GetAllTypes(this ModuleDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		return ((IEnumerable<TypeDefinition>)self.Types).SelectMany(Functional.Y((Func<TypeDefinition, IEnumerable<TypeDefinition>> f) => (TypeDefinition type) => ((IEnumerable<TypeDefinition>)type.NestedTypes).SelectMany(f).Prepend(type)));
	}
}
public static class ParameterReferenceRocks
{
	public static int GetSequence(this ParameterReference self)
	{
		return self.Index + 1;
	}
}
public static class SecurityDeclarationRocks
{
	public static PermissionSet ToPermissionSet(this SecurityDeclaration self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (TryProcessPermissionSetAttribute(self, out var set))
		{
			return set;
		}
		return CreatePermissionSet(self);
	}

	private static bool TryProcessPermissionSetAttribute(SecurityDeclaration declaration, out PermissionSet set)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Expected I4, but got Unknown
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Expected O, but got Unknown
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_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)
		set = null;
		if (!declaration.HasSecurityAttributes && declaration.SecurityAttributes.Count != 1)
		{
			return false;
		}
		SecurityAttribute val = declaration.SecurityAttributes[0];
		if (!Mixin.IsTypeOf(val.AttributeType, "System.Security.Permissions", "PermissionSetAttribute"))
		{
			return false;
		}
		PermissionSetAttribute val2 = new PermissionSetAttribute((SecurityAction)declaration.Action);
		CustomAttributeNamedArgument val3 = val.Properties[0];
		CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref val3)).Argument;
		string text = (string)((CustomAttributeArgument)(ref argument)).Value;
		string name = ((CustomAttributeNamedArgument)(ref val3)).Name;
		if (!(name == "XML"))
		{
			if (!(name == "Name"))
			{
				throw new NotImplementedException(((CustomAttributeNamedArgument)(ref val3)).Name);
			}
			val2.Name = text;
		}
		else
		{
			val2.XML = text;
		}
		set = val2.CreatePermissionSet();
		return true;
	}

	private static PermissionSet CreatePermissionSet(SecurityDeclaration declaration)
	{
		//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)
		PermissionSet permissionSet = new PermissionSet(PermissionState.None);
		Enumerator<SecurityAttribute> enumerator = declaration.SecurityAttributes.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				SecurityAttribute current = enumerator.Current;
				IPermission perm = CreatePermission(declaration, current);
				permissionSet.AddPermission(perm);
			}
			return permissionSet;
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static IPermission CreatePermission(SecurityDeclaration declaration, SecurityAttribute attribute)
	{
		SecurityAttribute obj = CreateSecurityAttribute(Type.GetType(((MemberReference)attribute.AttributeType).FullName) ?? throw new ArgumentException("attribute"), declaration) ?? throw new InvalidOperationException();
		CompleteSecurityAttribute(obj, attribute);
		return obj.CreatePermission();
	}

	private static void CompleteSecurityAttribute(SecurityAttribute security_attribute, SecurityAttribute attribute)
	{
		if (attribute.HasFields)
		{
			CompleteSecurityAttributeFields(security_attribute, attribute);
		}
		if (attribute.HasProperties)
		{
			CompleteSecurityAttributeProperties(security_attribute, attribute);
		}
	}

	private static void CompleteSecurityAttributeFields(SecurityAttribute security_attribute, SecurityAttribute attribute)
	{
		//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)
		//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_002d: 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)
		Type type = security_attribute.GetType();
		Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Fields.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				CustomAttributeNamedArgument current = enumerator.Current;
				FieldInfo? field = type.GetField(((CustomAttributeNamedArgument)(ref current)).Name);
				CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument;
				field.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value);
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static void CompleteSecurityAttributeProperties(SecurityAttribute security_attribute, SecurityAttribute attribute)
	{
		//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)
		//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_002d: 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)
		Type type = security_attribute.GetType();
		Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Properties.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				CustomAttributeNamedArgument current = enumerator.Current;
				PropertyInfo? property = type.GetProperty(((CustomAttributeNamedArgument)(ref current)).Name);
				CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument;
				property.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value, null);
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static SecurityAttribute CreateSecurityAttribute(Type attribute_type, SecurityDeclaration declaration)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Expected I4, but got Unknown
		try
		{
			return (SecurityAttribute)Activator.CreateInstance(attribute_type, (SecurityAction)declaration.Action);
		}
		catch (MissingMethodException)
		{
			return (SecurityAttribute)Activator.CreateInstance(attribute_type, new object[0]);
		}
	}

	public static SecurityDeclaration ToSecurityDeclaration(this PermissionSet self, SecurityAction action, ModuleDefinition module)
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Expected O, but got Unknown
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Expected O, but got Unknown
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (module == null)
		{
			throw new ArgumentNullException("module");
		}
		SecurityDeclaration val = new SecurityDeclaration(action);
		SecurityAttribute val2 = new SecurityAttribute(module.TypeSystem.LookupType("System.Security.Permissions", "PermissionSetAttribute"));
		val2.Properties.Add(new CustomAttributeNamedArgument("XML", new CustomAttributeArgument(module.TypeSystem.String, (object)self.ToXml().ToString())));
		val.SecurityAttributes.Add(val2);
		return val;
	}
}
public static class TypeDefinitionRocks
{
	public static IEnumerable<MethodDefinition> GetConstructors(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.HasMethods)
		{
			return Empty<MethodDefinition>.Array;
		}
		return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => method.IsConstructor);
	}

	public static MethodDefinition GetStaticConstructor(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.HasMethods)
		{
			return null;
		}
		return self.GetConstructors().FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition ctor) => ctor.IsStatic));
	}

	public static IEnumerable<MethodDefinition> GetMethods(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.HasMethods)
		{
			return Empty<MethodDefinition>.Array;
		}
		return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => !method.IsConstructor);
	}

	public static TypeReference GetEnumUnderlyingType(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.IsEnum)
		{
			throw new ArgumentException();
		}
		return Mixin.GetEnumUnderlyingType(self);
	}
}
public static class TypeReferenceRocks
{
	public static ArrayType MakeArrayType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new ArrayType(self);
	}

	public static ArrayType MakeArrayType(this TypeReference self, int rank)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Expected O, but got Unknown
		//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 (rank == 0)
		{
			throw new ArgumentOutOfRangeException("rank");
		}
		ArrayType val = new ArrayType(self);
		for (int i = 1; i < rank; i++)
		{
			val.Dimensions.Add(default(ArrayDimension));
		}
		return val;
	}

	public static PointerType MakePointerType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new PointerType(self);
	}

	public static ByReferenceType MakeByReferenceType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new ByReferenceType(self);
	}

	public static OptionalModifierType MakeOptionalModifierType(this TypeReference self, TypeReference modifierType)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		return new OptionalModifierType(modifierType, self);
	}

	public static RequiredModifierType MakeRequiredModifierType(this TypeReference self, TypeReference modifierType)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		return new RequiredModifierType(modifierType, self);
	}

	public static GenericInstanceType MakeGenericInstanceType(this TypeReference self, params TypeReference[] arguments)
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Expected O, but got Unknown
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (arguments == null)
		{
			throw new ArgumentNullException("arguments");
		}
		if (arguments.Length == 0)
		{
			throw new ArgumentException();
		}
		if (self.GenericParameters.Count != arguments.Length)
		{
			throw new ArgumentException();
		}
		GenericInstanceType val = new GenericInstanceType(self);
		foreach (TypeReference val2 in arguments)
		{
			val.GenericArguments.Add(val2);
		}
		return val;
	}

	public static PinnedType MakePinnedType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new PinnedType(self);
	}

	public static SentinelType MakeSentinelType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new SentinelType(self);
	}
}

BooBoo Building/BepInEx/core/MonoMod.RuntimeDetour.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using MonoMod.RuntimeDetour.Platforms;
using MonoMod.Utils;
using MonoMod.Utils.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2022 0x0ade")]
[assembly: AssemblyDescription("Flexible and easily extensible runtime detouring library. Wrap, replace and manipulate (Mono.Cecil) methods at runtime.")]
[assembly: AssemblyFileVersion("22.1.29.1")]
[assembly: AssemblyInformationalVersion("22.01.29.01")]
[assembly: AssemblyProduct("MonoMod.RuntimeDetour")]
[assembly: AssemblyTitle("MonoMod.RuntimeDetour")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("22.1.29.1")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
}
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static string Replace(this string self, string oldValue, string newValue, StringComparison comparison)
	{
		return self.Replace(oldValue, newValue);
	}

	public static bool Contains(this string self, string value, StringComparison comparison)
	{
		return self.Contains(value);
	}

	public static int GetHashCode(this string self, StringComparison comparison)
	{
		return self.GetHashCode();
	}

	public static int IndexOf(this string self, char value, StringComparison comparison)
	{
		return self.IndexOf(value);
	}

	public static int IndexOf(this string self, string value, StringComparison comparison)
	{
		return self.IndexOf(value);
	}

	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"))
			{
				string? environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG");
				bool? obj;
				if (environmentVariable == null)
				{
					obj = null;
				}
				else
				{
					string text = environmentVariable.ToLower(CultureInfo.InvariantCulture);
					obj = ((text != null) ? new bool?(MultiTargetShims.Contains(text, Tag.ToLower(CultureInfo.InvariantCulture), StringComparison.Ordinal)) : null);
				}
				bool? flag = obj;
				if (!flag.GetValueOrDefault())
				{
					return;
				}
			}
			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(CultureInfo.InvariantCulture, str, new object[1] { value }));
			writer.Flush();
			return value;
		}
	}
}
namespace MonoMod.RuntimeDetour
{
	public struct DetourConfig
	{
		public bool ManualApply;

		public int Priority;

		public string ID;

		public IEnumerable<string> Before;

		public IEnumerable<string> After;
	}
	public class Detour : ISortableDetour, IDetour, IDisposable
	{
		private static Dictionary<MethodBase, List<Detour>> _DetourMap = new Dictionary<MethodBase, List<Detour>>((IEqualityComparer<MethodBase>?)new GenericMethodInstantiationComparer());

		private static Dictionary<MethodBase, MethodInfo> _BackupMethods = new Dictionary<MethodBase, MethodInfo>();

		private static uint _GlobalIndexNext = 0u;

		public static Func<Detour, MethodBase, MethodBase, bool> OnDetour;

		public static Func<Detour, bool> OnUndo;

		public static Func<Detour, MethodBase, MethodBase> OnGenerateTrampoline;

		private readonly uint _GlobalIndex;

		private int _Priority;

		private string _ID;

		private List<string> _Before = new List<string>();

		private ReadOnlyCollection<string> _BeforeRO;

		private List<string> _After = new List<string>();

		private ReadOnlyCollection<string> _AfterRO;

		public readonly MethodBase Method;

		public readonly MethodBase Target;

		public readonly MethodBase TargetReal;

		private NativeDetour _TopDetour;

		private MethodInfo _ChainedTrampoline;

		private static int compileMethodSubscribed = 0;

		private List<Detour> _DetourChain
		{
			get
			{
				if (!_DetourMap.TryGetValue(Method, out var value))
				{
					return null;
				}
				return value;
			}
		}

		public bool IsValid => Index != -1;

		public bool IsApplied { get; private set; }

		private bool IsTop => _TopDetour != null;

		public int Index => _DetourChain?.IndexOf(this) ?? (-1);

		public int MaxIndex => _DetourChain?.Count ?? (-1);

		public uint GlobalIndex => _GlobalIndex;

		public int Priority
		{
			get
			{
				return _Priority;
			}
			set
			{
				if (_Priority != value)
				{
					_Priority = value;
					_RefreshChain(Method);
				}
			}
		}

		public string ID
		{
			get
			{
				return _ID;
			}
			set
			{
				if (string.IsNullOrEmpty(value))
				{
					value = Extensions.GetID(Target, (string)null, (string)null, true, false, true);
				}
				if (!(_ID == value))
				{
					_ID = value;
					_RefreshChain(Method);
				}
			}
		}

		public IEnumerable<string> Before
		{
			get
			{
				return _BeforeRO ?? (_BeforeRO = _Before.AsReadOnly());
			}
			set
			{
				lock (_Before)
				{
					_Before.Clear();
					if (value != null)
					{
						foreach (string item in value)
						{
							_Before.Add(item);
						}
					}
					_RefreshChain(Method);
				}
			}
		}

		public IEnumerable<string> After
		{
			get
			{
				return _AfterRO ?? (_AfterRO = _After.AsReadOnly());
			}
			set
			{
				lock (_After)
				{
					_After.Clear();
					if (value != null)
					{
						foreach (string item in value)
						{
							_After.Add(item);
						}
					}
					_RefreshChain(Method);
				}
			}
		}

		public Detour(MethodBase from, MethodBase to, ref DetourConfig config)
		{
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Expected O, but got Unknown
			from = from.GetIdentifiable();
			if (from.Equals(to))
			{
				throw new ArgumentException("Cannot detour a method to itself!");
			}
			MMDbgLog.Log("detour from " + Extensions.GetID(from, (string)null, (string)null, true, false, false) + " to " + Extensions.GetID(to, (string)null, (string)null, true, false, false));
			Method = from;
			Target = to.Pin();
			TargetReal = DetourHelper.Runtime.GetDetourTarget(from, to);
			_GlobalIndex = _GlobalIndexNext++;
			_Priority = config.Priority;
			_ID = config.ID;
			if (config.Before != null)
			{
				foreach (string item in config.Before)
				{
					_Before.Add(item);
				}
			}
			if (config.After != null)
			{
				foreach (string item2 in config.After)
				{
					_After.Add(item2);
				}
			}
			lock (_BackupMethods)
			{
				if ((!_BackupMethods.TryGetValue(Method, out var value) || (object)value == null) && (object)(value = Method.CreateILCopy()) != null)
				{
					_BackupMethods[Method] = value.Pin();
				}
			}
			ParameterInfo[] parameters = Method.GetParameters();
			Type[] array;
			if (!Method.IsStatic)
			{
				array = new Type[parameters.Length + 1];
				array[0] = Extensions.GetThisParamType(Method);
				for (int i = 0; i < parameters.Length; i++)
				{
					array[i + 1] = parameters[i].ParameterType;
				}
			}
			else
			{
				array = new Type[parameters.Length];
				for (int j = 0; j < parameters.Length; j++)
				{
					array[j] = parameters[j].ParameterType;
				}
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition($"Chain<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", (Method as MethodInfo)?.ReturnType ?? typeof(void), array);
			try
			{
				_ChainedTrampoline = val.StubCriticalDetour().Generate().Pin();
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			List<Detour> value2;
			lock (_DetourMap)
			{
				if (!_DetourMap.TryGetValue(Method, out value2))
				{
					value2 = (_DetourMap[Method] = new List<Detour>());
				}
			}
			lock (value2)
			{
				value2.Add(this);
			}
			if (!config.ManualApply)
			{
				Apply();
			}
		}

		public Detour(MethodBase from, MethodBase to, DetourConfig config)
			: this(from, to, ref config)
		{
		}

		public Detour(MethodBase from, MethodBase to)
			: this(from, to, DetourContext.Current?.DetourConfig ?? default(DetourConfig))
		{
		}

		public Detour(MethodBase method, IntPtr to, ref DetourConfig config)
			: this(method, DetourHelper.GenerateNativeProxy(to, method), ref config)
		{
		}

		public Detour(MethodBase method, IntPtr to, DetourConfig config)
			: this(method, DetourHelper.GenerateNativeProxy(to, method), ref config)
		{
		}

		public Detour(MethodBase method, IntPtr to)
			: this(method, DetourHelper.GenerateNativeProxy(to, method))
		{
		}

		public Detour(Delegate from, IntPtr to, ref DetourConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Detour(Delegate from, IntPtr to, DetourConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Detour(Delegate from, IntPtr to)
			: this(from.Method, to)
		{
		}

		public Detour(Delegate from, Delegate to, ref DetourConfig config)
			: this(from.Method, to.Method, ref config)
		{
		}

		public Detour(Delegate from, Delegate to, DetourConfig config)
			: this(from.Method, to.Method, ref config)
		{
		}

		public Detour(Delegate from, Delegate to)
			: this(from.Method, to.Method)
		{
		}

		public Detour(Expression from, IntPtr to, ref DetourConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Detour(Expression from, IntPtr to, DetourConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Detour(Expression from, IntPtr to)
			: this(((MethodCallExpression)from).Method, to)
		{
		}

		public Detour(Expression from, Expression to, ref DetourConfig config)
			: this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method, ref config)
		{
		}

		public Detour(Expression from, Expression to, DetourConfig config)
			: this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method, ref config)
		{
		}

		public Detour(Expression from, Expression to)
			: this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method)
		{
		}

		public Detour(Expression<Action> from, IntPtr to, ref DetourConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Detour(Expression<Action> from, IntPtr to, DetourConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Detour(Expression<Action> from, IntPtr to)
			: this(from.Body, to)
		{
		}

		public Detour(Expression<Action> from, Expression<Action> to, ref DetourConfig config)
			: this(from.Body, to.Body, ref config)
		{
		}

		public Detour(Expression<Action> from, Expression<Action> to, DetourConfig config)
			: this(from.Body, to.Body, ref config)
		{
		}

		public Detour(Expression<Action> from, Expression<Action> to)
			: this(from.Body, to.Body)
		{
		}

		public void Apply()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("Detour");
			}
			if (!IsApplied)
			{
				Func<Detour, MethodBase, MethodBase, bool> onDetour = OnDetour;
				if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[3] { this, Method, Target }))
				{
					IsApplied = true;
					_RefreshChain(Method);
				}
			}
		}

		public void Undo()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("Detour");
			}
			if (IsApplied)
			{
				Func<Detour, bool> onUndo = OnUndo;
				if (onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this }))
				{
					IsApplied = false;
					_RefreshChain(Method);
				}
			}
		}

		public void Free()
		{
			if (!IsValid)
			{
				return;
			}
			Undo();
			List<Detour> detourChain = _DetourChain;
			lock (detourChain)
			{
				detourChain.Remove(this);
				if (detourChain.Count == 0)
				{
					lock (_BackupMethods)
					{
						if (_BackupMethods.TryGetValue(Method, out var value))
						{
							value.Unpin();
							_BackupMethods.Remove(Method);
						}
					}
					lock (_DetourMap)
					{
						_DetourMap.Remove(Method);
					}
				}
			}
			_ChainedTrampoline.Unpin();
			Target.Unpin();
		}

		public void Dispose()
		{
			if (IsValid)
			{
				Undo();
				Free();
			}
		}

		public MethodBase GenerateTrampoline(MethodBase signature = null)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_00be: 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_00f6: 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)
			Func<Detour, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline;
			MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null);
			if ((object)methodBase != null)
			{
				return methodBase;
			}
			if ((object)signature == null)
			{
				signature = Target;
			}
			Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void);
			ParameterInfo[] parameters = signature.GetParameters();
			Type[] array = new Type[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				array[i] = parameters[i].ParameterType;
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition($"Trampoline<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", type, array);
			try
			{
				ILProcessor iLProcessor = val.GetILProcessor();
				for (int j = 0; j < 32; j++)
				{
					iLProcessor.Emit(OpCodes.Nop);
				}
				for (int k = 0; k < array.Length; k++)
				{
					iLProcessor.Emit(OpCodes.Ldarg, k);
				}
				Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)_ChainedTrampoline);
				iLProcessor.Emit(OpCodes.Ret);
				return val.Generate();
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		public T GenerateTrampoline<T>() where T : Delegate
		{
			if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
			{
				throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
			}
			return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T;
		}

		private void _TopUndo()
		{
			if (_TopDetour != null)
			{
				_TopDetour.Undo();
				_TopDetour.Free();
				_TopDetour = null;
				Method.Unpin();
				TargetReal.Unpin();
			}
		}

		private void _TopApply()
		{
			if (_TopDetour == null)
			{
				_TopDetour = new NativeDetour(Method.Pin().GetNativeStart(), TargetReal.Pin().GetNativeStart());
			}
		}

		private static void _OnCompileMethod(MethodBase method, IntPtr codeStart, ulong codeLen)
		{
			if ((object)method == null)
			{
				return;
			}
			MMDbgLog.Log("compiling: " + Extensions.GetID(method, (string)null, (string)null, true, false, false));
			if (_DetourMap.TryGetValue(method, out var value))
			{
				value.FindLast((Detour d) => d.IsTop)?._TopDetour?.ChangeSource(codeStart);
			}
		}

		private static void _RefreshChain(MethodBase method)
		{
			if (Interlocked.CompareExchange(ref compileMethodSubscribed, 1, 0) == 0)
			{
				DetourHelper.Runtime.OnMethodCompiled += _OnCompileMethod;
			}
			MMDbgLog.Log("detours applying for " + Extensions.GetID(method, (string)null, (string)null, true, false, false));
			List<Detour> list = _DetourMap[method];
			lock (list)
			{
				DetourSorter<Detour>.Sort(list);
				Detour detour = list.FindLast((Detour d) => d.IsTop);
				Detour detour2 = list.FindLast((Detour d) => d.IsApplied);
				if (detour != detour2)
				{
					detour?._TopUndo();
				}
				if (list.Count == 0)
				{
					return;
				}
				MethodBase method2 = _BackupMethods[method];
				foreach (Detour item in list)
				{
					if (item.IsApplied)
					{
						_ = item._ChainedTrampoline;
						using (NativeDetour nativeDetour = new NativeDetour(item._ChainedTrampoline.GetNativeStart(), method2.GetNativeStart()))
						{
							nativeDetour.Free();
						}
						method2 = item.Target;
					}
				}
				if (detour != detour2)
				{
					detour2?._TopApply();
				}
			}
		}
	}
	public class Detour<T> : Detour where T : Delegate
	{
		public Detour(T from, IntPtr to, ref DetourConfig config)
			: base(from, to, ref config)
		{
		}

		public Detour(T from, IntPtr to, DetourConfig config)
			: base(from, to, ref config)
		{
		}

		public Detour(T from, IntPtr to)
			: base(from, to)
		{
		}

		public Detour(T from, T to, ref DetourConfig config)
			: base(from, to, ref config)
		{
		}

		public Detour(T from, T to, DetourConfig config)
			: base(from, to, ref config)
		{
		}

		public Detour(T from, T to)
			: base(from, to)
		{
		}
	}
	public sealed class DetourContext : IDisposable
	{
		[ThreadStatic]
		private static List<DetourContext> _Contexts;

		[ThreadStatic]
		private static DetourContext Last;

		private MethodBase Creator;

		public int Priority;

		private readonly string _FallbackID;

		private string _ID;

		public List<string> Before = new List<string>();

		public List<string> After = new List<string>();

		private bool IsDisposed;

		private static List<DetourContext> Contexts => _Contexts ?? (_Contexts = new List<DetourContext>());

		internal static DetourContext Current
		{
			get
			{
				DetourContext last = Last;
				if (last != null && last.IsValid)
				{
					return Last;
				}
				List<DetourContext> contexts = Contexts;
				int num = contexts.Count - 1;
				while (num > -1)
				{
					DetourContext detourContext = contexts[num];
					if (!detourContext.IsValid)
					{
						contexts.RemoveAt(num);
						num--;
						continue;
					}
					return Last = detourContext;
				}
				return null;
			}
		}

		public string ID
		{
			get
			{
				return _ID ?? _FallbackID;
			}
			set
			{
				_ID = (string.IsNullOrEmpty(value) ? null : value);
			}
		}

		public DetourConfig DetourConfig
		{
			get
			{
				DetourConfig result = default(DetourConfig);
				result.Priority = Priority;
				result.ID = ID;
				result.Before = Before;
				result.After = After;
				return result;
			}
		}

		public HookConfig HookConfig
		{
			get
			{
				HookConfig result = default(HookConfig);
				result.Priority = Priority;
				result.ID = ID;
				result.Before = Before;
				result.After = After;
				return result;
			}
		}

		public ILHookConfig ILHookConfig
		{
			get
			{
				ILHookConfig result = default(ILHookConfig);
				result.Priority = Priority;
				result.ID = ID;
				result.Before = Before;
				result.After = After;
				return result;
			}
		}

		internal bool IsValid
		{
			get
			{
				if (IsDisposed)
				{
					return false;
				}
				if ((object)Creator == null)
				{
					return true;
				}
				StackTrace stackTrace = new StackTrace();
				int frameCount = stackTrace.FrameCount;
				for (int i = 0; i < frameCount; i++)
				{
					if ((object)stackTrace.GetFrame(i).GetMethod() == Creator)
					{
						return true;
					}
				}
				return false;
			}
		}

		public DetourContext(int priority, string id)
		{
			StackTrace stackTrace = new StackTrace();
			int frameCount = stackTrace.FrameCount;
			for (int i = 0; i < frameCount; i++)
			{
				MethodBase method = stackTrace.GetFrame(i).GetMethod();
				if ((object)method?.DeclaringType != typeof(DetourContext))
				{
					Creator = method;
					break;
				}
			}
			object obj = Creator?.DeclaringType?.Assembly?.GetName().Name;
			if (obj == null)
			{
				MethodBase creator = Creator;
				obj = (((object)creator != null) ? Extensions.GetID(creator, (string)null, (string)null, true, false, true) : null);
			}
			_FallbackID = (string)obj;
			Last = this;
			Contexts.Add(this);
			Priority = priority;
			ID = id;
		}

		public DetourContext(string id)
			: this(0, id)
		{
		}

		public DetourContext(int priority)
			: this(priority, null)
		{
		}

		public DetourContext()
			: this(0, null)
		{
		}

		public void Dispose()
		{
			if (IsDisposed)
			{
				IsDisposed = true;
				Last = null;
				Contexts.Remove(this);
			}
		}
	}
	public sealed class DetourModManager : IDisposable
	{
		private readonly Dictionary<IDetour, Assembly> DetourOwners = new Dictionary<IDetour, Assembly>();

		private readonly Dictionary<Assembly, List<IDetour>> OwnedDetourLists = new Dictionary<Assembly, List<IDetour>>();

		public HashSet<Assembly> Ignored = new HashSet<Assembly>();

		private bool Disposed;

		private static readonly string[] HookTypeNames = new string[4] { "MonoMod.RuntimeDetour.NativeDetour", "MonoMod.RuntimeDetour.Detour", "MonoMod.RuntimeDetour.Hook", "MonoMod.RuntimeDetour.ILHook" };

		public event Action<Assembly, MethodBase, Manipulator> OnILHook;

		public event Action<Assembly, MethodBase, MethodBase, object> OnHook;

		public event Action<Assembly, MethodBase, MethodBase> OnDetour;

		public event Action<Assembly, MethodBase, IntPtr, IntPtr> OnNativeDetour;

		public DetourModManager()
		{
			Ignored.Add(typeof(DetourModManager).Assembly);
			ILHook.OnDetour = (Func<ILHook, MethodBase, Manipulator, bool>)Delegate.Combine(ILHook.OnDetour, new Func<ILHook, MethodBase, Manipulator, bool>(RegisterILHook));
			ILHook.OnUndo = (Func<ILHook, bool>)Delegate.Combine(ILHook.OnUndo, new Func<ILHook, bool>(UnregisterDetour));
			Hook.OnDetour = (Func<Hook, MethodBase, MethodBase, object, bool>)Delegate.Combine(Hook.OnDetour, new Func<Hook, MethodBase, MethodBase, object, bool>(RegisterHook));
			Hook.OnUndo = (Func<Hook, bool>)Delegate.Combine(Hook.OnUndo, new Func<Hook, bool>(UnregisterDetour));
			Detour.OnDetour = (Func<Detour, MethodBase, MethodBase, bool>)Delegate.Combine(Detour.OnDetour, new Func<Detour, MethodBase, MethodBase, bool>(RegisterDetour));
			Detour.OnUndo = (Func<Detour, bool>)Delegate.Combine(Detour.OnUndo, new Func<Detour, bool>(UnregisterDetour));
			NativeDetour.OnDetour = (Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>)Delegate.Combine(NativeDetour.OnDetour, new Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>(RegisterNativeDetour));
			NativeDetour.OnUndo = (Func<NativeDetour, bool>)Delegate.Combine(NativeDetour.OnUndo, new Func<NativeDetour, bool>(UnregisterDetour));
		}

		public void Dispose()
		{
			if (!Disposed)
			{
				Disposed = true;
				OwnedDetourLists.Clear();
				ILHook.OnDetour = (Func<ILHook, MethodBase, Manipulator, bool>)Delegate.Remove(ILHook.OnDetour, new Func<ILHook, MethodBase, Manipulator, bool>(RegisterILHook));
				ILHook.OnUndo = (Func<ILHook, bool>)Delegate.Remove(ILHook.OnUndo, new Func<ILHook, bool>(UnregisterDetour));
				Hook.OnDetour = (Func<Hook, MethodBase, MethodBase, object, bool>)Delegate.Remove(Hook.OnDetour, new Func<Hook, MethodBase, MethodBase, object, bool>(RegisterHook));
				Hook.OnUndo = (Func<Hook, bool>)Delegate.Remove(Hook.OnUndo, new Func<Hook, bool>(UnregisterDetour));
				Detour.OnDetour = (Func<Detour, MethodBase, MethodBase, bool>)Delegate.Remove(Detour.OnDetour, new Func<Detour, MethodBase, MethodBase, bool>(RegisterDetour));
				Detour.OnUndo = (Func<Detour, bool>)Delegate.Remove(Detour.OnUndo, new Func<Detour, bool>(UnregisterDetour));
				NativeDetour.OnDetour = (Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>)Delegate.Remove(NativeDetour.OnDetour, new Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>(RegisterNativeDetour));
				NativeDetour.OnUndo = (Func<NativeDetour, bool>)Delegate.Remove(NativeDetour.OnUndo, new Func<NativeDetour, bool>(UnregisterDetour));
			}
		}

		public void Unload(Assembly asm)
		{
			if ((object)asm == null || Ignored.Contains(asm))
			{
				return;
			}
			HookEndpointManager.RemoveAllOwnedBy(asm);
			if (OwnedDetourLists.TryGetValue(asm, out var value))
			{
				IDetour[] array = value.ToArray();
				for (int i = 0; i < array.Length; i++)
				{
					array[i].Dispose();
				}
				if (value.Count > 0)
				{
					throw new Exception("Some detours failed to unregister in " + asm.FullName);
				}
				OwnedDetourLists.Remove(asm);
			}
		}

		internal Assembly GetHookOwner(StackTrace stack = null)
		{
			if (stack == null)
			{
				stack = new StackTrace();
			}
			Assembly assembly = null;
			int frameCount = stack.FrameCount;
			string text = null;
			for (int i = 0; i < frameCount; i++)
			{
				MethodBase method = stack.GetFrame(i).GetMethod();
				if ((object)method?.DeclaringType == null)
				{
					continue;
				}
				string fullName = method.DeclaringType.FullName;
				if (text == null)
				{
					if (HookTypeNames.Contains(fullName))
					{
						text = method.DeclaringType.FullName;
					}
				}
				else if (!(fullName == text))
				{
					assembly = method?.DeclaringType.Assembly;
					break;
				}
			}
			if (Ignored.Contains(assembly))
			{
				return null;
			}
			return assembly;
		}

		internal void TrackDetour(Assembly owner, IDetour detour)
		{
			if (!OwnedDetourLists.TryGetValue(owner, out var value))
			{
				value = (OwnedDetourLists[owner] = new List<IDetour>());
			}
			value.Add(detour);
			DetourOwners[detour] = owner;
		}

		internal bool RegisterILHook(ILHook _detour, MethodBase from, Manipulator manipulator)
		{
			Assembly hookOwner = GetHookOwner();
			if ((object)hookOwner == null)
			{
				return true;
			}
			this.OnILHook?.Invoke(hookOwner, from, manipulator);
			TrackDetour(hookOwner, _detour);
			return true;
		}

		internal bool RegisterHook(Hook _detour, MethodBase from, MethodBase to, object target)
		{
			Assembly hookOwner = GetHookOwner();
			if ((object)hookOwner == null)
			{
				return true;
			}
			this.OnHook?.Invoke(hookOwner, from, to, target);
			TrackDetour(hookOwner, _detour);
			return true;
		}

		internal bool RegisterDetour(Detour _detour, MethodBase from, MethodBase to)
		{
			Assembly hookOwner = GetHookOwner();
			if ((object)hookOwner == null)
			{
				return true;
			}
			this.OnDetour?.Invoke(hookOwner, from, to);
			TrackDetour(hookOwner, _detour);
			return true;
		}

		internal bool RegisterNativeDetour(NativeDetour _detour, MethodBase method, IntPtr from, IntPtr to)
		{
			Assembly hookOwner = GetHookOwner();
			if ((object)hookOwner == null)
			{
				return true;
			}
			this.OnNativeDetour?.Invoke(hookOwner, method, from, to);
			TrackDetour(hookOwner, _detour);
			return true;
		}

		internal bool UnregisterDetour(IDetour _detour)
		{
			if (DetourOwners.TryGetValue(_detour, out var value))
			{
				DetourOwners.Remove(_detour);
				OwnedDetourLists[value].Remove(_detour);
			}
			return true;
		}
	}
	public static class HarmonyDetourBridge
	{
		public enum Type
		{
			Auto,
			Basic,
			AsOriginal,
			Override
		}

		private class DetourToRDAttribute : Attribute
		{
			public string Type { get; }

			public int SkipParams { get; }

			public string Name { get; }

			public DetourToRDAttribute(string type, int skipParams = 0, string name = null)
			{
				Type = type;
				SkipParams = skipParams;
				Name = name;
			}
		}

		private class DetourToHAttribute : Attribute
		{
			public string Type { get; }

			public int SkipParams { get; }

			public string Name { get; }

			public DetourToHAttribute(string type, int skipParams = 0, string name = null)
			{
				Type = type;
				SkipParams = skipParams;
				Name = name;
			}
		}

		private class TranspileAttribute : Attribute
		{
			public string Type { get; }

			public string Name { get; }

			public TranspileAttribute(string type, string name = null)
			{
				Type = type;
				Name = name;
			}
		}

		private class CriticalAttribute : Attribute
		{
		}

		private static Type CurrentType;

		private static Assembly _HarmonyASM;

		private static readonly HashSet<IDisposable> _Detours;

		private static readonly Dictionary<System.Type, MethodInfo> _Emitters;

		[ThreadStatic]
		private static DynamicMethodDefinition _LastWrapperDMD;

		private static Assembly _SharedStateASM;

		private static DetourConfig _DetourConfig;

		public static bool Initialized { get; private set; }

		static HarmonyDetourBridge()
		{
			_Detours = new HashSet<IDisposable>();
			_Emitters = new Dictionary<System.Type, MethodInfo>();
			System.Type typeFromHandle = typeof(OpCode);
			System.Type proxyType = ILGeneratorShim.GetProxyType<CecilILGenerator>();
			MethodInfo[] methods = proxyType.GetMethods();
			foreach (MethodInfo methodInfo in methods)
			{
				if (methodInfo.Name != "Emit")
				{
					continue;
				}
				ParameterInfo[] parameters = methodInfo.GetParameters();
				if (parameters.Length == 2 && (object)parameters[0].ParameterType == typeFromHandle)
				{
					System.Type parameterType = parameters[1].ParameterType;
					if (!_Emitters.ContainsKey(parameterType) || (object)methodInfo.DeclaringType == proxyType)
					{
						_Emitters[parameterType] = methodInfo;
					}
				}
			}
		}

		public static bool Init(bool forceLoad = true, Type type = Type.Auto)
		{
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Expected O, but got Unknown
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Expected O, but got Unknown
			if ((object)_HarmonyASM == null)
			{
				_HarmonyASM = _FindHarmony();
			}
			if ((object)_HarmonyASM == null && forceLoad)
			{
				_HarmonyASM = Assembly.Load(new AssemblyName
				{
					Name = "0Harmony"
				});
			}
			if ((object)_HarmonyASM == null)
			{
				return false;
			}
			if (Initialized)
			{
				return true;
			}
			Initialized = true;
			if (type == Type.Auto)
			{
				type = Type.AsOriginal;
			}
			DetourConfig detourConfig = default(DetourConfig);
			detourConfig.Priority = type switch
			{
				Type.Override => 536870911, 
				Type.AsOriginal => -536870912, 
				_ => 0, 
			};
			_DetourConfig = detourConfig;
			CurrentType = type;
			try
			{
				MethodInfo[] methods = typeof(HarmonyDetourBridge).GetMethods(BindingFlags.Static | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					bool flag = methodInfo.GetCustomAttributes(typeof(CriticalAttribute), inherit: false).Any();
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(DetourToRDAttribute), inherit: false);
					for (int j = 0; j < customAttributes.Length; j++)
					{
						DetourToRDAttribute detourToRDAttribute = (DetourToRDAttribute)customAttributes[j];
						foreach (MethodInfo item in GetHarmonyMethod(methodInfo, detourToRDAttribute.Type, detourToRDAttribute.SkipParams, detourToRDAttribute.Name))
						{
							flag = false;
							_Detours.Add(new Hook(item, methodInfo));
						}
					}
					customAttributes = methodInfo.GetCustomAttributes(typeof(DetourToHAttribute), inherit: false);
					for (int j = 0; j < customAttributes.Length; j++)
					{
						DetourToHAttribute detourToHAttribute = (DetourToHAttribute)customAttributes[j];
						foreach (MethodInfo item2 in GetHarmonyMethod(methodInfo, detourToHAttribute.Type, detourToHAttribute.SkipParams, detourToHAttribute.Name))
						{
							flag = false;
							_Detours.Add(new Detour(methodInfo, item2));
						}
					}
					customAttributes = methodInfo.GetCustomAttributes(typeof(TranspileAttribute), inherit: false);
					for (int j = 0; j < customAttributes.Length; j++)
					{
						TranspileAttribute transpileAttribute = (TranspileAttribute)customAttributes[j];
						foreach (MethodInfo item3 in GetHarmonyMethod(methodInfo, transpileAttribute.Type, -1, transpileAttribute.Name))
						{
							DynamicMethodDefinition val = new DynamicMethodDefinition((MethodBase)item3);
							try
							{
								flag = false;
								ILContext val2 = new ILContext(val.Definition)
								{
									ReferenceBag = (IILReferenceBag)(object)RuntimeILReferenceBag.Instance
								};
								_Detours.Add((IDisposable)val2);
								val2.Invoke(Extensions.CreateDelegate<Manipulator>((MethodBase)methodInfo));
								if (val2.IsReadOnly)
								{
									val2.Dispose();
									_Detours.Remove((IDisposable)val2);
								}
								else
								{
									_Detours.Add(new Detour(item3, val.Generate()));
								}
							}
							finally
							{
								((IDisposable)val)?.Dispose();
							}
						}
					}
					if (flag)
					{
						throw new Exception("Cannot apply HarmonyDetourBridge rule " + methodInfo.Name);
					}
				}
			}
			catch
			{
				_EarlyReset();
				throw;
			}
			return true;
		}

		private static bool _EarlyReset()
		{
			foreach (IDisposable detour in _Detours)
			{
				detour.Dispose();
			}
			_Detours.Clear();
			return false;
		}

		public static void Reset()
		{
			if (Initialized)
			{
				Initialized = false;
				_EarlyReset();
			}
		}

		private static System.Type GetHarmonyType(string typeName)
		{
			return _HarmonyASM.GetType(typeName) ?? _HarmonyASM.GetType("HarmonyLib." + typeName) ?? _HarmonyASM.GetType("Harmony." + typeName) ?? _HarmonyASM.GetType("Harmony.ILCopying." + typeName);
		}

		private static IEnumerable<MethodInfo> GetHarmonyMethod(MethodInfo ctx, string typeName, int skipParams, string name)
		{
			System.Type harmonyType = GetHarmonyType(typeName);
			if ((object)harmonyType == null)
			{
				return null;
			}
			if (string.IsNullOrEmpty(name))
			{
				name = ctx.Name;
			}
			if (skipParams < 0)
			{
				return from method in harmonyType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
					where method.Name == name
					select method;
			}
			return new MethodInfo[1] { harmonyType.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, (from p in ctx.GetParameters().Skip(skipParams)
				select p.ParameterType).ToArray(), null) };
		}

		private static DynamicMethodDefinition CreateDMD(MethodBase original, string suffix)
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			if ((object)original == null)
			{
				throw new ArgumentNullException("original");
			}
			ParameterInfo[] parameters = original.GetParameters();
			System.Type[] array;
			if (!original.IsStatic)
			{
				array = new System.Type[parameters.Length + 1];
				array[0] = Extensions.GetThisParamType(original);
				for (int i = 0; i < parameters.Length; i++)
				{
					array[i + 1] = parameters[i].ParameterType;
				}
			}
			else
			{
				array = new System.Type[parameters.Length];
				for (int j = 0; j < parameters.Length; j++)
				{
					array[j] = parameters[j].ParameterType;
				}
			}
			return new DynamicMethodDefinition(MultiTargetShims.Replace(original.Name + suffix, "<>", "", StringComparison.Ordinal), (original as MethodInfo)?.ReturnType ?? typeof(void), array);
		}

		[DetourToRD("Memory", 0, null)]
		private static long GetMethodStart(MethodBase method, out Exception exception)
		{
			exception = null;
			try
			{
				_Detours.Add((IDisposable)new LazyDisposable<MethodBase>(method, (Action<MethodBase>)delegate(MethodBase m)
				{
					m.Unpin();
				}));
				return (long)method.Pin().GetNativeStart();
			}
			catch (Exception ex)
			{
				exception = ex;
				return 0L;
			}
		}

		[DetourToRD("Memory", 0, null)]
		[Critical]
		private static string WriteJump(long memory, long destination)
		{
			_Detours.Add(new NativeDetour((IntPtr)memory, (IntPtr)destination));
			return null;
		}

		[DetourToRD("Memory", 0, null)]
		[Critical]
		private static string DetourMethod(MethodBase original, MethodBase replacement)
		{
			if ((object)replacement == null)
			{
				replacement = _LastWrapperDMD.Generate();
				_LastWrapperDMD.Dispose();
				_LastWrapperDMD = null;
			}
			_Detours.Add(new Detour(original, replacement, ref _DetourConfig));
			return null;
		}

		[DetourToRD("MethodBodyReader", 1, null)]
		private static MethodInfo EmitMethodForType(object self, System.Type type)
		{
			foreach (KeyValuePair<System.Type, MethodInfo> emitter in _Emitters)
			{
				if ((object)emitter.Key == type)
				{
					return emitter.Value;
				}
			}
			foreach (KeyValuePair<System.Type, MethodInfo> emitter2 in _Emitters)
			{
				if (emitter2.Key.IsAssignableFrom(type))
				{
					return emitter2.Value;
				}
			}
			return null;
		}

		[DetourToRD("PatchProcessor", 2, null)]
		[Critical]
		private static List<DynamicMethod> Patch(Func<object, List<DynamicMethod>> orig, object self)
		{
			orig(self);
			return new List<DynamicMethod>();
		}

		[Transpile("PatchFunctions", null)]
		[Critical]
		private static void UpdateWrapper(ILContext il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(il);
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchThrow(i)
			});
			val.Next.OpCode = OpCodes.Pop;
		}

		[Transpile("MethodPatcher", null)]
		[Critical]
		private static void CreatePatchedMethod(ILContext il)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_0047: 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_014e: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(il);
			System.Type t_DynamicTools = GetHarmonyType("DynamicTools");
			if (!val.TryGotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchCall(i, t_DynamicTools, "CreateDynamicMethod")
			}))
			{
				il.MakeReadOnly();
				return;
			}
			val.Next.OpCode = OpCodes.Call;
			val.Next.Operand = il.Import((MethodBase)typeof(HarmonyDetourBridge).GetMethod("CreateDMD", BindingFlags.Static | BindingFlags.NonPublic));
			int varDMDi = -1;
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchStloc(i, ref varDMDi)
			});
			((VariableReference)il.Body.Variables[varDMDi]).VariableType = il.Import(typeof(DynamicMethodDefinition));
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchCallvirt<DynamicMethod>(i, "GetILGenerator")
			});
			val.Next.OpCode = OpCodes.Call;
			val.Next.Operand = il.Import((MethodBase)typeof(DynamicMethodDefinition).GetMethod("GetILGenerator", BindingFlags.Instance | BindingFlags.Public));
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchCall(i, t_DynamicTools, "PrepareDynamicMethod")
			});
			val.Next.OpCode = OpCodes.Pop;
			val.Next.Operand = null;
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchLdloc(i, varDMDi)
			});
			int index = val.Index;
			val.Index = index + 1;
			val.EmitDelegate<Func<DynamicMethodDefinition, DynamicMethod>>((Func<DynamicMethodDefinition, DynamicMethod>)delegate(DynamicMethodDefinition dmd)
			{
				_LastWrapperDMD = dmd;
				return null;
			});
		}

		[DetourToRD("HarmonySharedState", 1, null)]
		private static Assembly SharedStateAssembly(Func<Assembly> orig)
		{
			//IL_0046: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//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_0085: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			Assembly assembly = orig();
			if ((object)assembly != null)
			{
				return assembly;
			}
			if ((object)_SharedStateASM != null)
			{
				return _SharedStateASM;
			}
			string text = (string)GetHarmonyType("HarmonySharedState").GetField("name", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
			ModuleDefinition val = ModuleDefinition.CreateModule("MonoMod.RuntimeDetour." + text, new ModuleParameters
			{
				Kind = (ModuleKind)0,
				ReflectionImporterProvider = MMReflectionImporter.Provider
			});
			try
			{
				TypeDefinition val2 = new TypeDefinition("", text, (TypeAttributes)385)
				{
					BaseType = val.TypeSystem.Object
				};
				val.Types.Add(val2);
				val2.Fields.Add(new FieldDefinition("state", (FieldAttributes)22, val.ImportReference(typeof(Dictionary<MethodBase, byte[]>))));
				val2.Fields.Add(new FieldDefinition("version", (FieldAttributes)22, val.ImportReference(typeof(int))));
				return _SharedStateASM = ReflectionHelper.Load(val);
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		private static Assembly _FindHarmony()
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (assembly.GetName().Name == "0Harmony" || assembly.GetName().Name == "Harmony" || (object)assembly.GetType("Harmony.HarmonyInstance") != null || (object)assembly.GetType("HarmonyLib.Harmony") != null)
				{
					return assembly;
				}
			}
			object obj = System.Type.GetType("Harmony.HarmonyInstance", throwOnError: false, ignoreCase: false)?.Assembly;
			if (obj == null)
			{
				System.Type? type = System.Type.GetType("HarmonyLib.Harmony", throwOnError: false, ignoreCase: false);
				if ((object)type == null)
				{
					return null;
				}
				obj = type.Assembly;
			}
			return (Assembly)obj;
		}
	}
	public struct HookConfig
	{
		public bool ManualApply;

		public int Priority;

		public string ID;

		public IEnumerable<string> Before;

		public IEnumerable<string> After;
	}
	public class Hook : IDetour, IDisposable
	{
		public static Func<Hook, MethodBase, MethodBase, object, bool> OnDetour;

		public static Func<Hook, bool> OnUndo;

		public static Func<Hook, MethodBase, MethodBase> OnGenerateTrampoline;

		public readonly MethodBase Method;

		public readonly MethodBase Target;

		public readonly MethodBase TargetReal;

		public readonly object DelegateTarget;

		private Detour _Detour;

		private readonly Type _OrigDelegateType;

		private readonly MethodInfo _OrigDelegateInvoke;

		private int? _RefTarget;

		private int? _RefTrampoline;

		private int? _RefTrampolineTmp;

		public bool IsValid => _Detour.IsValid;

		public bool IsApplied => _Detour.IsApplied;

		public Detour Detour => _Detour;

		public Hook(MethodBase from, MethodInfo to, object target, ref HookConfig config)
		{
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Expected O, but got Unknown
			//IL_025b: Expected O, but got Unknown
			//IL_0298: 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_02c5: 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)
			//IL_0377: Expected O, but got Unknown
			//IL_0379: Expected O, but got Unknown
			//IL_0397: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f6: Unknown result type (might be due to invalid IL or missing references)
			from = from.GetIdentifiable();
			Method = from;
			Target = to;
			DelegateTarget = target;
			Type type = (from as MethodInfo)?.ReturnType ?? typeof(void);
			if ((object)to.ReturnType != type && !Extensions.IsCompatible(to.ReturnType, type))
			{
				throw new InvalidOperationException($"Return type of hook for {from} doesn't match, must be {((from as MethodInfo)?.ReturnType ?? typeof(void)).FullName}");
			}
			if (target == null && !to.IsStatic)
			{
				throw new InvalidOperationException($"Hook for method {from} must be static, or you must pass a target instance.");
			}
			ParameterInfo[] parameters = Target.GetParameters();
			ParameterInfo[] parameters2 = Method.GetParameters();
			Type[] array;
			if (!Method.IsStatic)
			{
				array = new Type[parameters2.Length + 1];
				array[0] = Extensions.GetThisParamType(Method);
				for (int i = 0; i < parameters2.Length; i++)
				{
					array[i + 1] = parameters2[i].ParameterType;
				}
			}
			else
			{
				array = new Type[parameters2.Length];
				for (int j = 0; j < parameters2.Length; j++)
				{
					array[j] = parameters2[j].ParameterType;
				}
			}
			Type type2 = null;
			if (parameters.Length == array.Length + 1 && typeof(Delegate).IsAssignableFrom(parameters[0].ParameterType))
			{
				type2 = (_OrigDelegateType = parameters[0].ParameterType);
			}
			else if (parameters.Length != array.Length)
			{
				throw new InvalidOperationException($"Parameter count of hook for {from} doesn't match, must be {array.Length}");
			}
			for (int k = 0; k < array.Length; k++)
			{
				Type type3 = array[k];
				Type parameterType = parameters[k + (((object)type2 != null) ? 1 : 0)].ParameterType;
				if (!Extensions.IsCompatible(type3, parameterType))
				{
					throw new InvalidOperationException($"Parameter #{k} of hook for {from} doesn't match, must be {type3.FullName} or related");
				}
			}
			MethodInfo methodInfo = (_OrigDelegateInvoke = type2?.GetMethod("Invoke"));
			DynamicMethodDefinition val = new DynamicMethodDefinition($"Hook<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", (Method as MethodInfo)?.ReturnType ?? typeof(void), array);
			DynamicMethodDefinition val2 = val;
			DynamicMethodDefinition val3 = val;
			try
			{
				ILProcessor iLProcessor = val2.GetILProcessor();
				if (target != null)
				{
					_RefTarget = DynamicMethodHelper.EmitReference<object>(iLProcessor, target);
				}
				if ((object)type2 != null)
				{
					_RefTrampoline = DynamicMethodHelper.EmitReference<Delegate>(iLProcessor, (Delegate)null);
				}
				for (int l = 0; l < array.Length; l++)
				{
					iLProcessor.Emit(OpCodes.Ldarg, l);
				}
				Extensions.Emit(iLProcessor, OpCodes.Call, Target);
				iLProcessor.Emit(OpCodes.Ret);
				TargetReal = val2.Generate().Pin();
			}
			finally
			{
				((IDisposable)val3)?.Dispose();
			}
			if ((object)type2 != null)
			{
				ParameterInfo[] parameters3 = methodInfo.GetParameters();
				Type[] array2 = new Type[parameters3.Length];
				for (int m = 0; m < parameters3.Length; m++)
				{
					array2[m] = parameters3[m].ParameterType;
				}
				DynamicMethodDefinition val4 = new DynamicMethodDefinition($"Chain:TMP<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", methodInfo?.ReturnType ?? typeof(void), array2);
				val2 = val4;
				val3 = val4;
				try
				{
					ILProcessor iLProcessor = val2.GetILProcessor();
					_RefTrampolineTmp = DynamicMethodHelper.EmitReference<Delegate>(iLProcessor, (Delegate)null);
					iLProcessor.Emit(OpCodes.Brfalse, iLProcessor.Body.Instructions[0]);
					DynamicMethodHelper.EmitGetReference<Delegate>(iLProcessor, _RefTrampolineTmp.Value);
					for (int n = 0; n < array.Length; n++)
					{
						iLProcessor.Emit(OpCodes.Ldarg, n);
					}
					Extensions.Emit(iLProcessor, OpCodes.Callvirt, (MethodBase)methodInfo);
					iLProcessor.Emit(OpCodes.Ret);
					DynamicMethodHelper.SetReference(_RefTrampoline.Value, (object)Extensions.CreateDelegate((MethodBase)val2.Generate(), type2));
				}
				finally
				{
					((IDisposable)val3)?.Dispose();
				}
			}
			_Detour = new Detour(Method, TargetReal, new DetourConfig
			{
				ManualApply = true,
				Priority = config.Priority,
				ID = config.ID,
				Before = config.Before,
				After = config.After
			});
			_UpdateOrig(null);
			if (!config.ManualApply)
			{
				Apply();
			}
		}

		public Hook(MethodBase from, MethodInfo to, object target, HookConfig config)
			: this(from, to, target, ref config)
		{
		}

		public Hook(MethodBase from, MethodInfo to, object target)
			: this(from, to, target, DetourContext.Current?.HookConfig ?? default(HookConfig))
		{
		}

		public Hook(MethodBase from, MethodInfo to, ref HookConfig config)
			: this(from, to, null, ref config)
		{
		}

		public Hook(MethodBase from, MethodInfo to, HookConfig config)
			: this(from, to, null, ref config)
		{
		}

		public Hook(MethodBase from, MethodInfo to)
			: this(from, to, null)
		{
		}

		public Hook(MethodBase method, IntPtr to, ref HookConfig config)
			: this(method, DetourHelper.GenerateNativeProxy(to, method), null, ref config)
		{
		}

		public Hook(MethodBase method, IntPtr to, HookConfig config)
			: this(method, DetourHelper.GenerateNativeProxy(to, method), null, ref config)
		{
		}

		public Hook(MethodBase method, IntPtr to)
			: this(method, DetourHelper.GenerateNativeProxy(to, method), null)
		{
		}

		public Hook(MethodBase method, Delegate to, ref HookConfig config)
			: this(method, to.Method, to.Target, ref config)
		{
		}

		public Hook(MethodBase method, Delegate to, HookConfig config)
			: this(method, to.Method, to.Target, ref config)
		{
		}

		public Hook(MethodBase method, Delegate to)
			: this(method, to.Method, to.Target)
		{
		}

		public Hook(Delegate from, IntPtr to, ref HookConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Hook(Delegate from, IntPtr to, HookConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Hook(Delegate from, IntPtr to)
			: this(from.Method, to)
		{
		}

		public Hook(Delegate from, Delegate to, ref HookConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Hook(Delegate from, Delegate to, HookConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Hook(Delegate from, Delegate to)
			: this(from.Method, to)
		{
		}

		public Hook(Expression from, IntPtr to, ref HookConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Hook(Expression from, IntPtr to, HookConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Hook(Expression from, IntPtr to)
			: this(((MethodCallExpression)from).Method, to)
		{
		}

		public Hook(Expression from, Delegate to, ref HookConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Hook(Expression from, Delegate to, HookConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Hook(Expression from, Delegate to)
			: this(((MethodCallExpression)from).Method, to)
		{
		}

		public Hook(Expression<Action> from, IntPtr to, ref HookConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Action> from, IntPtr to, HookConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Action> from, IntPtr to)
			: this(from.Body, to)
		{
		}

		public Hook(Expression<Action> from, Delegate to, ref HookConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Action> from, Delegate to, HookConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Action> from, Delegate to)
			: this(from.Body, to)
		{
		}

		public void Apply()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("Hook");
			}
			if (!IsApplied)
			{
				Func<Hook, MethodBase, MethodBase, object, bool> onDetour = OnDetour;
				if (onDetour != null && !Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[4] { this, Method, Target, DelegateTarget }))
				{
					return;
				}
			}
			_Detour.Apply();
		}

		public void Undo()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("Hook");
			}
			if (IsApplied)
			{
				Func<Hook, bool> onUndo = OnUndo;
				if (onUndo != null && !Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this }))
				{
					return;
				}
			}
			_Detour.Undo();
			if (!IsValid)
			{
				_Free();
			}
		}

		public void Free()
		{
			if (IsValid)
			{
				_Detour.Free();
				_Free();
			}
		}

		public void Dispose()
		{
			if (IsValid)
			{
				Undo();
				Free();
			}
		}

		private void _Free()
		{
			if (_RefTarget.HasValue)
			{
				DynamicMethodHelper.FreeReference(_RefTarget.Value);
			}
			if (_RefTrampoline.HasValue)
			{
				DynamicMethodHelper.FreeReference(_RefTrampoline.Value);
			}
			if (_RefTrampolineTmp.HasValue)
			{
				DynamicMethodHelper.FreeReference(_RefTrampolineTmp.Value);
			}
			TargetReal.Unpin();
		}

		public MethodBase GenerateTrampoline(MethodBase signature = null)
		{
			Func<Hook, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline;
			MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null);
			if ((object)methodBase != null)
			{
				return methodBase;
			}
			return _Detour.GenerateTrampoline(signature);
		}

		public T GenerateTrampoline<T>() where T : Delegate
		{
			if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
			{
				throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
			}
			return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T;
		}

		internal void _UpdateOrig(MethodBase invoke)
		{
			if ((object)_OrigDelegateType != null)
			{
				Delegate @delegate = Extensions.CreateDelegate(invoke ?? GenerateTrampoline(_OrigDelegateInvoke), _OrigDelegateType);
				DynamicMethodHelper.SetReference(_RefTrampoline.Value, (object)@delegate);
				DynamicMethodHelper.SetReference(_RefTrampolineTmp.Value, (object)@delegate);
			}
		}
	}
	public class Hook<T> : Hook
	{
		public Hook(Expression<Action> from, T to, ref HookConfig config)
			: base(from.Body, to as Delegate, ref config)
		{
		}

		public Hook(Expression<Action> from, T to, HookConfig config)
			: base(from.Body, to as Delegate, ref config)
		{
		}

		public Hook(Expression<Action> from, T to)
			: base(from.Body, to as Delegate)
		{
		}

		public Hook(Expression<Func<T>> from, IntPtr to, ref HookConfig config)
			: base(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Func<T>> from, IntPtr to, HookConfig config)
			: base(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Func<T>> from, IntPtr to)
			: base(from.Body, to)
		{
		}

		public Hook(Expression<Func<T>> from, Delegate to, ref HookConfig config)
			: base(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Func<T>> from, Delegate to, HookConfig config)
			: base(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Func<T>> from, Delegate to)
			: base(from.Body, to)
		{
		}

		public Hook(T from, IntPtr to, ref HookConfig config)
			: base(from as Delegate, to, ref config)
		{
		}

		public Hook(T from, IntPtr to, HookConfig config)
			: base(from as Delegate, to, ref config)
		{
		}

		public Hook(T from, IntPtr to)
			: base(from as Delegate, to)
		{
		}

		public Hook(T from, T to, ref HookConfig config)
			: base(from as Delegate, to as Delegate, ref config)
		{
		}

		public Hook(T from, T to, HookConfig config)
			: base(from as Delegate, to as Delegate, ref config)
		{
		}

		public Hook(T from, T to)
			: base(from as Delegate, to as Delegate)
		{
		}
	}
	public class Hook<TFrom, TTo> : Hook
	{
		public Hook(Expression<Func<TFrom>> from, TTo to, ref HookConfig config)
			: base(from.Body, to as Delegate)
		{
		}

		public Hook(Expression<Func<TFrom>> from, TTo to, HookConfig config)
			: base(from.Body, to as Delegate)
		{
		}

		public Hook(Expression<Func<TFrom>> from, TTo to)
			: base(from.Body, to as Delegate)
		{
		}

		public Hook(TFrom from, TTo to, ref HookConfig config)
			: base(from as Delegate, to as Delegate)
		{
		}

		public Hook(TFrom from, TTo to, HookConfig config)
			: base(from as Delegate, to as Delegate)
		{
		}

		public Hook(TFrom from, TTo to)
			: base(from as Delegate, to as Delegate)
		{
		}
	}
	public interface IDetour : IDisposable
	{
		bool IsValid { get; }

		bool IsApplied { get; }

		void Apply();

		void Undo();

		void Free();

		MethodBase GenerateTrampoline(MethodBase signature = null);

		T GenerateTrampoline<T>() where T : Delegate;
	}
	public interface ISortableDetour : IDetour, IDisposable
	{
		uint GlobalIndex { get; }

		int Priority { get; set; }

		string ID { get; set; }

		IEnumerable<string> Before { get; set; }

		IEnumerable<string> After { get; set; }
	}
	public struct ILHookConfig
	{
		public bool ManualApply;

		public int Priority;

		public string ID;

		public IEnumerable<string> Before;

		public IEnumerable<string> After;
	}
	public class ILHook : ISortableDetour, IDetour, IDisposable
	{
		private class Context
		{
			public List<ILHook> Chain = new List<ILHook>();

			public HashSet<ILContext> Active = new HashSet<ILContext>();

			public MethodBase Method;

			public Detour Detour;

			public Context(MethodBase method)
			{
				Method = method;
			}

			public void Add(ILHook hook)
			{
				List<ILHook> chain = Chain;
				lock (chain)
				{
					chain.Add(hook);
				}
			}

			public void Remove(ILHook hook)
			{
				List<ILHook> chain = Chain;
				lock (chain)
				{
					chain.Remove(hook);
					if (chain.Count == 0)
					{
						Refresh();
						lock (_Map)
						{
							_Map.Remove(Method);
							return;
						}
					}
				}
			}

			public void Refresh()
			{
				//IL_00be: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c5: Expected O, but got Unknown
				List<ILHook> chain = Chain;
				lock (chain)
				{
					foreach (ILContext item in Active)
					{
						item.Dispose();
					}
					Active.Clear();
					Detour?.Dispose();
					Detour = null;
					if (chain.Count == 0)
					{
						return;
					}
					bool flag = false;
					foreach (ILHook item2 in chain)
					{
						if (item2.IsApplied)
						{
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						return;
					}
					DetourSorter<ILHook>.Sort(chain);
					DynamicMethodDefinition val = new DynamicMethodDefinition(Method);
					MethodBase to;
					try
					{
						MethodDefinition definition = val.Definition;
						foreach (ILHook item3 in chain)
						{
							if (item3.IsApplied)
							{
								InvokeManipulator(definition, item3.Manipulator);
							}
						}
						to = val.Generate();
					}
					finally
					{
						((IDisposable)val)?.Dispose();
					}
					Detour = new Detour(Method, to, ref ILDetourConfig);
				}
			}

			private void InvokeManipulator(MethodDefinition def, Manipulator cb)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				ILContext val = new ILContext(def);
				val.ReferenceBag = (IILReferenceBag)(object)RuntimeILReferenceBag.Instance;
				val.Invoke(cb);
				if (val.IsReadOnly)
				{
					val.Dispose();
					return;
				}
				val.MakeReadOnly();
				Active.Add(val);
			}
		}

		public static Func<ILHook, MethodBase, Manipulator, bool> OnDetour;

		public static Func<ILHook, bool> OnUndo;

		private static DetourConfig ILDetourConfig = new DetourConfig
		{
			Priority = -268435456,
			Before = new string[1] { "*" }
		};

		private static Dictionary<MethodBase, Context> _Map = new Dictionary<MethodBase, Context>();

		private static uint _GlobalIndexNext = 0u;

		private readonly uint _GlobalIndex;

		private int _Priority;

		private string _ID;

		private List<string> _Before = new List<string>();

		private ReadOnlyCollection<string> _BeforeRO;

		private List<string> _After = new List<string>();

		private ReadOnlyCollection<string> _AfterRO;

		public readonly MethodBase Method;

		public readonly Manipulator Manipulator;

		private Context _Ctx
		{
			get
			{
				if (!_Map.TryGetValue(Method, out var value))
				{
					return null;
				}
				return value;
			}
		}

		public bool IsValid => Index != -1;

		public bool IsApplied { get; private set; }

		public int Index => _Ctx?.Chain.IndexOf(this) ?? (-1);

		public int MaxIndex => _Ctx?.Chain.Count ?? (-1);

		public uint GlobalIndex => _GlobalIndex;

		public int Priority
		{
			get
			{
				return _Priority;
			}
			set
			{
				if (_Priority != value)
				{
					_Priority = value;
					_Ctx.Refresh();
				}
			}
		}

		public string ID
		{
			get
			{
				return _ID;
			}
			set
			{
				if (string.IsNullOrEmpty(value))
				{
					MethodInfo method = ((Delegate)(object)Manipulator).Method;
					value = (((object)method != null) ? Extensions.GetID((MethodBase)method, (string)null, (string)null, true, false, true) : null) ?? GetHashCode().ToString(CultureInfo.InvariantCulture);
				}
				if (!(_ID == value))
				{
					_ID = value;
					_Ctx.Refresh();
				}
			}
		}

		public IEnumerable<string> Before
		{
			get
			{
				return _BeforeRO ?? (_BeforeRO = _Before.AsReadOnly());
			}
			set
			{
				lock (_Before)
				{
					_Before.Clear();
					if (value != null)
					{
						foreach (string item in value)
						{
							_Before.Add(item);
						}
					}
					_Ctx.Refresh();
				}
			}
		}

		public IEnumerable<string> After
		{
			get
			{
				return _AfterRO ?? (_AfterRO = _After.AsReadOnly());
			}
			set
			{
				lock (_After)
				{
					_After.Clear();
					if (value != null)
					{
						foreach (string item in value)
						{
							_After.Add(item);
						}
					}
					_Ctx.Refresh();
				}
			}
		}

		public ILHook(MethodBase from, Manipulator manipulator, ref ILHookConfig config)
		{
			from = from.GetIdentifiable();
			Method = from.Pin();
			Manipulator = manipulator;
			_GlobalIndex = _GlobalIndexNext++;
			_Priority = config.Priority;
			_ID = config.ID;
			if (config.Before != null)
			{
				foreach (string item in config.Before)
				{
					_Before.Add(item);
				}
			}
			if (config.After != null)
			{
				foreach (string item2 in config.After)
				{
					_After.Add(item2);
				}
			}
			Context value;
			lock (_Map)
			{
				if (!_Map.TryGetValue(Method, out value))
				{
					value = (_Map[Method] = new Context(Method));
				}
			}
			lock (value)
			{
				value.Add(this);
			}
			if (!config.ManualApply)
			{
				Apply();
			}
		}

		public ILHook(MethodBase from, Manipulator manipulator, ILHookConfig config)
			: this(from, manipulator, ref config)
		{
		}

		public ILHook(MethodBase from, Manipulator manipulator)
			: this(from, manipulator, DetourContext.Current?.ILHookConfig ?? default(ILHookConfig))
		{
		}

		public void Apply()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("ILHook");
			}
			if (!IsApplied)
			{
				Func<ILHook, MethodBase, Manipulator, bool> onDetour = OnDetour;
				if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[3] { this, Method, Manipulator }))
				{
					IsApplied = true;
					_Ctx.Refresh();
				}
			}
		}

		public void Undo()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("ILHook");
			}
			if (IsApplied)
			{
				Func<ILHook, bool> onUndo = OnUndo;
				if (onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this }))
				{
					IsApplied = false;
					_Ctx.Refresh();
				}
			}
		}

		public void Free()
		{
			if (IsValid)
			{
				Undo();
				_Ctx.Remove(this);
				Method.Unpin();
			}
		}

		public void Dispose()
		{
			if (IsValid)
			{
				Undo();
				Free();
			}
		}

		public MethodBase GenerateTrampoline(MethodBase signature = null)
		{
			throw new NotSupportedException();
		}

		public T GenerateTrampoline<T>() where T : Delegate
		{
			throw new NotSupportedException();
		}
	}
	public struct NativeDetourConfig
	{
		public bool ManualApply;

		public bool SkipILCopy;
	}
	public class NativeDetour : IDetour, IDisposable
	{
		public static Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool> OnDetour;

		public static Func<NativeDetour, bool> OnUndo;

		public static Func<NativeDetour, MethodBase, MethodBase> OnGenerateTrampoline;

		private NativeDetourData _Data;

		public readonly MethodBase Method;

		private readonly MethodInfo _BackupMethod;

		private readonly IntPtr _BackupNative;

		private HashSet<MethodBase> _Pinned = new HashSet<MethodBase>();

		public bool IsValid { get; private set; }

		public bool IsApplied { get; private set; }

		public NativeDetourData Data => _Data;

		public NativeDetour(MethodBase method, IntPtr from, IntPtr to, ref NativeDetourConfig config)
		{
			if (from == to)
			{
				throw new InvalidOperationException($"Cannot detour from a location to itself! (from: {from:X16} to: {to:X16} method: {method})");
			}
			method = method?.GetIdentifiable();
			Method = method;
			Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool> onDetour = OnDetour;
			if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[4] { this, method, from, to }))
			{
				IsValid = true;
				_Data = DetourHelper.Native.Create(from, to);
				if (!config.SkipILCopy)
				{
					method?.TryCreateILCopy(out _BackupMethod);
				}
				_BackupNative = DetourHelper.Native.MemAlloc(_Data.Size);
				if (!config.ManualApply)
				{
					Apply();
				}
			}
		}

		public NativeDetour(MethodBase method, IntPtr from, IntPtr to, NativeDetourConfig config)
			: this(method, from, to, ref config)
		{
		}

		public NativeDetour(MethodBase method, IntPtr from, IntPtr to)
			: this(method, from, to, default(NativeDetourConfig))
		{
		}

		public NativeDetour(IntPtr from, IntPtr to, ref NativeDetourConfig config)
			: this(null, from, to, ref config)
		{
		}

		public NativeDetour(IntPtr from, IntPtr to, NativeDetourConfig config)
			: this(null, from, to, ref config)
		{
		}

		public NativeDetour(IntPtr from, IntPtr to)
			: this(null, from, to)
		{
		}

		public NativeDetour(MethodBase from, IntPtr to, ref NativeDetourConfig config)
			: this(from, from.Pin().GetNativeStart(), to, ref config)
		{
			_Pinned.Add(from);
		}

		public NativeDetour(MethodBase from, IntPtr to, NativeDetourConfig config)
			: this(from, from.Pin().GetNativeStart(), to, ref config)
		{
			_Pinned.Add(from);
		}

		public NativeDetour(MethodBase from, IntPtr to)
			: this(from, from.Pin().GetNativeStart(), to)
		{
			_Pinned.Add(from);
		}

		public NativeDetour(IntPtr from, MethodBase to, ref NativeDetourConfig config)
			: this(from, to.Pin().GetNativeStart(), ref config)
		{
			_Pinned.Add(to);
		}

		public NativeDetour(IntPtr from, MethodBase to, NativeDetourConfig config)
			: this(from, to.Pin().GetNativeStart(), ref config)
		{
			_Pinned.Add(to);
		}

		public NativeDetour(IntPtr from, MethodBase to)
			: this(from, to.Pin().GetNativeStart())
		{
			_Pinned.Add(to);
		}

		public NativeDetour(MethodBase from, MethodBase to, ref NativeDetourConfig config)
			: this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to), ref config)
		{
			_Pinned.Add(from);
		}

		public NativeDetour(MethodBase from, MethodBase to, NativeDetourConfig config)
			: this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to), ref config)
		{
			_Pinned.Add(from);
		}

		public NativeDetour(MethodBase from, MethodBase to)
			: this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to))
		{
			_Pinned.Add(from);
		}

		public NativeDetour(Delegate from, IntPtr to, ref NativeDetourConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public NativeDetour(Delegate from, IntPtr to, NativeDetourConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public NativeDetour(Delegate from, IntPtr to)
			: this(from.Method, to)
		{
		}

		public NativeDetour(IntPtr from, Delegate to, ref NativeDetourConfig config)
			: this(from, to.Method, ref config)
		{
		}

		public NativeDetour(IntPtr from, Delegate to, NativeDetourConfig config)
			: this(from, to.Method, ref config)
		{
		}

		public NativeDetour(IntPtr from, Delegate to)
			: this(from, to.Method)
		{
		}

		public NativeDetour(Delegate from, Delegate to, ref NativeDetourConfig config)
			: this(from.Method, to.Method, ref config)
		{
		}

		public NativeDetour(Delegate from, Delegate to, NativeDetourConfig config)
			: this(from.Method, to.Method, ref config)
		{
		}

		public NativeDetour(Delegate from, Delegate to)
			: this(from.Method, to.Method)
		{
		}

		public void Apply()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("NativeDetour");
			}
			if (!IsApplied)
			{
				IsApplied = true;
				DetourHelper.Native.Copy(_Data.Method, _BackupNative, _Data.Type);
				DetourHelper.Native.MakeWritable(_Data);
				DetourHelper.Native.Apply(_Data);
				DetourHelper.Native.MakeExecutable(_Data);
				DetourHelper.Native.FlushICache(_Data);
			}
		}

		public void Undo()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("NativeDetour");
			}
			Func<NativeDetour, bool> onUndo = OnUndo;
			if ((onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this })) && IsApplied)
			{
				IsApplied = false;
				DetourHelper.Native.MakeWritable(_Data);
				DetourHelper.Native.Copy(_BackupNative, _Data.Method, _Data.Type);
				DetourHelper.Native.MakeExecutable(_Data);
				DetourHelper.Native.FlushICache(_Data);
			}
		}

		public void ChangeSource(IntPtr newSource)
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("NativeDetour");
			}
			NativeDetourData data = _Data;
			_Data = DetourHelper.Native.Create(newSource, _Data.Target);
			IsApplied = false;
			Apply();
			DetourHelper.Native.Free(data);
		}

		public void ChangeTarget(IntPtr newTarget)
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("NativeDetour");
			}
			NativeDetourData data = _Data;
			_Data = DetourHelper.Native.Create(_Data.Method, newTarget);
			IsApplied = false;
			Apply();
			DetourHelper.Native.Free(data);
		}

		public void Free()
		{
			if (!IsValid)
			{
				return;
			}
			IsValid = false;
			DetourHelper.Native.MemFree(_BackupNative);
			DetourHelper.Native.Free(_Data);
			if (IsApplied)
			{
				return;
			}
			foreach (MethodBase item in _Pinned)
			{
				item.Unpin();
			}
			_Pinned.Clear();
		}

		public void Dispose()
		{
			if (IsValid)
			{
				Undo();
				Free();
			}
		}

		public MethodBase GenerateTrampoline(MethodBase signature = null)
		{
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Expected O, but got Unknown
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Expected O, but got Unknown
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Expected O, but got Unknown
			//IL_0198: Expected O, but got Unknown
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: 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_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			Func<NativeDetour, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline;
			MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null);
			if ((object)methodBase != null)
			{
				return methodBase;
			}
			if (!IsValid)
			{
				throw new ObjectDisposedException("NativeDetour");
			}
			if ((object)_BackupMethod != null)
			{
				return _BackupMethod;
			}
			if ((object)signature == null)
			{
				throw new ArgumentNullException("A signature must be given if the NativeDetour doesn't hold a reference to a managed method.");
			}
			MethodBase methodBase2 = Method;
			if ((object)methodBase2 == null)
			{
				methodBase2 = DetourHelper.GenerateNativeProxy(_Data.Method, signature);
			}
			Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void);
			ParameterInfo[] parameters = signature.GetParameters();
			Type[] array = new Type[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				array[i] = parameters[i].ParameterType;
			}
			MethodBase method = Method;
			DynamicMethodDefinition val = new DynamicMethodDefinition(string.Format("Trampoline:Native<{0}>?{1}", (((object)method != null) ? Extensions.GetID(method, (string)null, (string)null, true, false, true) : null) ?? ((long)_Data.Method).ToString("X16", CultureInfo.InvariantCulture), GetHashCode()), type, array);
			try
			{
				ILProcessor iLProcessor = val.GetILProcessor();
				ExceptionHandler val2 = new ExceptionHandler((ExceptionHandlerType)2);
				iLProcessor.Body.ExceptionHandlers.Add(val2);
				iLProcessor.EmitDetourCopy(_BackupNative, _Data.Method, _Data.Type);
				VariableDefinition val3 = null;
				if ((object)type != typeof(void))
				{
					Collection<VariableDefinition> variables = iLProcessor.Body.Variables;
					VariableDefinition val4 = new VariableDefinition(Extensions.Import(iLProcessor, type));
					val3 = val4;
					variables.Add(val4);
				}
				int count = iLProcessor.Body.Instructions.Count;
				for (int j = 0; j < array.Length; j++)
				{
					iLProcessor.Emit(OpCodes.Ldarg, j);
				}
				if (methodBase2 is MethodInfo)
				{
					Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)(MethodInfo)methodBase2);
				}
				else
				{
					if (!(methodBase2 is ConstructorInfo))
					{
						throw new NotSupportedException("Method type " + methodBase2.GetType().FullName + " not supported.");
					}
					Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)(ConstructorInfo)methodBase2);
				}
				if (val3 != null)
				{
					iLProcessor.Emit(OpCodes.Stloc, val3);
				}
				Extensions.Emit(iLProcessor, OpCodes.Leave, (object)null);
				Instruction obj = iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1];
				int count2 = iLProcessor.Body.Instructions.Count;
				_ = iLProcessor.Body.Instructions.Count;
				iLProcessor.EmitDetourApply(_Data);
				int count3 = iLProcessor.Body.Instructions.Count;
				Instruction val5 = null;
				if (val3 != null)
				{
					iLProcessor.Emit(OpCodes.Ldloc, val3);
					val5 = iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1];
				}
				iLProcessor.Emit(OpCodes.Ret);
				val5 = val5 ?? iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1];
				obj.Operand = val5;
				val2.TryStart = iLProcessor.Body.Instructions[count];
				val2.TryEnd = iLProcessor.Body.Instructions[count2];
				val2.HandlerStart = iLProcessor.Body.Instructions[count2];
				val2.HandlerEnd = iLProcessor.Body.Instructions[count3];
				return val.Generate();
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		public T GenerateTrampoline<T>() where T : Delegate
		{
			if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
			{
				throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
			}
			return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T;
		}
	}
	internal static class DetourSorter<T> where T : ISortableDetour
	{
		private sealed class Group
		{
			public readonly string StepName;

			public List<T> Items = new List<T>();

			public List<Group> Children = new List<Group>();

			public List<Group> NonMatching = new List<Group>();

			public Group(string stepName)
			{
				StepName = stepName;
			}

			public Group(string stepName, List<T> items)
				: this(stepName)
			{
				Items.AddRange(items);
			}

			public void Step(Step step)
			{
				if (Children.Count != 0)
				{
					foreach (Group child in Children)
					{
						child.Step(step);
					}
					return;
				}
				if (Items.Count <= 1)
				{
					return;
				}
				if ((Items.Count == 2 && !((!step.IsFlat) ?? false)) || step.IsFlat.GetValueOrDefault())
				{
					Items.Sort(step);
					return;
				}
				string name = step.GetType().Name;
				Group group = new Group(name, new List<T> { Items[0] });
				Children.Add(group);
				for (int i = 1; i < Items.Count; i++)
				{
					T val = Items[i];
					if (step.Any(group.Items, val))
					{
						Group group2 = group;
						group = null;
						if (Children.Count > 1)
						{
							foreach (Group child2 in Children)
							{
								if (child2 != group2 && !step.Any(child2.Items, val) && !step.Any(child2.NonMatching, val))
								{
									group = child2;
									break;
								}
							}
						}
						if (group == null)
						{
							group = new Group(name);
							Children.Add(group);
							group.NonMatching.Add(group2);
							group2.NonMatching.Add(group);
						}
					}
					group.Items.Add(val);
				}
				if (Children.Count == 1)
				{
					Children.Clear();
				}
				else
				{
					Children.Sort(step.ForGroup);
				}
			}

			public void Flatten()
			{
				if (Children.Count != 0)
				{
					Items.Clear();
					Flatten(Items);
				}
			}

			public void Flatten(List<T> total)
			{
				if (Children.Count == 0)
				{
					total.AddRange(Items);
					return;
				}
				foreach (Group child in Children)
				{
					child.Flatten(total);
				}
			}
		}

		private abstract class Step : IComparer<T>
		{
			public abstract GroupComparer ForGroup { get; }

			public virtual bool? IsFlat => null;

			public abstract int Compare(T x, T y);

			public bool Any(List<T> xlist, T y)
			{
				foreach (T item in xlist)
				{
					if (Compare(item, y) != 0)
					{
						return true;
					}
				}
				return false;
			}

			public bool Any(List<Group> groups, T y)
			{
				foreach (Group group in groups)
				{
					if (Any(group.Items, y))
					{
						return true;
					}
				}
				return false;
			}
		}

		private sealed class GroupComparer : IComparer<Group>
		{
			public Step Step;

			public GroupComparer(Step step)
			{
				Step = step;
			}

			public int Compare(Group xg, Group yg)
			{
				foreach (T item in xg.Items)
				{
					foreach (T item2 in yg.Items)
					{
						int result;
						if ((result = Step.Compare(item, item2)) != 0)
						{
							return result;
						}
					}
				}
				return 0;
			}
		}

		private sealed class BeforeAfterAll : Step
		{
			public static readonly BeforeAfterAll _ = new BeforeAfterAll();

			public static readonly GroupComparer Group = new GroupComparer(_);

			public override GroupComparer ForGroup => Group;

			public override bool? IsFlat => false;

			public override int Compare(T a, T b)
			{
				if (a.Before.Contains("*") && !b.Before.Contains("*"))
				{
					return -1;
				}
				if (!a.Before.Contains("*") && b.Before.Contains("*"))
				{
					return 1;
				}
				if (a.After.Contains("*") && !b.After.Contains("*"))
				{
					return 1;
				}
				if (!a.After.Contains("*") && b.After.Contains("*"))
				{
					return -1;
				}
				return 0;
			}
		}

		private sealed class BeforeAfter : Step
		{
			public static readonly BeforeAfter _ = new BeforeAfter();

			public static readonly GroupComparer Group = new GroupComparer(_);

			public override GroupComparer ForGroup => Group;

			public override int Compare(T a, T b)
			{
				if (a.Before.Contains(b.ID))
				{
					return -1;
				}
				if (a.After.Contains(b.ID))
				{
					return 1;
				}
				if (b.Before.Contains(a.ID))
				{
					return 1;
				}
				if (b.After.Contains(a.ID))
				{
					return -1;
				}
				return 0;
			}
		}

		private sealed class Priority : Step
		{
			public static readonly Priority _ = new Priority();

			public static readonly GroupComparer Group = new GroupComparer(_);

			public override GroupComparer ForGroup => Group;

			public override int Compare(T a, T b)
			{
				int num = a.Priority - b.Priority;
				if (num != 0)
				{
					return num;
				}
				return 0;
			}
		}

		private sealed class GlobalIndex : Step
		{
			public static readonly GlobalIndex _ = new GlobalIndex();

			public static readonly GroupComparer Group = new GroupComparer(_);

			public override GroupComparer ForGroup => Group;

			public override int Compare(T a, T b)
			{
				return a.GlobalIndex.CompareTo(b.GlobalIndex);
			}
		}

		public static void Sort(List<T> detours)
		{
			lock (detours)
			{
				if (detours.Count > 1)
				{
					detours.Sort(GlobalIndex._);
					Group group = new Group("Init", detours);
					group.Step(BeforeAfterAll._);
					group.Step(BeforeAfter._);
					group.Step(Priority._);
					group.Step(GlobalIndex._);
					detours.Clear();
					group.Flatten(detours);
				}
			}
		}
	}
	public static class DetourHelper
	{
		private static readonly object _RuntimeLock = new object();

		private static bool _RuntimeInit = false;

		private static IDetourRuntimePlatform _Runtime;

		private static readonly object _NativeLock = new object();

		private static bool _NativeInit = false;

		private static IDetourNativePlatform _Native;

		private static readonly FieldInfo _f_Native = typeof(DetourHelper).GetField("_Native", BindingFlags.Static | BindingFlags.NonPublic);

		private static readonly MethodInfo _m_ToNativeDetourData = typeof(DetourHelper).GetMethod("ToNativeDetourData", BindingFlags.Static | BindingFlags.NonPublic);

		private static readonly MethodInfo _m_Copy = typeof(IDetourNativePlatform).GetMethod("Copy");

		private static readonly MethodInfo _m_Apply = typeof(IDetourNativePlatform).GetMethod("Apply");

		private static readonly ConstructorInfo _ctor_Exception = typeof(Exception).GetConstructor(new Type[1] { typeof(string) });

		public static IDetourRuntimePlatform Runtime
		{
			get
			{
				if (_Runtime != null)
				{
					return _Runtime;
				}
				lock (_RuntimeLock)
				{
					if (_Runtime != null)
					{
						return _Runtime;
					}
					if (_RuntimeInit)
					{
						return null;
					}
					_RuntimeInit = true;
					if ((object)Type.GetType("Mono.Runtime") != null)
					{
						_Runtime = new DetourRuntimeMonoPlatform();
					}
					else if (typeof(object).Assembly.GetName().Name == "System.Private.CoreLib")
					{
						_Runtime = DetourRuntimeNETCorePlatform.Create();
					}
					else
					{
						_Runtime = new DetourRuntimeNETPlatform();
					}
					return _Runtime;
				}
			}
			set
			{
				_Runtime = value;
			}
		}

		public static IDetourNativePlatform Native
		{
			get
			{
				if (_Native != null)
				{
					return _Native;
				}
				lock (_NativeLock)
				{
					if (_Native != null)
					{
						return _Native;
					}
					if (_NativeInit)
					{
						return null;
					}
					_NativeInit = true;
					IDetourNativePlatform detourNativePlatform = ((!PlatformHelper.Is((Platform)65536)) ? ((IDetourNativePlatform)new DetourNativeX86Platform()) : ((IDetourNativePlatform)new DetourNativeARMPlatform()));
					if (PlatformHelper.Is((Platform)37))
					{
						return _Native = new DetourNativeWindowsPlatform(detourNativePlatform);
					}
					if ((object)Type.GetType("Mono.Runtime") != null)
					{
						try
						{
							return _Native = new DetourNativeMonoPlatform(detourNativePlatform, "libmonosgen-2.0." + PlatformHelper.LibrarySuffix);
						}
						catch
						{
						}
					}
					string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_RUNTIMEDETOUR_MONOPOSIXHELPER");
					if (((object)Type.GetType("Mono.Runtime") != null && environmentVariable != "0") || environmentVariable == "1")
					{
						try
						{
							return _Native = new DetourNativeMonoPosixPlatform(detourNativePlatform);
						}
						catch
						{
						}
					}
					try
					{
						return _Native = new DetourNativeLibcPlatform(detourNativePlatform);
					}
					catch
					{
					}
					return detourNativePlatform;
				}
			}
			set
			{
				_Native = value;
			}
		}

		public static void MakeWritable(this IDetourNativePlatform plat, NativeDetourData detour)
		{
			plat.MakeWritable(detour.Method, detour.Size);
		}

		public static void MakeExecutable(this IDetourNativePlatform plat, NativeDetourData detour)
		{
			plat.MakeExecutable(detour.Method, detour.Size);
		}

		public static void FlushICache(this IDetourNativePlatform plat, NativeDetourData detour)
		{
			plat.FlushICache(detour.Method, detour.Size);
		}

		public unsafe static void Write(this IntPtr to, ref int offs, byte value)
		{
			*(byte*)((long)to + offs) = value;
			offs++;
		}

		public unsafe static void Write(this IntPtr to, ref int offs, ushort value)
		{
			*(ushort*)((long)to + offs) = value;
			offs += 2;
		}

		public unsafe static void Write(this IntPtr to, ref int offs, uint value)
		{
			*(uint*)((long)to + offs) = value;
			offs += 4;
		}

		public unsafe static void Write(this IntPtr to, ref int offs, ulong value)
		{
			*(ulong*)((long)to + offs) = value;
			offs += 8;
		}

		public static MethodBase GetIdentifiable(this MethodBase method)
		{
			return Runtime.GetIdentifiable(method);
		}

		public static IntPtr GetNativeStart(this MethodBase method)
		{
			return Runtime.GetNativeStart(method);
		}

		public static IntPtr GetNativeStart(this Delegate method)
		{
			return method.Method.GetNativeStart();
		}

		public static IntPtr GetNativeStart(this Expression method)
		{
			return ((MethodCallExpression)method).Method.GetNativeStart();
		}

		public static MethodInfo CreateILCopy(this MethodBase method)
		{
			return Runtime.CreateCopy(method);
		}

		public static bool TryCreateILCopy(this MethodBase method, out MethodInfo dm)
		{
			return Runtime.TryCreateCopy(method, out dm);
		}

		public static T Pin<T>(this T method) where T : MethodBase
		{
			Runtime.Pin(method);
			return method;
		}

		public static T Unpin<T>(this T method) where T : MethodBase
		{
			Runtime.Unpin(method);
			return method;
		}

		public static MethodInfo GenerateNativeProxy(IntPtr target, MethodBase signature)
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void);
			ParameterInfo[] parameters = signature.GetParameters();
			Type[] array = new Type[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				array[i] = parameters[i].ParameterType;
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition("Native<" + ((long)target).ToString("X16", CultureInfo.InvariantCulture) + ">", type, array);
			MethodInfo methodInfo;
			try
			{
				methodInfo = val.StubCriticalDetour().Generate().Pin();
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			NativeDetourData detour = Native.Create(methodInfo.GetNativeStart(), target);
			Native.MakeWritable(detour);
			Native.Apply(detour);
			Native.MakeExecutable(detour);
			Native.FlushICache(detour);
			Native.Free(detour);
			return methodInfo;
		}

		private static NativeDetourData ToNativeDetourData(IntPtr method, IntPtr target, uint size, byte type, IntPtr extra)
		{
			NativeDetourData result = default(NativeDetourData);
			result.Method = method;
			result.Target = target;
			result.Size = size;
			result.Type = type;
			result.Extra = extra;
			return result;
		}

		public static DynamicMethodDefinition StubCriticalDetour(this DynamicMethodDefinition dm)
		{
			//IL_001d: 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_0051: 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)
			ILProcessor iLProcessor = dm.GetILProcessor();
			ModuleDefinition module = ((MemberReference)iLProcessor.Body.Method).Module;
			for (int i = 0; i < 32; i++)
			{
				iLProcessor.Emit(OpCodes.Nop);
			}
			iLProcessor.Emit(OpCodes.Ldstr, ((MemberReference)dm.Definition).Name + " should've been detoured!");
			iLProcessor.Emit(OpCodes.Newobj, module.ImportReference((MethodBase)_ctor_Exception));
			iLProcessor.Emit(OpCodes.Throw);
			return dm;
		}

		public static void EmitDetourCopy(this ILProcessor il, IntPtr src, IntPtr dst, byte type)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			ModuleDefinition module = ((MemberReference)il.Body.Method).Module;
			il.Emit(OpCodes.Ldsfld, module.ImportReference(_f_Native));
			il.Emit(OpCodes.Ldc_I8, (long)src);
			il.Emit(OpCodes.Conv_I);
			il.Emit(OpCodes.Ldc_I8, (long)dst);
			il.Emit(OpCodes.Conv_I);
			il.Emit(OpCodes.Ldc_I4, (int)type);
			il.Emit(OpCodes.Conv_U1);
			il.Emit(OpCodes.Callvirt, module.ImportReference((MethodBase)_m_Copy));
		}

		public static void EmitDetourApply(this ILProcessor il, NativeDetourData data)
		{
			//IL_0012: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_007b: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			ModuleDefinition module = ((MemberReference)il.Body.Method).Module;
			il.Emit(OpCodes.Ldsfld, module.ImportReference(_f_Native));
			il.Emit(OpCodes.Ldc_I8, (long)data.Method);
			il.Emit(OpCodes.Conv_I);
			il.Emit(OpCodes.Ldc_I8, (long)data.Target);
			il.Emit(OpCodes.Conv_I);
			il.Emit(OpCodes.Ldc_I4, (int)data.Size);
			il.Emit(OpCodes.Ldc_I4, (int)data.Type);
			il.Emit(OpCodes.Conv_U1);
			il.Emit(OpCodes.Ldc_I8, (long)data.Extra);
			il.Emit(OpCodes.Conv_I);
			il.Emit(OpCodes.Call, module.ImportReference((MethodBase)_m_ToNativeDetourData));
			il.Emit(OpCodes.Callvirt, module.ImportReference((MethodBase)_m_Apply));
		}
	}
	public interface IDetourNativePlatform
	{
		NativeDetourData Create(IntPtr from, IntPtr to, byte? type = null);

		void Free(NativeDetourData detour);

		void Apply(NativeDetourData detour);

		void Copy(IntPtr src, IntPtr dst, byte type);

		void MakeWritable(IntPtr src, uint size);

		void MakeExecutable(IntPtr src, uint size);

		void MakeReadWriteExecutable(IntPtr src, uint size);

		void FlushICache(IntPtr src, uint size);

		IntPtr MemAlloc(uint size);

		void MemFree(IntPtr ptr);
	}
	public interface IDetourRuntimePlatform
	{
		bool OnMethodCompiledWillBeCalled { get; }

		event OnMethodCompiledEvent OnMethodCompiled;

		MethodBase GetIdentifiable(MethodBase method);

		IntPtr GetNativeStart(MethodBase method);

		MethodInfo CreateCopy(MethodBase method);

		bool TryCreateCopy(MethodBase method, out MethodInfo dm);

		void Pin(MethodBase method);

		void Unpin(MethodBase method);

		MethodBase GetDetourTarget(MethodBase from, MethodBase to);

		uint TryMemAllocScratchCloseTo(IntPtr target, out IntPtr ptr, int size);
	}
	public delegate void OnMethodCompiledEvent(MethodBase method, IntPtr codeStart, ulong codeSize);
	public struct NativeDetourData
	{
		public IntPtr Method;

		public IntPtr Target;

		public byte Type;

		public uint Size;

		public IntPtr Extra;
	}
}
namespace MonoMod.RuntimeDetour.Platforms
{
	public class DetourNativeARMPlatform : IDetourNativePlatform
	{
		public enum DetourType : byte
		{
			Thumb,
			ThumbBX,
			AArch32,
			AArch32BX,
			AArch64
		}

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate int d_flushicache(IntPtr code, ulong size);

		private static readonly uint[] DetourSizes = new uint[5] { 8u, 12u, 8u, 12u, 16u };

		public bool ShouldFlushICache = true;

		private readonly byte[] _FlushCache32 = new byte[44]
		{
			128, 64, 45, 233, 0, 48, 160, 225, 1, 192,
			128, 224, 20, 224, 159, 229, 3, 0, 160, 225,
			12, 16, 160, 225, 14, 112, 160, 225, 0, 32,
			160, 227, 0, 0, 0, 239, 128, 128, 189, 232,
			2, 0, 15, 0
		};

		private readonly byte[] _FlushCache64 = new byte[76]
		{
			1, 0, 1, 139, 0, 244, 126, 146, 63, 0,
			0, 235, 201, 0, 0, 84, 226, 3, 0, 170,
			34, 126, 11, 213, 66, 16, 0, 145, 63, 0,
			2, 235, 168, 255, 255, 84, 159, 59, 3, 213,
			63, 0, 0, 235, 169, 0, 0, 84, 32, 117,
			11, 213, 0, 16, 0, 145, 63, 0, 0, 235,
			168, 255, 255, 84, 159, 59, 3, 213, 223, 63,
			3, 213, 192, 3, 95, 214
		};

		private static DetourType GetDetourType(IntPtr from, IntPtr to)
		{
			if (IntPtr.Size >= 8)
			{
				return DetourType.AArch64;
			}
			bool num = ((long)from & 1) == 1;
			bool flag = ((long)to & 1) == 1;
			if (num)
			{
				if (flag)
				{
					return DetourType.Thumb;
				}
				return DetourType.ThumbBX;
			}
			if (flag)
			{
				return DetourType.AArch32BX;
			}
			return DetourType.AArch32;
		}

		public NativeDetourData Create(IntPtr from, IntPtr to, byte? type)
		{
			NativeDetourData nativeDetourData = default(NativeDetourData);
			nativeDetourData.Method = (IntPtr)((long)from & -2);
			nativeDetourData.Target = (IntPtr)((long)to & -2);
			NativeDetourData result = nativeDetourData;
			uint[] detourSizes = DetourSizes;
			int num = ((int?)type) ?? ((int)GetDetourType(from, to));
			byte b = (byte)num;
			result.Type = (byte)num;
			result.Size = detourSizes[b];
			return result;
		}

		public void Free(NativeDetourData detour)
		{
		}

		public void Apply(NativeDetourData detour)
		{
			int offs = 0;
			switch ((DetourType)detour.Type)
			{
			case DetourType.Thumb:
				detour.Method.Write(ref offs, 223);
				detour.Method.Write(ref offs, 248);
				detour.Method.Write(ref offs, 0);
				detour.Method.Write(ref offs, 240);
				detour.Method.Write(ref offs, (uint)(int)detour.Target | 1u);
				break;
			case DetourType.ThumbBX:
				detour.Method.Write(ref offs, 223);
				detour.Method.Write(ref offs, 248);
				detour.Method.Write(ref offs, 4);
				detour.Method.Write(ref offs, 160);
				detour.Method.Write(ref offs, 80);
				detour.Method.Write(ref offs, 71);
				detour.Method.Write(ref offs, 0);
				detour.Method.Write(ref offs, 191);
				detour.Method.Write(ref offs, (uint)(int)detour.Target | 0u);
				break;
			case DetourType.AArch32:
				detour.Method.Write(ref offs, 4);
				detour.Method.Write(ref offs, 240);
				detour.Method.Write(ref offs, 31);
				detour.Method.Write(ref offs, 229);
				detour.Method.Write(ref offs, (uint)(int)detour.Target | 0u);
				break;
			case DetourType.AArch32BX:
				detour.Method.Write(ref offs, 0);
				detour.Method.Write(ref offs, 128);
				detour.Method.Write(ref offs, 159);
				detour.Method.Write(ref offs, 229);
				detour.Method.Write(ref offs, 24);
				detour.Method.Write(ref offs, byte.MaxValue);
				detour.Method.Write(ref offs, 47);
				detour.Method.Write(ref offs, 225);
				detour.Method.Write(ref offs, (uint)(int)detour.Target | 1u);
				break;
			case DetourType.AArch64:
				detour.Method.Write(ref offs, 79);
				detour.Method.Write(ref offs, 0);
				detour.Method.Write(ref offs, 0);
				detour.Method.Write(ref offs, 88);
				detour.Method.Write(ref offs, 224);
				detour.Method.Write(ref offs, 1);
				detour.Method.Write(ref offs, 31);
				detour.Method.Write(ref offs, 214);
				detour.Method.Write(ref offs, (ulong)(long)detour.Target);
				break;
			default:
				throw new NotSupportedException($"Unknown detour type {detour.Type}");
			}
		}

		public unsafe void Copy(IntPtr src, IntPtr dst, byte type)
		{
			switch ((DetourType)type)
			{
			case DetourType.Thumb:
				*(int*)(long)dst = *(int*)(long)src;
				*(int*)((long)dst + 4) = *(int*)((long)src + 4);
				break;
			case DetourType.ThumbBX:
				*(int*)(long)dst = *(int*)(long)src;
				*(short*)((long)dst + 4) = *(short*)((long)src + 4);
				*(short*)((long)dst + 6) = *(short*)((long)src + 6);
				*(int*)((long)dst + 8) = *(int*)((long)src + 8);
				break;
			case DetourType.AArch32:
				*(int*)(long)dst = *(int*)(long)src;
				*(int*)((long)dst + 4) = *(int*)((long)src + 4);
				break;
			case DetourType.AArch32BX:
				*(int*)(long)dst = *(int*)(long)src;
				*(int*)((long)dst + 4) = *(int*)((long)src + 4);
				*(int*)((long)dst + 8) = *(int*)((long)src + 8);
				break;
			case DetourType.AArch64:
				*(int*)(long)dst = *(int*)(long)src;
				*(int*)((long)dst + 4) = *(int*)((long)src + 4);
				*(long*)((long)dst + 8) = *(long*)((long)src + 8);
				break;
			default:
				throw new NotSupportedException($"Unknown detour type {type}");
			}
		}

		public void MakeWritable(IntPtr src, uint size)
		{
		}

		public void MakeExecutable(IntPtr src, uint size)
		{
		}

		public void MakeReadWriteExecutable(IntPtr src, uint size)
		{
		}

		public unsafe void FlushICache(IntPtr src, uint size)
		{
			if (ShouldFlushICache)
			{
				byte[] array = ((IntPtr.Size >= 8) ? _FlushCache64 : _FlushCache32);
				fixed (byte* ptr = array)
				{
					DetourHelper.Native.MakeExecutable((IntPtr)ptr, (uint)array.Length);
					(Marshal.GetDelegateForFunctionPointer((IntPtr)ptr, typeof(d_flushicache)) as d_flushicache)(src, size);
				}
			}
		}

		public IntPtr MemAlloc(uint size)
		{
			return Marshal.AllocHGlobal((int)size);
		}

		public void MemFree(IntPtr ptr)
		{
			Marshal.FreeHGlobal(ptr);
		}
	}
	public class DetourNativeLibcPlatform : IDetourNativePlatform
	{
		[Flags]
		private enum MmapProts
		{
			PROT_READ = 1,
			PROT_WRITE = 2,
			PROT_EXEC = 4,
			PROT_NONE = 0,
			PROT_GROWSDOWN = 0x1000000,
			PROT_GROWSUP = 0x2000000
		}

		private readonly IDetourNativePlatform Inner;

		private readonly long _Pagesize;

		public DetourNativeLibcPlatform(IDetourNativePlatform inner)
		{
			Inner = inner;
			PropertyInfo property = typeof(Environment).GetProperty("SystemPageSize");
			if ((object)property == null)
			{
				throw new NotSupportedException("Unsupported runtime");
			}
			_Pagesize = (int)property.GetValue(null, new object[0]);
		}

		private void SetMemPerms(IntPtr start, ulong len, MmapProts prot)
		{
			long pagesize = _Pagesize;
			long num = (long)start & ~(pagesize - 1);
			long num2 = ((long)start + (long)len + pagesize - 1) & ~(pagesize - 1);
			if (mprotect((IntPtr)num, (IntPtr)(num2 - num), prot) != 0)
			{
				throw new Win32Exception();
			}
		}

		public void MakeWritable(IntPtr src, uint size)
		{
			SetMemPerms(src, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC);
		}

		public void MakeExecutable(IntPtr src, uint size)
		{
			SetMemPerms(src, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC);
		}

		public void MakeReadWriteExecutable(IntPtr

BooBoo Building/BepInEx/core/MonoMod.Utils.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("MonoMod.Utils.Cil.ILGeneratorProxy")]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2022 0x0ade")]
[assembly: AssemblyDescription("Utilities and smaller MonoMod \"components\" (f.e. ModInterop, DynDll, DynData). Can be used for your own mods. Required by all other MonoMod components.")]
[assembly: AssemblyFileVersion("22.1.29.1")]
[assembly: AssemblyInformationalVersion("22.01.29.01")]
[assembly: AssemblyProduct("MonoMod.Utils")]
[assembly: AssemblyTitle("MonoMod.Utils")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("22.1.29.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static string Replace(this string self, string oldValue, string newValue, StringComparison comparison)
	{
		return self.Replace(oldValue, newValue);
	}

	public static bool Contains(this string self, string value, StringComparison comparison)
	{
		return self.Contains(value);
	}

	public static int GetHashCode(this string self, StringComparison comparison)
	{
		return self.GetHashCode();
	}

	public static int IndexOf(this string self, char value, StringComparison comparison)
	{
		return self.IndexOf(value);
	}

	public static int IndexOf(this string self, string value, StringComparison comparison)
	{
		return self.IndexOf(value);
	}

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	public class IgnoresAccessChecksToAttribute : Attribute
	{
		public string AssemblyName { get; }

		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
			AssemblyName = assemblyName;
		}
	}
}
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"))
			{
				string? environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG");
				bool? obj;
				if (environmentVariable == null)
				{
					obj = null;
				}
				else
				{
					string text = environmentVariable.ToLower(CultureInfo.InvariantCulture);
					obj = ((text != null) ? new bool?(MultiTargetShims.Contains(text, Tag.ToLower(CultureInfo.InvariantCulture), StringComparison.Ordinal)) : null);
				}
				bool? flag = obj;
				if (!flag.GetValueOrDefault())
				{
					return;
				}
			}
			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(CultureInfo.InvariantCulture, str, new object[1] { value }));
			writer.Flush();
			return value;
		}
	}
}
namespace MonoMod.ModInterop
{
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class ModExportNameAttribute : Attribute
	{
		public string Name;

		public ModExportNameAttribute(string name)
		{
			Name = name;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field)]
	public sealed class ModImportNameAttribute : Attribute
	{
		public string Name;

		public ModImportNameAttribute(string name)
		{
			Name = name;
		}
	}
	public static class ModInteropManager
	{
		private static HashSet<Type> Registered = new HashSet<Type>();

		private static Dictionary<string, List<MethodInfo>> Methods = new Dictionary<string, List<MethodInfo>>();

		private static List<FieldInfo> Fields = new List<FieldInfo>();

		public static void ModInterop(this Type type)
		{
			if (Registered.Contains(type))
			{
				return;
			}
			Registered.Add(type);
			string name = type.Assembly.GetName().Name;
			object[] customAttributes = type.GetCustomAttributes(typeof(ModExportNameAttribute), inherit: false);
			for (int i = 0; i < customAttributes.Length; i++)
			{
				name = ((ModExportNameAttribute)customAttributes[i]).Name;
			}
			FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
			foreach (FieldInfo fieldInfo in fields)
			{
				if (typeof(Delegate).IsAssignableFrom(fieldInfo.FieldType))
				{
					Fields.Add(fieldInfo);
				}
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public);
			foreach (MethodInfo method in methods)
			{
				method.RegisterModExport();
				method.RegisterModExport(name);
			}
			foreach (FieldInfo field in Fields)
			{
				if (!Methods.TryGetValue(field.GetModImportName(), out var value))
				{
					field.SetValue(null, null);
					continue;
				}
				bool flag = false;
				foreach (MethodInfo item in value)
				{
					try
					{
						field.SetValue(null, Delegate.CreateDelegate(field.FieldType, null, item));
						flag = true;
					}
					catch
					{
						continue;
					}
					break;
				}
				if (!flag)
				{
					field.SetValue(null, null);
				}
			}
		}

		public static void RegisterModExport(this MethodInfo method, string prefix = null)
		{
			if (!method.IsPublic || !method.IsStatic)
			{
				throw new MemberAccessException("Utility must be public static");
			}
			string text = method.Name;
			if (!string.IsNullOrEmpty(prefix))
			{
				text = prefix + "." + text;
			}
			if (!Methods.TryGetValue(text, out var value))
			{
				value = (Methods[text] = new List<MethodInfo>());
			}
			if (!value.Contains(method))
			{
				value.Add(method);
			}
		}

		private static string GetModImportName(this FieldInfo field)
		{
			object[] customAttributes = field.GetCustomAttributes(typeof(ModImportNameAttribute), inherit: false);
			int num = 0;
			if (num < customAttributes.Length)
			{
				return ((ModImportNameAttribute)customAttributes[num]).Name;
			}
			customAttributes = field.DeclaringType.GetCustomAttributes(typeof(ModImportNameAttribute), inherit: false);
			num = 0;
			if (num < customAttributes.Length)
			{
				return ((ModImportNameAttribute)customAttributes[num]).Name + "." + field.Name;
			}
			return field.Name;
		}
	}
}
namespace MonoMod.Utils
{
	public sealed class DynData<TTarget> : IDisposable where TTarget : class
	{
		private class _Data_ : IDisposable
		{
			public readonly Dictionary<string, Func<TTarget, object>> Getters = new Dictionary<string, Func<TTarget, object>>();

			public readonly Dictionary<string, Action<TTarget, object>> Setters = new Dictionary<string, Action<TTarget, object>>();

			public readonly Dictionary<string, object> Data = new Dictionary<string, object>();

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

			~_Data_()
			{
				Dispose();
			}

			public void Dispose()
			{
				lock (Data)
				{
					if (Data.Count == 0)
					{
						return;
					}
					foreach (string item in Disposable)
					{
						if (Data.TryGetValue(item, out var value) && value is IDisposable disposable)
						{
							disposable.Dispose();
						}
					}
					Disposable.Clear();
					Data.Clear();
				}
			}
		}

		private static int CreationsInProgress;

		private static readonly object[] _NoArgs;

		private static readonly _Data_ _DataStatic;

		private static readonly Dictionary<WeakReference, _Data_> _DataMap;

		private static readonly HashSet<WeakReference> _DataMapDead;

		private static readonly Dictionary<string, Func<TTarget, object>> _SpecialGetters;

		private static readonly Dictionary<string, Action<TTarget, object>> _SpecialSetters;

		private readonly WeakReference Weak;

		private TTarget KeepAlive;

		private readonly _Data_ _Data;

		public Dictionary<string, Func<TTarget, object>> Getters => _Data.Getters;

		public Dictionary<string, Action<TTarget, object>> Setters => _Data.Setters;

		public Dictionary<string, object> Data => _Data.Data;

		public bool IsAlive
		{
			get
			{
				if (Weak != null)
				{
					return Weak.SafeGetIsAlive();
				}
				return true;
			}
		}

		public TTarget Target => Weak?.SafeGetTarget() as TTarget;

		public object this[string name]
		{
			get
			{
				if (_SpecialGetters.TryGetValue(name, out var value) || Getters.TryGetValue(name, out value))
				{
					return value(Weak?.SafeGetTarget() as TTarget);
				}
				if (Data.TryGetValue(name, out var value2))
				{
					return value2;
				}
				return null;
			}
			set
			{
				if (_SpecialSetters.TryGetValue(name, out var value2) || Setters.TryGetValue(name, out value2))
				{
					value2(Weak?.SafeGetTarget() as TTarget, value);
					return;
				}
				object obj;
				if (_Data.Disposable.Contains(name) && (obj = this[name]) != null && obj is IDisposable disposable)
				{
					disposable.Dispose();
				}
				Data[name] = value;
			}
		}

		public static event Action<DynData<TTarget>, TTarget> OnInitialize;

		static DynData()
		{
			CreationsInProgress = 0;
			_NoArgs = new object[0];
			_DataStatic = new _Data_();
			_DataMap = new Dictionary<WeakReference, _Data_>(new WeakReferenceComparer());
			_DataMapDead = new HashSet<WeakReference>();
			_SpecialGetters = new Dictionary<string, Func<TTarget, object>>();
			_SpecialSetters = new Dictionary<string, Action<TTarget, object>>();
			GCListener.OnCollect += delegate
			{
				if (CreationsInProgress != 0)
				{
					return;
				}
				lock (_DataMap)
				{
					foreach (KeyValuePair<WeakReference, _Data_> item in _DataMap)
					{
						if (!item.Key.SafeGetIsAlive())
						{
							_DataMapDead.Add(item.Key);
							item.Value.Dispose();
						}
					}
					foreach (WeakReference item2 in _DataMapDead)
					{
						_DataMap.Remove(item2);
					}
					_DataMapDead.Clear();
				}
			};
			FieldInfo[] fields = typeof(TTarget).GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (FieldInfo field in fields)
			{
				string name = field.Name;
				_SpecialGetters[name] = (TTarget obj) => field.GetValue(obj);
				_SpecialSetters[name] = delegate(TTarget obj, object value)
				{
					field.SetValue(obj, value);
				};
			}
			PropertyInfo[] properties = typeof(TTarget).GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (PropertyInfo propertyInfo in properties)
			{
				string name2 = propertyInfo.Name;
				MethodInfo get = propertyInfo.GetGetMethod(nonPublic: true);
				if ((object)get != null)
				{
					_SpecialGetters[name2] = (TTarget obj) => get.Invoke(obj, _NoArgs);
				}
				MethodInfo set = propertyInfo.GetSetMethod(nonPublic: true);
				if ((object)set != null)
				{
					_SpecialSetters[name2] = delegate(TTarget obj, object value)
					{
						set.Invoke(obj, new object[1] { value });
					};
				}
			}
		}

		public DynData()
			: this((TTarget)null, keepAlive: false)
		{
		}

		public DynData(TTarget obj)
			: this(obj, keepAlive: true)
		{
		}

		public DynData(TTarget obj, bool keepAlive)
		{
			if (obj != null)
			{
				WeakReference weakReference = new WeakReference(obj);
				WeakReference key = weakReference;
				CreationsInProgress++;
				lock (_DataMap)
				{
					if (!_DataMap.TryGetValue(key, out _Data))
					{
						_Data = new _Data_();
						_DataMap.Add(key, _Data);
					}
				}
				CreationsInProgress--;
				Weak = weakReference;
				if (keepAlive)
				{
					KeepAlive = obj;
				}
			}
			else
			{
				_Data = _DataStatic;
			}
			DynData<TTarget>.OnInitialize?.Invoke(this, obj);
		}

		public T Get<T>(string name)
		{
			return (T)this[name];
		}

		public void Set<T>(string name, T value)
		{
			this[name] = value;
		}

		public void RegisterProperty(string name, Func<TTarget, object> getter, Action<TTarget, object> setter)
		{
			Getters[name] = getter;
			Setters[name] = setter;
		}

		public void UnregisterProperty(string name)
		{
			Getters.Remove(name);
			Setters.Remove(name);
		}

		private void Dispose(bool disposing)
		{
			KeepAlive = null;
		}

		~DynData()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}
	}
	public static class Extensions
	{
		private static readonly Type t_StateMachineAttribute = typeof(object).Assembly.GetType("System.Runtime.CompilerServices.StateMachineAttribute");

		private static readonly PropertyInfo p_StateMachineType = t_StateMachineAttribute?.GetProperty("StateMachineType");

		private static readonly Type t_Code = typeof(Code);

		private static readonly Type t_OpCodes = typeof(OpCodes);

		private static readonly Dictionary<int, OpCode> _ToLongOp = new Dictionary<int, OpCode>();

		private static readonly Dictionary<int, OpCode> _ToShortOp = new Dictionary<int, OpCode>();

		private static readonly object[] _NoArgs = new object[0];

		private static readonly Dictionary<Type, FieldInfo> fmap_mono_assembly = new Dictionary<Type, FieldInfo>();

		private static readonly bool _MonoAssemblyNameHasArch = new AssemblyName("Dummy, ProcessorArchitecture=MSIL").ProcessorArchitecture == ProcessorArchitecture.MSIL;

		private static readonly Type _RTDynamicMethod = typeof(DynamicMethod).GetNestedType("RTDynamicMethod", BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly Type t_ParamArrayAttribute = typeof(ParamArrayAttribute);

		private static readonly FieldInfo f_GenericParameter_position = typeof(GenericParameter).GetField("position", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo f_GenericParameter_type = typeof(GenericParameter).GetField("type", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly Dictionary<Type, int> _GetManagedSizeCache = new Dictionary<Type, int> { 
		{
			typeof(void),
			0
		} };

		private static MethodInfo _GetManagedSizeHelper;

		private static readonly Dictionary<MethodBase, Func<IntPtr>> _GetLdftnPointerCache = new Dictionary<MethodBase, Func<IntPtr>>();

		public static string ToHexadecimalString(this byte[] data)
		{
			return MultiTargetShims.Replace(BitConverter.ToString(data), "-", string.Empty, StringComparison.Ordinal);
		}

		public static T InvokePassing<T>(this MulticastDelegate md, T val, params object[] args)
		{
			if ((object)md == null)
			{
				return val;
			}
			object[] array = new object[args.Length + 1];
			array[0] = val;
			Array.Copy(args, 0, array, 1, args.Length);
			Delegate[] invocationList = md.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				array[0] = invocationList[i].DynamicInvoke(array);
			}
			return (T)array[0];
		}

		public static bool InvokeWhileTrue(this MulticastDelegate md, params object[] args)
		{
			if ((object)md == null)
			{
				return true;
			}
			Delegate[] invocationList = md.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				if (!(bool)invocationList[i].DynamicInvoke(args))
				{
					return false;
				}
			}
			return true;
		}

		public static bool InvokeWhileFalse(this MulticastDelegate md, params object[] args)
		{
			if ((object)md == null)
			{
				return false;
			}
			Delegate[] invocationList = md.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				if ((bool)invocationList[i].DynamicInvoke(args))
				{
					return true;
				}
			}
			return false;
		}

		public static T InvokeWhileNull<T>(this MulticastDelegate md, params object[] args) where T : class
		{
			if ((object)md == null)
			{
				return null;
			}
			Delegate[] invocationList = md.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				T val = (T)invocationList[i].DynamicInvoke(args);
				if (val != null)
				{
					return val;
				}
			}
			return null;
		}

		public static string SpacedPascalCase(this string input)
		{
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < input.Length; i++)
			{
				char c = input[i];
				if (i > 0 && char.IsUpper(c))
				{
					stringBuilder.Append(' ');
				}
				stringBuilder.Append(c);
			}
			return stringBuilder.ToString();
		}

		public static string ReadNullTerminatedString(this BinaryReader stream)
		{
			string text = "";
			char c;
			while ((c = stream.ReadChar()) != 0)
			{
				text += c;
			}
			return text;
		}

		public static void WriteNullTerminatedString(this BinaryWriter stream, string text)
		{
			if (text != null)
			{
				foreach (char ch in text)
				{
					stream.Write(ch);
				}
			}
			stream.Write('\0');
		}

		public static T CastDelegate<T>(this Delegate source) where T : class
		{
			return source.CastDelegate(typeof(T)) as T;
		}

		public static Delegate CastDelegate(this Delegate source, Type type)
		{
			if ((object)source == null)
			{
				return null;
			}
			Delegate[] invocationList = source.GetInvocationList();
			if (invocationList.Length == 1)
			{
				return CreateDelegate(invocationList[0].Method, type, invocationList[0].Target);
			}
			Delegate[] array = new Delegate[invocationList.Length];
			for (int i = 0; i < invocationList.Length; i++)
			{
				array[i] = invocationList[i].CastDelegate(type);
			}
			return Delegate.Combine(array);
		}

		public static bool TryCastDelegate<T>(this Delegate source, out T result) where T : class
		{
			if (source is T val)
			{
				result = val;
				return true;
			}
			Delegate result2;
			bool result3 = source.TryCastDelegate(typeof(T), out result2);
			result = result2 as T;
			return result3;
		}

		public static bool TryCastDelegate(this Delegate source, Type type, out Delegate result)
		{
			result = null;
			if ((object)source == null)
			{
				return false;
			}
			try
			{
				Delegate[] invocationList = source.GetInvocationList();
				if (invocationList.Length == 1)
				{
					result = CreateDelegate(invocationList[0].Method, type, invocationList[0].Target);
					return true;
				}
				Delegate[] array = new Delegate[invocationList.Length];
				for (int i = 0; i < invocationList.Length; i++)
				{
					array[i] = invocationList[i].CastDelegate(type);
				}
				result = Delegate.Combine(array);
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static void LogDetailed(this Exception e, string tag = null)
		{
			if (tag == null)
			{
				Console.WriteLine("--------------------------------");
				Console.WriteLine("Detailed exception log:");
			}
			for (Exception ex = e; ex != null; ex = ex.InnerException)
			{
				Console.WriteLine("--------------------------------");
				Console.WriteLine(ex.GetType().FullName + ": " + ex.Message + "\n" + ex.StackTrace);
				if (ex is ReflectionTypeLoadException ex2)
				{
					for (int i = 0; i < ex2.Types.Length; i++)
					{
						Console.WriteLine("ReflectionTypeLoadException.Types[" + i + "]: " + ex2.Types[i]);
					}
					for (int j = 0; j < ex2.LoaderExceptions.Length; j++)
					{
						ex2.LoaderExceptions[j].LogDetailed(tag + ((tag == null) ? "" : ", ") + "rtle:" + j);
					}
				}
				if (ex is TypeLoadException)
				{
					Console.WriteLine("TypeLoadException.TypeName: " + ((TypeLoadException)ex).TypeName);
				}
				if (ex is BadImageFormatException)
				{
					Console.WriteLine("BadImageFormatException.FileName: " + ((BadImageFormatException)ex).FileName);
				}
			}
		}

		public static MethodInfo GetStateMachineTarget(this MethodInfo method)
		{
			if ((object)p_StateMachineType == null)
			{
				return null;
			}
			object[] customAttributes = method.GetCustomAttributes(inherit: false);
			for (int i = 0; i < customAttributes.Length; i++)
			{
				Attribute attribute = (Attribute)customAttributes[i];
				if (t_StateMachineAttribute.IsCompatible(attribute.GetType()))
				{
					return (p_StateMachineType.GetValue(attribute, null) as Type)?.GetMethod("MoveNext", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				}
			}
			return null;
		}

		public static MethodBase GetActualGenericMethodDefinition(this MethodInfo method)
		{
			return (method.IsGenericMethod ? method.GetGenericMethodDefinition() : method).GetUnfilledMethodOnGenericType();
		}

		public static MethodBase GetUnfilledMethodOnGenericType(this MethodBase method)
		{
			if ((object)method.DeclaringType != null && method.DeclaringType.IsGenericType)
			{
				Type genericTypeDefinition = method.DeclaringType.GetGenericTypeDefinition();
				method = MethodBase.GetMethodFromHandle(method.MethodHandle, genericTypeDefinition.TypeHandle);
			}
			return method;
		}

		public static bool Is(this MemberReference member, string fullName)
		{
			if (member == null)
			{
				return false;
			}
			return MultiTargetShims.Replace(member.FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal);
		}

		public static bool Is(this MemberReference member, string typeFullName, string name)
		{
			if (member == null)
			{
				return false;
			}
			if (MultiTargetShims.Replace(((MemberReference)member.DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal))
			{
				return member.Name == name;
			}
			return false;
		}

		public static bool Is(this MemberReference member, Type type, string name)
		{
			if (member == null)
			{
				return false;
			}
			if (MultiTargetShims.Replace(((MemberReference)member.DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal))
			{
				return member.Name == name;
			}
			return false;
		}

		public static bool Is(this MethodReference method, string fullName)
		{
			if (method == null)
			{
				return false;
			}
			if (MultiTargetShims.Contains(fullName, " ", StringComparison.Ordinal))
			{
				if (MultiTargetShims.Replace(method.GetID(null, null, withType: true, simple: true), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal))
				{
					return true;
				}
				if (MultiTargetShims.Replace(method.GetID(), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal))
				{
					return true;
				}
			}
			return MultiTargetShims.Replace(((MemberReference)method).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal);
		}

		public static bool Is(this MethodReference method, string typeFullName, string name)
		{
			if (method == null)
			{
				return false;
			}
			if (MultiTargetShims.Contains(name, " ", StringComparison.Ordinal) && MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal) && MultiTargetShims.Replace(method.GetID(null, null, withType: false), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(name, "+", "/", StringComparison.Ordinal))
			{
				return true;
			}
			if (MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal))
			{
				return ((MemberReference)method).Name == name;
			}
			return false;
		}

		public static bool Is(this MethodReference method, Type type, string name)
		{
			if (method == null)
			{
				return false;
			}
			if (MultiTargetShims.Contains(name, " ", StringComparison.Ordinal) && MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal) && MultiTargetShims.Replace(method.GetID(null, null, withType: false), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(name, "+", "/", StringComparison.Ordinal))
			{
				return true;
			}
			if (MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal))
			{
				return ((MemberReference)method).Name == name;
			}
			return false;
		}

		public static void ReplaceOperands(this ILProcessor il, object from, object to)
		{
			//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)
			Enumerator<Instruction> enumerator = il.Body.Instructions.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					Instruction current = enumerator.Current;
					if (current.Operand?.Equals(from) ?? (from == null))
					{
						current.Operand = to;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public static FieldReference Import(this ILProcessor il, FieldInfo field)
		{
			return ((MemberReference)il.Body.Method).Module.ImportReference(field);
		}

		public static MethodReference Import(this ILProcessor il, MethodBase method)
		{
			return ((MemberReference)il.Body.Method).Module.ImportReference(method);
		}

		public static TypeReference Import(this ILProcessor il, Type type)
		{
			return ((MemberReference)il.Body.Method).Module.ImportReference(type);
		}

		public static MemberReference Import(this ILProcessor il, MemberInfo member)
		{
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			if (!(member is FieldInfo field))
			{
				if (!(member is MethodBase method))
				{
					if (member is Type type)
					{
						return (MemberReference)(object)il.Import(type);
					}
					throw new NotSupportedException("Unsupported member type " + member.GetType().FullName);
				}
				return (MemberReference)(object)il.Import(method);
			}
			return (MemberReference)(object)il.Import(field);
		}

		public static Instruction Create(this ILProcessor il, OpCode opcode, FieldInfo field)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return il.Create(opcode, il.Import(field));
		}

		public static Instruction Create(this ILProcessor il, OpCode opcode, MethodBase method)
		{
			//IL_0012: 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 (method is DynamicMethod)
			{
				return il.Create(opcode, (object)method);
			}
			return il.Create(opcode, il.Import(method));
		}

		public static Instruction Create(this ILProcessor il, OpCode opcode, Type type)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return il.Create(opcode, il.Import(type));
		}

		public static Instruction Create(this ILProcessor il, OpCode opcode, object operand)
		{
			//IL_0001: 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)
			Instruction obj = il.Create(OpCodes.Nop);
			obj.OpCode = opcode;
			obj.Operand = operand;
			return obj;
		}

		public static Instruction Create(this ILProcessor il, OpCode opcode, MemberInfo member)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			if (!(member is FieldInfo field))
			{
				if (!(member is MethodBase method))
				{
					if (member is Type type)
					{
						return il.Create(opcode, type);
					}
					throw new NotSupportedException("Unsupported member type " + member.GetType().FullName);
				}
				return il.Create(opcode, method);
			}
			return il.Create(opcode, field);
		}

		public static void Emit(this ILProcessor il, OpCode opcode, FieldInfo field)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			il.Emit(opcode, il.Import(field));
		}

		public static void Emit(this ILProcessor il, OpCode opcode, MethodBase method)
		{
			//IL_0012: 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 (method is DynamicMethod)
			{
				il.Emit(opcode, (object)method);
			}
			else
			{
				il.Emit(opcode, il.Import(method));
			}
		}

		public static void Emit(this ILProcessor il, OpCode opcode, Type type)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			il.Emit(opcode, il.Import(type));
		}

		public static void Emit(this ILProcessor il, OpCode opcode, MemberInfo member)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			if (!(member is FieldInfo field))
			{
				if (!(member is MethodBase method))
				{
					if (!(member is Type type))
					{
						throw new NotSupportedException("Unsupported member type " + member.GetType().FullName);
					}
					il.Emit(opcode, type);
				}
				else
				{
					il.Emit(opcode, method);
				}
			}
			else
			{
				il.Emit(opcode, field);
			}
		}

		public static void Emit(this ILProcessor il, OpCode opcode, object operand)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			il.Append(il.Create(opcode, operand));
		}

		public static TypeDefinition SafeResolve(this TypeReference r)
		{
			try
			{
				return r.Resolve();
			}
			catch
			{
				return null;
			}
		}

		public static FieldDefinition SafeResolve(this FieldReference r)
		{
			try
			{
				return r.Resolve();
			}
			catch
			{
				return null;
			}
		}

		public static MethodDefinition SafeResolve(this MethodReference r)
		{
			try
			{
				return r.Resolve();
			}
			catch
			{
				return null;
			}
		}

		public static PropertyDefinition SafeResolve(this PropertyReference r)
		{
			try
			{
				return r.Resolve();
			}
			catch
			{
				return null;
			}
		}

		public static CustomAttribute GetCustomAttribute(this ICustomAttributeProvider cap, string attribute)
		{
			//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)
			if (cap == null || !cap.HasCustomAttributes)
			{
				return null;
			}
			Enumerator<CustomAttribute> enumerator = cap.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current = enumerator.Current;
					if (((MemberReference)current.AttributeType).FullName == attribute)
					{
						return current;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return null;
		}

		public static bool HasCustomAttribute(this ICustomAttributeProvider cap, string attribute)
		{
			return cap.GetCustomAttribute(attribute) != null;
		}

		public static int GetInt(this Instruction instr)
		{
			//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_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_0016: 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_0025: 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_0034: 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_0043: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: 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_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: 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)
			OpCode opCode = instr.OpCode;
			if (opCode == OpCodes.Ldc_I4_M1)
			{
				return -1;
			}
			if (opCode == OpCodes.Ldc_I4_0)
			{
				return 0;
			}
			if (opCode == OpCodes.Ldc_I4_1)
			{
				return 1;
			}
			if (opCode == OpCodes.Ldc_I4_2)
			{
				return 2;
			}
			if (opCode == OpCodes.Ldc_I4_3)
			{
				return 3;
			}
			if (opCode == OpCodes.Ldc_I4_4)
			{
				return 4;
			}
			if (opCode == OpCodes.Ldc_I4_5)
			{
				return 5;
			}
			if (opCode == OpCodes.Ldc_I4_6)
			{
				return 6;
			}
			if (opCode == OpCodes.Ldc_I4_7)
			{
				return 7;
			}
			if (opCode == OpCodes.Ldc_I4_8)
			{
				return 8;
			}
			if (opCode == OpCodes.Ldc_I4_S)
			{
				return (sbyte)instr.Operand;
			}
			return (int)instr.Operand;
		}

		public static int? GetIntOrNull(this Instruction instr)
		{
			//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_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_001b: 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_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: 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_0058: 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_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: 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_00ee: Unknown result type (might be due to invalid IL or missing references)
			OpCode opCode = instr.OpCode;
			if (opCode == OpCodes.Ldc_I4_M1)
			{
				return -1;
			}
			if (opCode == OpCodes.Ldc_I4_0)
			{
				return 0;
			}
			if (opCode == OpCodes.Ldc_I4_1)
			{
				return 1;
			}
			if (opCode == OpCodes.Ldc_I4_2)
			{
				return 2;
			}
			if (opCode == OpCodes.Ldc_I4_3)
			{
				return 3;
			}
			if (opCode == OpCodes.Ldc_I4_4)
			{
				return 4;
			}
			if (opCode == OpCodes.Ldc_I4_5)
			{
				return 5;
			}
			if (opCode == OpCodes.Ldc_I4_6)
			{
				return 6;
			}
			if (opCode == OpCodes.Ldc_I4_7)
			{
				return 7;
			}
			if (opCode == OpCodes.Ldc_I4_8)
			{
				return 8;
			}
			if (opCode == OpCodes.Ldc_I4_S)
			{
				return (sbyte)instr.Operand;
			}
			if (opCode == OpCodes.Ldc_I4)
			{
				return (int)instr.Operand;
			}
			return null;
		}

		public static bool IsBaseMethodCall(this MethodBody body, MethodReference called)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			MethodDefinition method = body.Method;
			if (called == null)
			{
				return false;
			}
			TypeReference val = ((MemberReference)called).DeclaringType;
			while (val is TypeSpecification)
			{
				val = ((TypeSpecification)val).ElementType;
			}
			string patchFullName = ((MemberReference)(object)val).GetPatchFullName();
			bool flag = false;
			try
			{
				TypeDefinition val2 = method.DeclaringType;
				while ((val2 = val2.BaseType?.SafeResolve()) != null)
				{
					if (((MemberReference)(object)val2).GetPatchFullName() == patchFullName)
					{
						flag = true;
						break;
					}
				}
			}
			catch
			{
				flag = ((MemberReference)(object)method.DeclaringType).GetPatchFullName() == patchFullName;
			}
			if (!flag)
			{
				return false;
			}
			return true;
		}

		public static bool IsCallvirt(this MethodReference method)
		{
			if (!method.HasThis)
			{
				return false;
			}
			if (((MemberReference)method).DeclaringType.IsValueType)
			{
				return false;
			}
			return true;
		}

		public static bool IsStruct(this TypeReference type)
		{
			if (!type.IsValueType)
			{
				return false;
			}
			if (type.IsPrimitive)
			{
				return false;
			}
			return true;
		}

		public static OpCode ToLongOp(this OpCode op)
		{
			//IL_0007: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected I4, but got Unknown
			//IL_0053: 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_0049: 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_0093: 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_0098: 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_00a0: Expected I4, but got Unknown
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			string name = Enum.GetName(t_Code, ((OpCode)(ref op)).Code);
			if (!name.EndsWith("_S", StringComparison.Ordinal))
			{
				return op;
			}
			lock (_ToLongOp)
			{
				if (_ToLongOp.TryGetValue((int)((OpCode)(ref op)).Code, out var value))
				{
					return value;
				}
				return _ToLongOp[(int)((OpCode)(ref op)).Code] = (OpCode)(((??)(OpCode?)t_OpCodes.GetField(name.Substring(0, name.Length - 2))?.GetValue(null)) ?? op);
			}
		}

		public static OpCode ToShortOp(this OpCode op)
		{
			//IL_0007: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected I4, but got Unknown
			//IL_0053: 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_0049: 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_008f: 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_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)
			//IL_009c: Expected I4, but got Unknown
			//IL_009c: 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)
			string name = Enum.GetName(t_Code, ((OpCode)(ref op)).Code);
			if (name.EndsWith("_S", StringComparison.Ordinal))
			{
				return op;
			}
			lock (_ToShortOp)
			{
				if (_ToShortOp.TryGetValue((int)((OpCode)(ref op)).Code, out var value))
				{
					return value;
				}
				return _ToShortOp[(int)((OpCode)(ref op)).Code] = (OpCode)(((??)(OpCode?)t_OpCodes.GetField(name + "_S")?.GetValue(null)) ?? op);
			}
		}

		public static void RecalculateILOffsets(this MethodDefinition method)
		{
			if (method.HasBody)
			{
				int num = 0;
				for (int i = 0; i < method.Body.Instructions.Count; i++)
				{
					Instruction val = method.Body.Instructions[i];
					val.Offset = num;
					num += val.GetSize();
				}
			}
		}

		public static void FixShortLongOps(this MethodDefinition method)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: 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)
			if (!method.HasBody)
			{
				return;
			}
			for (int i = 0; i < method.Body.Instructions.Count; i++)
			{
				Instruction val = method.Body.Instructions[i];
				if (val.Operand is Instruction)
				{
					val.OpCode = val.OpCode.ToLongOp();
				}
			}
			method.RecalculateILOffsets();
			bool flag;
			do
			{
				flag = false;
				for (int j = 0; j < method.Body.Instructions.Count; j++)
				{
					Instruction val2 = method.Body.Instructions[j];
					object operand = val2.Operand;
					Instruction val3 = (Instruction)((operand is Instruction) ? operand : null);
					if (val3 != null)
					{
						int num = val3.Offset - (val2.Offset + val2.GetSize());
						if (num == (sbyte)num)
						{
							OpCode opCode = val2.OpCode;
							val2.OpCode = val2.OpCode.ToShortOp();
							flag = opCode != val2.OpCode;
						}
					}
				}
			}
			while (flag);
		}

		public static bool Is(this MemberInfo minfo, MemberReference mref)
		{
			return mref.Is(minfo);
		}

		public static bool Is(this MemberReference mref, MemberInfo minfo)
		{
			if (mref == null)
			{
				return false;
			}
			TypeReference val = mref.DeclaringType;
			if (((val != null) ? ((MemberReference)val).FullName : null) == "<Module>")
			{
				val = null;
			}
			GenericParameter val2 = (GenericParameter)(object)((mref is GenericParameter) ? mref : null);
			if (val2 != null)
			{
				if (!(minfo is Type type))
				{
					return false;
				}
				if (!type.IsGenericParameter)
				{
					IGenericParameterProvider owner = val2.Owner;
					IGenericInstance val3 = (IGenericInstance)(object)((owner is IGenericInstance) ? owner : null);
					if (val3 != null)
					{
						return ((MemberReference)(object)val3.GenericArguments[val2.Position]).Is(type);
					}
					return false;
				}
				return val2.Position == type.GenericParameterPosition;
			}
			if ((object)minfo.DeclaringType != null)
			{
				if (val == null)
				{
					return false;
				}
				Type type2 = minfo.DeclaringType;
				if (minfo is Type && type2.IsGenericType && !type2.IsGenericTypeDefinition)
				{
					type2 = type2.GetGenericTypeDefinition();
				}
				if (!((MemberReference)(object)val).Is(type2))
				{
					return false;
				}
			}
			else if (val != null)
			{
				return false;
			}
			if (!(mref is TypeSpecification) && mref.Name != minfo.Name)
			{
				return false;
			}
			TypeReference val4 = (TypeReference)(object)((mref is TypeReference) ? mref : null);
			if (val4 != null)
			{
				if (!(minfo is Type type3))
				{
					return false;
				}
				if (type3.IsGenericParameter)
				{
					return false;
				}
				GenericInstanceType val5 = (GenericInstanceType)(object)((mref is GenericInstanceType) ? mref : null);
				if (val5 != null)
				{
					if (!type3.IsGenericType)
					{
						return false;
					}
					Collection<TypeReference> genericArguments = val5.GenericArguments;
					Type[] genericArguments2 = type3.GetGenericArguments();
					if (genericArguments.Count != genericArguments2.Length)
					{
						return false;
					}
					for (int i = 0; i < genericArguments.Count; i++)
					{
						if (!((MemberReference)(object)genericArguments[i]).Is(genericArguments2[i]))
						{
							return false;
						}
					}
					return ((MemberReference)(object)((TypeSpecification)val5).ElementType).Is(type3.GetGenericTypeDefinition());
				}
				if (val4.HasGenericParameters)
				{
					if (!type3.IsGenericType)
					{
						return false;
					}
					Collection<GenericParameter> genericParameters = val4.GenericParameters;
					Type[] genericArguments3 = type3.GetGenericArguments();
					if (genericParameters.Count != genericArguments3.Length)
					{
						return false;
					}
					for (int j = 0; j < genericParameters.Count; j++)
					{
						if (!((MemberReference)(object)genericParameters[j]).Is(genericArguments3[j]))
						{
							return false;
						}
					}
				}
				else if (type3.IsGenericType)
				{
					return false;
				}
				ArrayType val6 = (ArrayType)(object)((mref is ArrayType) ? mref : null);
				if (val6 != null)
				{
					if (!type3.IsArray)
					{
						return false;
					}
					if (val6.Dimensions.Count == type3.GetArrayRank())
					{
						return ((MemberReference)(object)((TypeSpecification)val6).ElementType).Is(type3.GetElementType());
					}
					return false;
				}
				ByReferenceType val7 = (ByReferenceType)(object)((mref is ByReferenceType) ? mref : null);
				if (val7 != null)
				{
					if (!type3.IsByRef)
					{
						return false;
					}
					return ((MemberReference)(object)((TypeSpecification)val7).ElementType).Is(type3.GetElementType());
				}
				PointerType val8 = (PointerType)(object)((mref is PointerType) ? mref : null);
				if (val8 != null)
				{
					if (!type3.IsPointer)
					{
						return false;
					}
					return ((MemberReference)(object)((TypeSpecification)val8).ElementType).Is(type3.GetElementType());
				}
				TypeSpecification val9 = (TypeSpecification)(object)((mref is TypeSpecification) ? mref : null);
				if (val9 != null)
				{
					return ((MemberReference)(object)val9.ElementType).Is(type3.HasElementType ? type3.GetElementType() : type3);
				}
				if (val != null)
				{
					return mref.Name == type3.Name;
				}
				return mref.FullName == MultiTargetShims.Replace(type3.FullName, "+", "/", StringComparison.Ordinal);
			}
			if (minfo is Type)
			{
				return false;
			}
			MethodReference methodRef = (MethodReference)(object)((mref is MethodReference) ? mref : null);
			if (methodRef != null)
			{
				if (!(minfo is MethodBase methodBase))
				{
					return false;
				}
				Collection<ParameterDefinition> parameters = methodRef.Parameters;
				ParameterInfo[] parameters2 = methodBase.GetParameters();
				if (parameters.Count != parameters2.Length)
				{
					return false;
				}
				GenericInstanceMethod val10 = (GenericInstanceMethod)(object)((mref is GenericInstanceMethod) ? mref : null);
				if (val10 != null)
				{
					if (!methodBase.IsGenericMethod)
					{
						return false;
					}
					Collection<TypeReference> genericArguments4 = val10.GenericArguments;
					Type[] genericArguments5 = methodBase.GetGenericArguments();
					if (genericArguments4.Count != genericArguments5.Length)
					{
						return false;
					}
					for (int k = 0; k < genericArguments4.Count; k++)
					{
						if (!((MemberReference)(object)genericArguments4[k]).Is(genericArguments5[k]))
						{
							return false;
						}
					}
					return ((MemberReference)(object)((MethodSpecification)val10).ElementMethod).Is((methodBase as MethodInfo)?.GetGenericMethodDefinition() ?? methodBase);
				}
				if (methodRef.HasGenericParameters)
				{
					if (!methodBase.IsGenericMethod)
					{
						return false;
					}
					Collection<GenericParameter> genericParameters2 = methodRef.GenericParameters;
					Type[] genericArguments6 = methodBase.GetGenericArguments();
					if (genericParameters2.Count != genericArguments6.Length)
					{
						return false;
					}
					for (int l = 0; l < genericParameters2.Count; l++)
					{
						if (!((MemberReference)(object)genericParameters2[l]).Is(genericArguments6[l]))
						{
							return false;
						}
					}
				}
				else if (methodBase.IsGenericMethod)
				{
					return false;
				}
				Relinker relinker = null;
				relinker = delegate(IMetadataTokenProvider paramMemberRef, IGenericParameterProvider ctx)
				{
					TypeReference val15 = (TypeReference)(object)((paramMemberRef is TypeReference) ? paramMemberRef : null);
					return (IMetadataTokenProvider)((val15 == null) ? ((object)paramMemberRef) : ((object)ResolveParameter(val15)));
				};
				if (!((MemberReference)(object)methodRef.ReturnType.Relink(relinker, null)).Is((methodBase as MethodInfo)?.ReturnType ?? typeof(void)) && !((MemberReference)(object)methodRef.ReturnType).Is((methodBase as MethodInfo)?.ReturnType ?? typeof(void)))
				{
					return false;
				}
				for (int m = 0; m < parameters.Count; m++)
				{
					if (!((MemberReference)(object)((ParameterReference)parameters[m]).ParameterType.Relink(relinker, null)).Is(parameters2[m].ParameterType) && !((MemberReference)(object)((ParameterReference)parameters[m]).ParameterType).Is(parameters2[m].ParameterType))
					{
						return false;
					}
				}
				return true;
			}
			if (minfo is MethodInfo)
			{
				return false;
			}
			if (mref is FieldReference != minfo is FieldInfo)
			{
				return false;
			}
			if (mref is PropertyReference != minfo is PropertyInfo)
			{
				return false;
			}
			if (mref is EventReference != minfo is EventInfo)
			{
				return false;
			}
			return true;
			TypeReference ResolveParameter(TypeReference paramTypeRef)
			{
				GenericParameter val11 = (GenericParameter)(object)((paramTypeRef is GenericParameter) ? paramTypeRef : null);
				if (val11 != null)
				{
					if (val11.Owner is MethodReference)
					{
						MethodReference obj = methodRef;
						GenericInstanceMethod val12 = (GenericInstanceMethod)(object)((obj is GenericInstanceMethod) ? obj : null);
						if (val12 != null)
						{
							return val12.GenericArguments[val11.Position];
						}
					}
					IGenericParameterProvider owner2 = val11.Owner;
					TypeReference val13 = (TypeReference)(object)((owner2 is TypeReference) ? owner2 : null);
					if (val13 != null)
					{
						TypeReference declaringType = ((MemberReference)methodRef).DeclaringType;
						GenericInstanceType val14 = (GenericInstanceType)(object)((declaringType is GenericInstanceType) ? declaringType : null);
						if (val14 != null && ((MemberReference)val13).FullName == ((MemberReference)((TypeSpecification)val14).ElementType).FullName)
						{
							return val14.GenericArguments[val11.Position];
						}
					}
					return paramTypeRef;
				}
				if (paramTypeRef == ((MemberReference)methodRef).DeclaringType.GetElementType())
				{
					return ((MemberReference)methodRef).DeclaringType;
				}
				return paramTypeRef;
			}
		}

		public static IMetadataTokenProvider ImportReference(this ModuleDefinition mod, IMetadataTokenProvider mtp)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			if (mtp is TypeReference)
			{
				return (IMetadataTokenProvider)(object)mod.ImportReference((TypeReference)mtp);
			}
			if (mtp is FieldReference)
			{
				return (IMetadataTokenProvider)(object)mod.ImportReference((FieldReference)mtp);
			}
			if (mtp is MethodReference)
			{
				return (IMetadataTokenProvider)(object)mod.ImportReference((MethodReference)mtp);
			}
			return mtp;
		}

		public static void AddRange<T>(this Collection<T> list, IEnumerable<T> other)
		{
			foreach (T item in other)
			{
				list.Add(item);
			}
		}

		public static void AddRange(this IDictionary dict, IDictionary other)
		{
			foreach (DictionaryEntry item in other)
			{
				dict.Add(item.Key, item.Value);
			}
		}

		public static void AddRange<K, V>(this IDictionary<K, V> dict, IDictionary<K, V> other)
		{
			foreach (KeyValuePair<K, V> item in other)
			{
				dict.Add(item.Key, item.Value);
			}
		}

		public static void AddRange<K, V>(this Dictionary<K, V> dict, Dictionary<K, V> other)
		{
			foreach (KeyValuePair<K, V> item in other)
			{
				dict.Add(item.Key, item.Value);
			}
		}

		public static void InsertRange<T>(this Collection<T> list, int index, IEnumerable<T> other)
		{
			foreach (T item in other)
			{
				list.Insert(index++, item);
			}
		}

		public static bool IsCompatible(this Type type, Type other)
		{
			if (!type._IsCompatible(other))
			{
				return other._IsCompatible(type);
			}
			return true;
		}

		private static bool _IsCompatible(this Type type, Type other)
		{
			if ((object)type == other)
			{
				return true;
			}
			if (type.IsAssignableFrom(other))
			{
				return true;
			}
			if (other.IsEnum && type.IsCompatible(Enum.GetUnderlyingType(other)))
			{
				return true;
			}
			if ((other.IsPointer || other.IsByRef) && (object)type == typeof(IntPtr))
			{
				return true;
			}
			return false;
		}

		public static T GetDeclaredMember<T>(this T member) where T : MemberInfo
		{
			if ((object)member.DeclaringType == member.ReflectedType)
			{
				return member;
			}
			int metadataToken = member.MetadataToken;
			MemberInfo[] members = member.DeclaringType.GetMembers((BindingFlags)(-1));
			foreach (MemberInfo memberInfo in members)
			{
				if (memberInfo.MetadataToken == metadataToken)
				{
					return (T)memberInfo;
				}
			}
			return member;
		}

		public unsafe static void SetMonoCorlibInternal(this Assembly asm, bool value)
		{
			if ((object)Type.GetType("Mono.Runtime") == null)
			{
				return;
			}
			Type type = asm?.GetType();
			if ((object)type == null)
			{
				return;
			}
			FieldInfo value2;
			lock (fmap_mono_assembly)
			{
				if (!fmap_mono_assembly.TryGetValue(type, out value2))
				{
					value2 = type.GetField("_mono_assembly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? type.GetField("dynamic_assembly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					fmap_mono_assembly[type] = value2;
				}
			}
			if ((object)value2 == null)
			{
				return;
			}
			AssemblyName assemblyName = new AssemblyName(asm.FullName);
			lock (ReflectionHelper.AssemblyCache)
			{
				WeakReference value3 = new WeakReference(asm);
				ReflectionHelper.AssemblyCache[asm.GetRuntimeHashedFullName()] = value3;
				ReflectionHelper.AssemblyCache[assemblyName.FullName] = value3;
				ReflectionHelper.AssemblyCache[assemblyName.Name] = value3;
			}
			long num = 0L;
			object value4 = value2.GetValue(asm);
			if (!(value4 is IntPtr intPtr))
			{
				if (value4 is UIntPtr uIntPtr)
				{
					num = (long)(ulong)uIntPtr;
				}
			}
			else
			{
				num = (long)intPtr;
			}
			int num2 = IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + 20 + 4 + 4 + 4 + (_MonoAssemblyNameHasArch ? ((!(typeof(object).Assembly.GetName().Name == "System.Private.CoreLib")) ? ((IntPtr.Size == 4) ? 12 : 16) : ((IntPtr.Size == 4) ? 20 : 24)) : ((typeof(object).Assembly.GetName().Name == "System.Private.CoreLib") ? 16 : 8)) + IntPtr.Size + IntPtr.Size + 1 + 1 + 1;
			byte* ptr = (byte*)(num + num2);
			*ptr = (byte)(value ? 1 : 0);
		}

		public static bool IsDynamicMethod(this MethodBase method)
		{
			if ((object)_RTDynamicMethod != null)
			{
				if (!(method is DynamicMethod))
				{
					return (object)method.GetType() == _RTDynamicMethod;
				}
				return true;
			}
			if (method is DynamicMethod)
			{
				return true;
			}
			if (method.MetadataToken != 0 || !method.IsStatic || !method.IsPublic || (method.Attributes & MethodAttributes.PrivateScope) != 0)
			{
				return false;
			}
			MethodInfo[] methods = method.DeclaringType.GetMethods(BindingFlags.Static | BindingFlags.Public);
			foreach (MethodInfo methodInfo in methods)
			{
				if ((object)method == methodInfo)
				{
					return false;
				}
			}
			return true;
		}

		public static object SafeGetTarget(this WeakReference weak)
		{
			try
			{
				return weak.Target;
			}
			catch (InvalidOperationException)
			{
				return null;
			}
		}

		public static bool SafeGetIsAlive(this WeakReference weak)
		{
			try
			{
				return weak.IsAlive;
			}
			catch (InvalidOperationException)
			{
				return false;
			}
		}

		public static T CreateDelegate<T>(this MethodBase method) where T : Delegate
		{
			return (T)method.CreateDelegate(typeof(T), null);
		}

		public static T CreateDelegate<T>(this MethodBase method, object target) where T : Delegate
		{
			return (T)method.CreateDelegate(typeof(T), target);
		}

		public static Delegate CreateDelegate(this MethodBase method, Type delegateType)
		{
			return method.CreateDelegate(delegateType, null);
		}

		public static Delegate CreateDelegate(this MethodBase method, Type delegateType, object target)
		{
			if (!typeof(Delegate).IsAssignableFrom(delegateType))
			{
				throw new ArgumentException("Type argument must be a delegate type!");
			}
			if (method is DynamicMethod dynamicMethod)
			{
				return dynamicMethod.CreateDelegate(delegateType, target);
			}
			RuntimeMethodHandle methodHandle = method.MethodHandle;
			RuntimeHelpers.PrepareMethod(methodHandle);
			IntPtr functionPointer = methodHandle.GetFunctionPointer();
			return (Delegate)Activator.CreateInstance(delegateType, target, functionPointer);
		}

		public static MethodDefinition FindMethod(this TypeDefinition type, string id, bool simple = true)
		{
			//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_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<MethodDefinition> enumerator;
			if (simple && !MultiTargetShims.Contains(id, " ", StringComparison.Ordinal))
			{
				enumerator = type.Methods.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						MethodDefinition current = enumerator.Current;
						if (((MethodReference)(object)current).GetID(null, null, withType: true, simple: true) == id)
						{
							return current;
						}
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				enumerator = type.Methods.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						MethodDefinition current2 = enumerator.Current;
						if (((MethodReference)(object)current2).GetID(null, null, withType: false, simple: true) == id)
						{
							return current2;
						}
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			}
			enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current3 = enumerator.Current;
					if (((MethodReference)(object)current3).GetID() == id)
					{
						return current3;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current4 = enumerator.Current;
					if (((MethodReference)(object)current4).GetID(null, null, withType: false) == id)
					{
						return current4;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return null;
		}

		public static MethodDefinition FindMethodDeep(this TypeDefinition type, string id, bool simple = true)
		{
			MethodDefinition obj = type.FindMethod(id, simple);
			if (obj == null)
			{
				TypeReference baseType = type.BaseType;
				if (baseType == null)
				{
					return null;
				}
				TypeDefinition obj2 = baseType.Resolve();
				if (obj2 == null)
				{
					return null;
				}
				obj = obj2.FindMethodDeep(id, simple);
			}
			return obj;
		}

		public static MethodInfo FindMethod(this Type type, string id, bool simple = true)
		{
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			MethodInfo[] array;
			if (simple && !MultiTargetShims.Contains(id, " ", StringComparison.Ordinal))
			{
				array = methods;
				foreach (MethodInfo methodInfo in array)
				{
					if (methodInfo.GetID(null, null, withType: true, proxyMethod: false, simple: true) == id)
					{
						return methodInfo;
					}
				}
				array = methods;
				foreach (MethodInfo methodInfo2 in array)
				{
					if (methodInfo2.GetID(null, null, withType: false, proxyMethod: false, simple: true) == id)
					{
						return methodInfo2;
					}
				}
			}
			array = methods;
			foreach (MethodInfo methodInfo3 in array)
			{
				if (methodInfo3.GetID(null, null, withType: true, proxyMethod: false, simple: false) == id)
				{
					return methodInfo3;
				}
			}
			array = methods;
			foreach (MethodInfo methodInfo4 in array)
			{
				if (methodInfo4.GetID(null, null, withType: false, proxyMethod: false, simple: false) == id)
				{
					return methodInfo4;
				}
			}
			return null;
		}

		public static MethodInfo FindMethodDeep(this Type type, string id, bool simple = true)
		{
			MethodInfo methodInfo = type.FindMethod(id, simple);
			if ((object)methodInfo == null)
			{
				Type? baseType = type.BaseType;
				if ((object)baseType == null)
				{
					return null;
				}
				methodInfo = baseType.FindMethodDeep(id, simple);
			}
			return methodInfo;
		}

		public static PropertyDefinition FindProperty(this TypeDefinition type, string name)
		{
			//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<PropertyDefinition> enumerator = type.Properties.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					PropertyDefinition current = enumerator.Current;
					if (((MemberReference)current).Name == name)
					{
						return current;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return null;
		}

		public static PropertyDefinition FindPropertyDeep(this TypeDefinition type, string name)
		{
			PropertyDefinition obj = type.FindProperty(name);
			if (obj == null)
			{
				TypeReference baseType = type.BaseType;
				if (baseType == null)
				{
					return null;
				}
				TypeDefinition obj2 = baseType.Resolve();
				if (obj2 == null)
				{
					return null;
				}
				obj = obj2.FindPropertyDeep(name);
			}
			return obj;
		}

		public static FieldDefinition FindField(this TypeDefinition type, string name)
		{
			//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<FieldDefinition> enumerator = type.Fields.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					FieldDefinition current = enumerator.Current;
					if (((MemberReference)current).Name == name)
					{
						return current;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return null;
		}

		public static FieldDefinition FindFieldDeep(this TypeDefinition type, string name)
		{
			FieldDefinition obj = type.FindField(name);
			if (obj == null)
			{
				TypeReference baseType = type.BaseType;
				if (baseType == null)
				{
					return null;
				}
				TypeDefinition obj2 = baseType.Resolve();
				if (obj2 == null)
				{
					return null;
				}
				obj = obj2.FindFieldDeep(name);
			}
			return obj;
		}

		public static EventDefinition FindEvent(this TypeDefinition type, string name)
		{
			//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<EventDefinition> enumerator = type.Events.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					EventDefinition current = enumerator.Current;
					if (((MemberReference)current).Name == name)
					{
						return current;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return null;
		}

		public static EventDefinition FindEventDeep(this TypeDefinition type, string name)
		{
			EventDefinition obj = type.FindEvent(name);
			if (obj == null)
			{
				TypeReference baseType = type.BaseType;
				if (baseType == null)
				{
					return null;
				}
				TypeDefinition obj2 = baseType.Resolve();
				if (obj2 == null)
				{
					return null;
				}
				obj = obj2.FindEventDeep(name);
			}
			return obj;
		}

		public static string GetID(this MethodReference method, string name = null, string type = null, bool withType = true, bool simple = false)
		{
			StringBuilder stringBuilder = new StringBuilder();
			if (simple)
			{
				if (withType && (type != null || ((MemberReference)method).DeclaringType != null))
				{
					stringBuilder.Append(type ?? ((MemberReference)(object)((MemberReference)method).DeclaringType).GetPatchFullName()).Append("::");
				}
				stringBuilder.Append(name ?? ((MemberReference)method).Name);
				return stringBuilder.ToString();
			}
			stringBuilder.Append(((MemberReference)(object)method.ReturnType).GetPatchFullName()).Append(" ");
			if (withType && (type != null || ((MemberReference)method).DeclaringType != null))
			{
				stringBuilder.Append(type ?? ((MemberReference)(object)((MemberReference)method).DeclaringType).GetPatchFullName()).Append("::");
			}
			stringBuilder.Append(name ?? ((MemberReference)method).Name);
			GenericInstanceMethod val = (GenericInstanceMethod)(object)((method is GenericInstanceMethod) ? method : null);
			if (val != null && val.GenericArguments.Count != 0)
			{
				stringBuilder.Append("<");
				Collection<TypeReference> genericArguments = val.GenericArguments;
				for (int i = 0; i < genericArguments.Count; i++)
				{
					if (i > 0)
					{
						stringBuilder.Append(",");
					}
					stringBuilder.Append(((MemberReference)(object)genericArguments[i]).GetPatchFullName());
				}
				stringBuilder.Append(">");
			}
			else if (method.GenericParameters.Count != 0)
			{
				stringBuilder.Append("<");
				Collection<GenericParameter> genericParameters = method.GenericParameters;
				for (int j = 0; j < genericParameters.Count; j++)
				{
					if (j > 0)
					{
						stringBuilder.Append(",");
					}
					stringBuilder.Append(((MemberReference)genericParameters[j]).Name);
				}
				stringBuilder.Append(">");
			}
			stringBuilder.Append("(");
			if (method.HasParameters)
			{
				Collection<ParameterDefinition> parameters = method.Parameters;
				for (int k = 0; k < parameters.Count; k++)
				{
					ParameterDefinition val2 = parameters[k];
					if (k > 0)
					{
						stringBuilder.Append(",");
					}
					if (((ParameterReference)val2).ParameterType.IsSentinel)
					{
						stringBuilder.Append("...,");
					}
					stringBuilder.Append(((MemberReference)(object)((ParameterReference)val2).ParameterType).GetPatchFullName());
				}
			}
			stringBuilder.Append(")");
			return stringBuilder.ToString();
		}

		public static string GetID(this CallSite method)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(((MemberReference)(object)method.ReturnType).GetPatchFullName()).Append(" ");
			stringBuilder.Append("(");
			if (method.HasParameters)
			{
				Collection<ParameterDefinition> parameters = method.Parameters;
				for (int i = 0; i < parameters.Count; i++)
				{
					ParameterDefinition val = parameters[i];
					if (i > 0)
					{
						stringBuilder.Append(",");
					}
					if (((ParameterReference)val).ParameterType.IsSentinel)
					{
						stringBuilder.Append("...,");
					}
					stringBuilder.Append(((MemberReference)(object)((ParameterReference)val).ParameterType).GetPatchFullName());
				}
			}
			stringBuilder.Append(")");
			return stringBuilder.ToString();
		}

		public static string GetID(this MethodBase method, string name = null, string type = null, bool withType = true, bool proxyMethod = false, bool simple = false)
		{
			while (method is MethodInfo && method.IsGenericMethod && !method.IsGenericMethodDefinition)
			{
				method = ((MethodInfo)method).GetGenericMethodDefinition();
			}
			StringBuilder stringBuilder = new StringBuilder();
			if (simple)
			{
				if (withType && (type != null || (object)method.DeclaringType != null))
				{
					stringBuilder.Append(type ?? method.DeclaringType.FullName).Append("::");
				}
				stringBuilder.Append(name ?? method.Name);
				return stringBuilder.ToString();
			}
			stringBuilder.Append((method as MethodInfo)?.ReturnType?.FullName ?? "System.Void").Append(" ");
			if (withType && (type != null || (object)method.DeclaringType != null))
			{
				stringBuilder.Append(type ?? MultiTargetShims.Replace(method.DeclaringType.FullName, "+", "/", StringComparison.Ordinal)).Append("::");
			}
			stringBuilder.Append(name ?? method.Name);
			if (method.ContainsGenericParameters)
			{
				stringBuilder.Append("<");
				Type[] genericArguments = method.GetGenericArguments();
				for (int i = 0; i < genericArguments.Length; i++)
				{
					if (i > 0)
					{
						stringBuilder.Append(",");
					}
					stringBuilder.Append(genericArguments[i].Name);
				}
				stringBuilder.Append(">");
			}
			stringBuilder.Append("(");
			ParameterInfo[] parameters = method.GetParameters();
			for (int j = (proxyMethod ? 1 : 0); j < parameters.Length; j++)
			{
				ParameterInfo parameterInfo = parameters[j];
				if (j > (proxyMethod ? 1 : 0))
				{
					stringBuilder.Append(",");
				}
				bool flag;
				try
				{
					flag = parameterInfo.GetCustomAttributes(t_ParamArrayAttribute, inherit: false).Length != 0;
				}
				catch (NotSupportedException)
				{
					flag = false;
				}
				if (flag)
				{
					stringBuilder.Append("...,");
				}
				stringBuilder.Append(parameterInfo.ParameterType.FullName);
			}
			stringBuilder.Append(")");
			return stringBuilder.ToString();
		}

		public static string GetPatchName(this MemberReference mr)
		{
			MemberReference obj = ((mr is ICustomAttributeProvider) ? mr : null);
			return ((obj != null) ? ((ICustomAttributeProvider)(object)obj).GetPatchName() : null) ?? mr.Name;
		}

		public static string GetPatchFullName(this MemberReference mr)
		{
			MemberReference obj = ((mr is ICustomAttributeProvider) ? mr : null);
			return ((obj != null) ? ((ICustomAttributeProvider)(object)obj).GetPatchFullName(mr) : null) ?? mr.FullName;
		}

		private static string GetPatchName(this ICustomAttributeProvider cap)
		{
			//IL_004e: 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_001b: Unknown result type (might be due to invalid IL or missing references)
			CustomAttribute customAttribute = cap.GetCustomAttribute("MonoMod.MonoModPatch");
			string text;
			if (customAttribute != null)
			{
				CustomAttributeArgument val = customAttribute.ConstructorArguments[0];
				text = (string)((CustomAttributeArgument)(ref val)).Value;
				int num = text.LastIndexOf('.');
				if (num != -1 && num != text.Length - 1)
				{
					text = text.Substring(num + 1);
				}
				return text;
			}
			text = ((MemberReference)cap).Name;
			if (!text.StartsWith("patch_", StringComparison.Ordinal))
			{
				return text;
			}
			return text.Substring(6);
		}

		private static string GetPatchFullName(this ICustomAttributeProvider cap, MemberReference mr)
		{
			//IL_003a: 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_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Expected O, but got Unknown
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Expected O, but got Unknown
			//IL_0323: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Expected O, but got Unknown
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			TypeReference val = (TypeReference)(object)((cap is TypeReference) ? cap : null);
			if (val != null)
			{
				CustomAttribute customAttribute = cap.GetCustomAttribute("MonoMod.MonoModPatch");
				string text;
				if (customAttribute != null)
				{
					CustomAttributeArgument val2 = customAttribute.ConstructorArguments[0];
					text = (string)((CustomAttributeArgument)(ref val2)).Value;
				}
				else
				{
					text = ((MemberReference)cap).Name;
					text = (text.StartsWith("patch_", StringComparison.Ordinal) ? text.Substring(6) : text);
				}
				if (text.StartsWith("global::", StringComparison.Ordinal))
				{
					text = text.Substring(8);
				}
				else if (!MultiTargetShims.Contains(text, ".", StringComparison.Ordinal) && !MultiTargetShims.Contains(text, "/", StringComparison.Ordinal))
				{
					if (!string.IsNullOrEmpty(val.Namespace))
					{
						text = val.Namespace + "." + text;
					}
					else if (val.IsNested)
					{
						text = ((MemberReference)(object)((MemberReference)val).DeclaringType).GetPatchFullName() + "/" + text;
					}
				}
				if (mr is TypeSpecification)
				{
					List<TypeSpecification> list = new List<TypeSpecification>();
					TypeSpecification val3 = (TypeSpecification)mr;
					TypeReference elementType;
					do
					{
						list.Add(val3);
						elementType = val3.ElementType;
					}
					while ((val3 = (TypeSpecification)(object)((elementType is TypeSpecification) ? elementType : null)) != null);
					StringBuilder stringBuilder = new StringBuilder(text.Length + list.Count * 4);
					stringBuilder.Append(text);
					for (int num = list.Count - 1; num > -1; num--)
					{
						val3 = list[num];
						if (((TypeReference)val3).IsByReference)
						{
							stringBuilder.Append("&");
						}
						else if (((TypeReference)val3).IsPointer)
						{
							stringBuilder.Append("*");
						}
						else if (!((TypeReference)val3).IsPinned && !((TypeReference)val3).IsSentinel)
						{
							if (((TypeReference)val3).IsArray)
							{
								ArrayType val4 = (ArrayType)val3;
								if (val4.IsVector)
								{
									stringBuilder.Append("[]");
								}
								else
								{
									stringBuilder.Append("[");
									for (int i = 0; i < val4.Dimensions.Count; i++)
									{
										if (i > 0)
										{
											stringBuilder.Append(",");
										}
										ArrayDimension val5 = val4.Dimensions[i];
										stringBuilder.Append(((object)(ArrayDimension)(ref val5)).ToString());
									}
									stringBuilder.Append("]");
								}
							}
							else if (((TypeReference)val3).IsRequiredModifier)
							{
								stringBuilder.Append("modreq(").Append(((RequiredModifierType)val3).ModifierType).Append(")");
							}
							else if (((TypeReference)val3).IsOptionalModifier)
							{
								stringBuilder.Append("modopt(").Append(((OptionalModifierType)val3).ModifierType).Append(")");
							}
							else if (((TypeReference)val3).IsGenericInstance)
							{
								GenericInstanceType val6 = (GenericInstanceType)val3;
								stringBuilder.Append("<");
								for (int j = 0; j < val6.GenericArguments.Count; j++)
								{
									if (j > 0)
									{
										stringBuilder.Append(",");
									}
									stringBuilder.Append(((MemberReference)(object)val6.GenericArguments[j]).GetPatchFullName());
								}
								stringBuilder.Append(">");
							}
							else
							{
								if (!((TypeReference)val3).IsFunctionPointer)
								{
									throw new NotSupportedException($"MonoMod can't handle TypeSpecification: {((MemberReference)val).FullName} ({((object)val).GetType()})");
								}
								FunctionPointerType val7 = (FunctionPointerType)val3;
								stringBuilder.Append(" ").Append(((MemberReference)(object)val7.ReturnType).GetPatchFullName()).Append(" *(");
								if (val7.HasParameters)
								{
									for (int k = 0; k < val7.Parameters.Count; k++)
									{
										ParameterDefinition val8 = val7.Parameters[k];
										if (k > 0)
										{
											stringBuilder.Append(",");
										}
										if (((ParameterReference)val8).ParameterType.IsSentinel)
										{
											stringBuilder.Append("...,");
										}
										stringBuilder.Append(((MemberReference)((ParameterReference)val8).ParameterType).FullName);
									}
								}
								stringBuilder.Append(")");
							}
						}
					}
					text = stringBuilder.ToString();
				}
				return text;
			}
			FieldReference val9 = (FieldReference)(object)((cap is FieldReference) ? cap : null);
			if (val9 != null)
			{
				return ((MemberReference)(object)val9.FieldType).GetPatchFullName() + " " + ((MemberReference)(object)((MemberReference)val9).DeclaringType).GetPatchFullName() + "::" + cap.GetPatchName();
			}
			if (cap is MethodReference)
			{
				throw new InvalidOperationException("GetPatchFullName not supported on MethodReferences - use GetID instead");
			}
			throw new InvalidOperationException($"GetPatchFullName not supported on type {((object)cap).GetType()}");
		}

		public static MethodDefinition Clone(this MethodDefinition o, MethodDefinition c = null)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: 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_00fd: 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_013d: 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_01c9: 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)
			if (o == null)
			{
				return null;
			}
			if (c == null)
			{
				c = new MethodDefinition(((MemberReference)o).Name, o.Attributes, ((MethodReference)o).ReturnType);
			}
			((MemberReference)c).Name = ((MemberReference)o).Name;
			c.Attributes = o.Attributes;
			((MethodReference)c).ReturnType = ((MethodReference)o).ReturnType;
			c.DeclaringType = o.DeclaringType;
			((MemberReference)c).MetadataToken = ((MemberReference)c).MetadataToken;
			c.Body = o.Body?.Clone(c);
			c.Attributes = o.Attributes;
			c.ImplAttributes = o.ImplAttributes;
			c.PInvokeInfo = o.PInvokeInfo;
			c.IsPreserveSig = o.IsPreserveSig;
			c.IsPInvokeImpl = o.IsPInvokeImpl;
			Enumerator<GenericParameter> enumerator = ((MethodReference)o).GenericParameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					GenericParameter current = enumerator.Current;
					((MethodReference)c).GenericParameters.Add(current.Clone());
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<ParameterDefinition> enumerator2 = ((MethodReference)o).Parameters.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					ParameterDefinition current2 = enumerator2.Current;
					((MethodReference)c).Parameters.Add(current2.Clone());
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<CustomAttribute> enumerator3 = o.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					CustomAttribute current3 = enumerator3.Current;
					c.CustomAttributes.Add(current3.Clone());
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodReference> enumerator4 = o.Overrides.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodReference current4 = enumerator4.Current;
					c.Overrides.Add(current4);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			if (c.Body != null)
			{
				Enumerator<Instruction> enumerator5 = c.Body.Instructions.GetEnumerator();
				try
				{
					while (enumerator5.MoveNext())
					{
						Instruction current5 = enumerator5.Current;
						object operand = current5.Operand;
						GenericParameter val = (GenericParameter)((operand is GenericParameter) ? operand : null);
						int num;
						if (val != null && (num = ((MethodReference)o).GenericParameters.IndexOf(val)) != -1)
						{
							current5.Operand = ((MethodReference)c).GenericParameters[num];
							continue;
						}
						object operand2 = current5.Operand;
						ParameterDefinition val2 = (ParameterDefinition)((operand2 is ParameterDefinition) ? operand2 : null);
						if (val2 != null && (num = ((MethodReference)o).Parameters.IndexOf(val2)) != -1)
						{
							current5.Operand = ((MethodReference)c).Parameters[num];
						}
					}
				}
				finally
				{
					((IDisposable)enumerator5).Dispose();
				}
			}
			return c;
		}

		public static MethodBody Clone(this MethodBody bo, MethodDefinition m)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_005b: 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)
			if (bo == null)
			{
				return null;
			}
			MethodBody bc = new MethodBody(m);
			bc.MaxStackSize = bo.MaxStackSize;
			bc.InitLocals = bo.InitLocals;
			bc.LocalVarToken = bo.LocalVarToken;
			bc.Instructions.AddRange(((IEnumerable<Instruction>)bo.Instructions).Select(delegate(Instruction o)
			{
				//IL_0000: 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)
				Instruction obj = Instruction.Create(OpCodes.Nop);
				obj.OpCode = o.OpCode;
				obj.Operand = o.Operand;
				obj.Offset = o.Offset;
				return obj;
			}));
			Enumerator<Instruction> enumerator = bc.Instructions.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					Instruction current = enumerator.Current;
					object operand = current.Operand;
					Instruction val = (Instruction)((operand is Instruction) ? operand : null);
					if (val != null)
					{
						current.Operand = bc.Instructions[bo.Instructions.IndexOf(val)];
					}
					else if (current.Operand is Instruction[] source)
					{
						current.Operand = source.Select((Instruction i) => bc.Instructions[bo.Instructions.IndexOf(i)]).ToArray();
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			bc.ExceptionHandlers.AddRange(((IEnumerable<ExceptionHandler>)bo.ExceptionHandlers).Select((Func<ExceptionHandler, ExceptionHandler>)((ExceptionHandler o) => new ExceptionHandler(o.HandlerType)
			{
				TryStart = ((o.TryStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.TryStart)]),
				TryEnd = ((o.TryEnd == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.TryEnd)]),
				FilterStart = ((o.FilterStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.FilterStart)]),
				HandlerStart = ((o.HandlerStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.HandlerStart)]),
				HandlerEnd = ((o.HandlerEnd == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.HandlerEnd)]),
				CatchType = o.CatchType
			})));
			bc.Variables.AddRange(((IEnumerable<VariableDefinition>)bo.Variables).Select((Func<VariableDefinition, VariableDefinition>)((VariableDefinition o) => new VariableDefinition(((VariableReference)o).VariableType))));
			m.CustomDebugInformations.AddRange((IEnumerable<CustomDebugInformation>)bo.Method.CustomDebugInformations);
			m.DebugInformation.SequencePoints.AddRange(((IEnumerable<SequencePoint>)bo.Method.DebugInformation.SequencePoints).Select((Func<SequencePoint, SequencePoint>)((SequencePoint o) => new SequencePoint(((IEnumerable<Instruction>)bc.Instructions).FirstOrDefault((Func<Instruction, bool>)((Instruction i) => i.Offset == o.Offset)), o.Document)
			{
				StartLine = o.StartLine,
				StartColumn = o.StartColumn,
				EndLine = o.EndLine,
				EndColumn = o.EndColumn
			})));
			return bc;
		}

		public static GenericParameter Update(this GenericParameter param, int position, GenericParameterType type)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			f_GenericParameter_position.SetValue(param, position);
			f_GenericParameter_type.SetValue(param, type);
			return param;
		}

		public static GenericParameter ResolveGenericParameter(this IGenericParameterProvider provider, GenericParameter orig)
		{
			//IL_002d: 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_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			if (provider is GenericParameter && ((MemberReference)(GenericParameter)provider).Name == ((MemberReference)orig).Name)
			{
				return (GenericParameter)provider;
			}
			Enumerator<GenericParameter> enumerator = provider.GenericParameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					GenericParameter current = enumerator.Current;
					if (((MemberReference)current).Name == ((MemberReference)orig).Name)
					{
						return current;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			int position = orig.Position;
			if (provider is MethodReference && orig.DeclaringMethod != null)
			{
				if (position < provider.GenericParameters.Count)
				{
					return provider.GenericParameters[position];
				}
				return orig.Clone().Update(position, (GenericParameterType)1);
			}
			if (provider is TypeReference && ((MemberReference)orig).DeclaringType != null)
			{
				if (position < provider.GenericParameters.Count)
				{
					return provider.GenericParameters[position];
				}
				return orig.Clone().Update(position, (GenericParameterType)0);
			}
			IGenericParameterProvider obj = ((provider is TypeSpecification) ? provider : null);
			object obj2 = ((obj != null) ? ((IGenericParameterProvider)(object)((TypeSpecification)obj).ElementType).ResolveGenericParameter(orig) : null);
			if (obj2 == null)
			{
				IGenericParameterProvider obj3 = ((provider is MemberReference) ? provider : null);
				if (obj3 == null)
				{
					return null;
				}
				TypeReference declaringType = ((MemberReference)obj3).DeclaringType;
				if (declaringType == null)
				{
					return null;
				}
				obj2 = ((IGenericParameterProvider)(object)declaringType).ResolveGenericParameter(orig);
			}
			return (GenericParameter)obj2;
		}

		public static IMetadataTokenProvider Relink(this IMetadataTokenProvider mtp, Relinker relinker, IGenericParameterProvider context)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			if (mtp is TypeReference)
			{
				return (IMetadataTokenProvider)(object)Extensions.Relink((TypeReference)mtp, relinker, context);
			}
			if (mtp is MethodReference)
			{
				return Extensions.Relink((MethodReference)mtp, relinker, context);
			}
			if (mtp is FieldReference)
			{
				return Extensions.Relink((FieldReference)mtp, relinker, context);
			}
			if (mtp is ParameterDefinition)
			{
				return (IMetadataTokenProvider)(object)Extensions.Relink((ParameterDefinition)mtp, relinker, context);
			}
			if (mtp is CallSite)
			{
				return (IMetadataTokenProvider)(object)Extensions.Relink((CallSite)mtp, relinker, context);
			}
			throw new InvalidOperationException($"MonoMod can't handle metadata token providers of the type {((object)mtp).GetType()}");
		}

		public static TypeReference Relink(this TypeReference type, Relinker relinker, IGenericParameterProvider context)
		{
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Expected O, but got Unknown
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			//IL_00af: 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_00c7: Expected O, but got Unknown
			//IL_00d0: 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_00e8: Expected O, but got Unknown
			//IL_0082: 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_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Expected O, but got Unknown
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			if (type == null)
			{
				return null;
			}
			TypeSpecification val = (TypeSpecification)(object)((type is TypeSpecification) ? type : null);
			if (val != null)
			{
				TypeReference val2 = val.ElementType.Relink(relinker, context);
				if (type.IsSentinel)
				{
					return (TypeReference)new SentinelType(val2);
				}
				if (type.IsByReference)
				{
					return (TypeReference)new ByReferenceType(val2);
				}
				if (type.IsPointer)
				{
					return (TypeReference)new PointerType(val2);
				}
				if (type.IsPinned)
				{
					return (TypeReference)new PinnedType(val2);
				}
				if (type.IsArray)
				{
					ArrayType val3 = new ArrayType(val2, ((ArrayType)type).Rank);
					for (int i = 0; i < val3.Rank; i++)
					{
						val3.Dimensions[i] = ((ArrayType)type).Dimensions[i];
					}
					return (TypeReference)(object)val3;
				}
				if (type.IsRequiredModifier)
				{
					return (TypeReference)new RequiredModifierType(((RequiredModifierType)type).ModifierType.Relink(relinker, context), val2);
				}
				if (type.IsOptionalModifier)
				{
					return (TypeReference)new OptionalModifierType(((OptionalModifierType)type).ModifierType.Relink(relinker, context), val2);
				}
				if (type.IsGenericInstance)
				{
					GenericInstanceType val4 = new GenericInstanceType(val2);
					Enumerator<TypeReference> enumerator = ((GenericInstanceType)type).GenericArguments.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							TypeReference current = enumerator.Current;
							val4.GenericArguments.Add(current?.Relink(relinker, context));
						}
						return (TypeReference)(object)val4;
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (type.IsFunctionPointer)
				{
					FunctionPointerType val5 = (FunctionPointerType)type;
					val5.ReturnType = val5.ReturnType.Relink(relinker, context);
					for (int j = 0; j < val5.Parameters.Count; j++)
					{
						((ParameterReference)val5.Parameters[j]).ParameterType = ((ParameterReference)val5.Parameters[j]).ParameterType.Relink(relinker, context);
					}
					return (TypeReference)(object)val5;
				}
				throw new NotSupportedException($"MonoMod can't handle TypeSpecification: {((MemberReference)type).FullName} ({((object)type).GetType()})");
			}
			if (!type.IsGenericParameter || context == null)
			{
				return (TypeReference)relinker((IMetadataTokenProvider)(object)type, context);
			}
			GenericParameter val6 = context.ResolveGenericParameter((GenericParameter)type);
			if (val6 == null)
			{
				throw new RelinkTargetNotFoundException(string.Format("{0} {1} (context: {2})", "MonoMod relinker failed finding", ((MemberReference)type).FullName, context), (IMetadataTokenProvider)(object)type, (IMetadataTokenProvider)(object)context);
			}
			for (int k = 0; k < val6.Constraints.Count; k++)
			{
				if (!val6.Constraints[k].GetConstraintType().IsGenericInstance)
				{
					val6.Constraints[k] = val6.Constraints[k].Relink(relinker, context);
				}
			}
			return (TypeReference)(object)val6;
		}

		public static IMetadataTokenProvider Relink(this MethodReference method, Relinker relinker, IGenericParameterProvider context)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Expected O, but got Unknown
			if (method.IsGenericInstance)
			{
				GenericInstanceMethod val = (GenericInstanceMethod)method;
				GenericInstanceMethod val2 = new GenericInstanceMethod((MethodReference)((MethodSpecification)val).ElementMethod.Relink(relinker, context));
				Enumerator<TypeReference> enumerator = val.GenericArguments.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						TypeReference current = enumerator.Current;
						val2.GenericArguments.Add(current.Relink(relinker, context));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				return (IMetadataTokenProvider)(MethodReference)relinker((IMetadataTokenProvider)(object)val2, context);
			}
			MethodReference val3 = new MethodReference(((MemberReference)method).Name, method.ReturnType, ((MemberReference)method).DeclaringType.Relink(relinker, context));
			val3.CallingConvention = method.CallingConvention;
			val3.ExplicitThis = method.ExplicitThis;
			val3.HasThis = method.HasThis;
			Enumerator<GenericParameter> enumerator2 = method.GenericParameters.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					GenericParameter current2 = enumerator2.Current;
					val3.GenericParameters.Add(current2.Relink(relinker, context));
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			val3.ReturnType = val3.ReturnType?.Relink(relinker, (IGenericParameterProvider)(object)val3);
			Enumerator<ParameterDefinition> enumerator3 = method.Parameters.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					ParameterDefinition current3 = enumerator3.Current;
					((ParameterReference)current3).ParameterType = ((ParameterReference)current3).ParameterType.Relink(relinker, (IGenericParameterProvider)(object)method);
					val3.Parameters.Add(current3);
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			retur

BooBoo Building/BepInEx/patchers/Evaisa-HookGenPatcher/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;
	}
}

BooBoo Building/BepInEx/patchers/Evaisa-HookGenPatcher/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

BooBoo Building/BepInEx/patchers/Evaisa-HookGenPatcher/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();
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/2018-LC_API/LC_API.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("")]
[assembly: AssemblyCompany("2018")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Utilities for plugin devs")]
[assembly: AssemblyFileVersion("3.2.2.0")]
[assembly: AssemblyInformationalVersion("3.2.2+e96d87362270a53aa685ebd58208893259059f3c")]
[assembly: AssemblyProduct("Lethal Company API")]
[assembly: AssemblyTitle("LC_API")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("3.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LC_API
{
	internal static class CheatDatabase
	{
		private const string SIG_REQ_GUID = "LC_API_ReqGUID";

		private const string SIG_SEND_MODS = "LC_APISendMods";

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

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

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

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

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

		private ConfigEntry<bool> configOverrideModServer;

		private ConfigEntry<bool> configLegacyAssetLoading;

		private ConfigEntry<bool> configDisableBundleLoader;

		internal static Harmony Harmony;

		internal static Plugin Instance { get; private set; }

		public static bool Initialized { get; private set; }

		private void Awake()
		{
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Expected O, but got Unknown
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Expected O, but got Unknown
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Expected O, but got Unknown
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Expected O, but got Unknown
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Expected O, but got Unknown
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Expected O, but got Unknown
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Expected O, but got Unknown
			Instance = this;
			configOverrideModServer = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Force modded server browser", false, "Should the API force you into the modded server browser?");
			configLegacyAssetLoading = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Legacy asset bundle loading", false, "Should the BundleLoader use legacy asset loading? Turning this on may help with loading assets from older plugins.");
			configDisableBundleLoader = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Disable BundleLoader", false, "Should the BundleLoader be turned off? Enable this if you are having problems with mods that load assets using a different method from LC_API's BundleLoader.");
			CommandHandler.commandPrefix = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Prefix", "/", "Command prefix");
			Log = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogWarning((object)"\n.____    _________           _____  __________ .___  \r\n|    |   \\_   ___ \\         /  _  \\ \\______   \\|   | \r\n|    |   /    \\  \\/        /  /_\\  \\ |     ___/|   | \r\n|    |___\\     \\____      /    |    \\|    |    |   | \r\n|_______ \\\\______  /______\\____|__  /|____|    |___| \r\n        \\/       \\//_____/        \\/                 \r\n                                                     ");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Starting up..");
			if (configOverrideModServer.Value)
			{
				ModdedServer.SetServerModdedOnly();
			}
			Harmony = new Harmony("ModAPI");
			MethodInfo methodInfo = AccessTools.Method(typeof(GameNetworkManager), "SteamMatchmaking_OnLobbyCreated", (Type[])null, (Type[])null);
			AccessTools.Method(typeof(GameNetworkManager), "LobbyDataIsJoinable", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(ServerPatch), "OnLobbyCreate", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(MenuManager), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(ServerPatch), "CacheMenuManager", (Type[])null, (Type[])null);
			AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(typeof(HUDManager), "SubmitChat_performed", (Type[])null, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.Method(typeof(CommandHandler.SubmitChatPatch), "Transpiler", (Type[])null, (Type[])null);
			MethodInfo methodInfo7 = AccessTools.Method(typeof(GameNetworkManager), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo8 = AccessTools.Method(typeof(ServerPatch), "GameNetworkManagerAwake", (Type[])null, (Type[])null);
			MethodInfo methodInfo9 = AccessTools.Method(typeof(NetworkManager), "StartClient", (Type[])null, (Type[])null);
			MethodInfo methodInfo10 = AccessTools.Method(typeof(NetworkManager), "StartHost", (Type[])null, (Type[])null);
			MethodInfo methodInfo11 = AccessTools.Method(typeof(NetworkManager), "Shutdown", (Type[])null, (Type[])null);
			MethodInfo methodInfo12 = AccessTools.Method(typeof(RegisterPatch), "Postfix", (Type[])null, (Type[])null);
			MethodInfo methodInfo13 = AccessTools.Method(typeof(UnregisterPatch), "Postfix", (Type[])null, (Type[])null);
			Harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo7, new HarmonyMethod(methodInfo8), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo9, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo10, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo11, (HarmonyMethod)null, new HarmonyMethod(methodInfo13), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Network.Init();
			Events.Patch(Harmony);
		}

		internal void Start()
		{
			Initialize();
		}

		internal void OnDestroy()
		{
			Initialize();
		}

		internal void Initialize()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			if (!Initialized)
			{
				Initialized = true;
				if (!configDisableBundleLoader.Value)
				{
					BundleLoader.Load(configLegacyAssetLoading.Value);
				}
				GameObject val = new GameObject("API");
				Object.DontDestroyOnLoad((Object)val);
				val.AddComponent<LC_APIManager>();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Started!");
				CheatDatabase.RunLocalCheatDetector();
			}
		}

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

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

		public const string PLUGIN_NAME = "Lethal Company API";

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

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

		public static int GameVersion { get; internal set; }

		public static bool ModdedOnly => moddedOnly;

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

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

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

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

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

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

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

		public static void Broadcast(string data, string signature)
		{
			if (data.Contains("/"))
			{
				Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )");
				return;
			}
			HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data + "/" + signature + "/" + NetworkBroadcastDataType.BDstring.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1);
		}

		public static void Broadcast(List<string> data, string signature)
		{
			string text = "";
			foreach (string datum in data)
			{
				if (datum.Contains("/"))
				{
					Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )");
					return;
				}
				if (datum.Contains("\n"))
				{
					Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( NewLine )");
					return;
				}
				text = text + datum + "\n";
			}
			HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data?.ToString() + "/" + signature + "/" + NetworkBroadcastDataType.BDlistString.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1);
		}

		public static void Broadcast(int data, string signature)
		{
			HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data + "/" + signature + "/" + NetworkBroadcastDataType.BDint.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1);
		}

		public static void Broadcast(float data, string signature)
		{
			HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data + "/" + signature + "/" + NetworkBroadcastDataType.BDfloat.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1);
		}

		public static void Broadcast(Vector3 data, string signature)
		{
			//IL_0016: 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)
			HUDManager instance = HUDManager.Instance;
			string[] obj = new string[9] { "<size=0>NWE/", null, null, null, null, null, null, null, null };
			Vector3 val = data;
			obj[1] = ((object)(Vector3)(ref val)).ToString();
			obj[2] = "/";
			obj[3] = signature;
			obj[4] = "/";
			obj[5] = NetworkBroadcastDataType.BDvector3.ToString();
			obj[6] = "/";
			obj[7] = GameNetworkManager.Instance.localPlayerController.playerClientId.ToString();
			obj[8] = "/</size>";
			instance.AddTextToChatOnServer(string.Concat(obj), -1);
		}

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

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

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

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

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

		private static void GotString(string data, string signature)
		{
		}

		private static void GotInt(int data, string signature)
		{
		}

		private static void GotFloat(float data, string signature)
		{
		}

		private static void GotVector3(Vector3 data, string signature)
		{
		}

		internal static void SetupNetworking()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			for (int i = 0; i < types.Length; i++)
			{
				MethodInfo[] methods = types[i].GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}
	}
}
namespace LC_API.Networking
{
	public static class Network
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static HandleNamedMessageDelegate <>9__35_2;

			public static Events.CustomEventHandler <>9__35_0;

			public static Events.CustomEventHandler <>9__35_1;

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

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

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

		internal const string MESSAGE_RELAY_UNIQUE_NAME = "LC_API_RELAY_MESSAGE";

		private static MethodInfo _registerInfo = null;

		private static MethodInfo _registerInfoGeneric = null;

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


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


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

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

		public static event Events.CustomEventHandler RegisterNetworkMessages;

		internal static event Events.CustomEventHandler UnregisterNetworkMessages;

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

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

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

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

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

		internal static void UnregisterAllMessages()
		{
			string[] array = NetworkMessageFinalizers.Keys.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				UnregisterMessage(array[i]);
			}
		}

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

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

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

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

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

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

		public static void UnregisterMessage(string uniqueName)
		{
			if (NetworkMessageFinalizers.Remove(uniqueName))
			{
				NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler(uniqueName);
			}
		}

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

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

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

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

		public bool RelayToSelf { get; }

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

		internal abstract bool RelayToSelf { get; }

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

		internal override bool RelayToSelf { get; }

		internal Action<ulong> OnReceived { get; }

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

		public void Send()
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater());
				return;
			}
			byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId).ToBytes();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
				if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)3);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)3);
				}
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

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

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

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

		internal override bool RelayToSelf { get; }

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

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

		public void Send(T obj)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater(obj));
				return;
			}
			byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId, obj.ToBytes()).ToBytes();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
				if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)3);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)3);
				}
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

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

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

		private IEnumerator ReadLater(ulong fakeSender, FastBufferReader reader)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to read network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Read(fakeSender, reader);
		}
	}
	internal class NetworkMessageWrapper
	{
		public string UniqueName { get; set; }

		public ulong Sender { get; set; }

		public byte[] Message { get; set; }

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

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

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

		public float x { get; set; }

		public float y { get; set; }

		[JsonIgnore]
		public Vector2 vector2
		{
			get
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				if (!v2.HasValue)
				{
					v2 = new Vector2(x, y);
				}
				return v2.Value;
			}
		}

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

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

		public static implicit operator Vector2S(Vector2 vector2)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return new Vector2S(vector2.x, vector2.y);
		}
	}
	public struct Vector2IntS
	{
		private Vector2Int? v2;

		public int x { get; set; }

		public int y { get; set; }

		[JsonIgnore]
		public Vector2Int vector2
		{
			get
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				if (!v2.HasValue)
				{
					v2 = new Vector2Int(x, y);
				}
				return v2.Value;
			}
		}

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

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

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

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

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

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

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

		public static implicit operator Vector3S(Vector3 vector3)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3S(vector3.x, vector3.y, vector3.z);
		}
	}
	public struct Vector3IntS
	{
		private Vector3Int? v3;

		public int x { get; set; }

		public int y { get; set; }

		public int z { get; set; }

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

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

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

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

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public float w { get; set; }

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

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

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

		public static implicit operator Vector4S(Vector4 vector4)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector4S(vector4.x, vector4.y, vector4.z, vector4.w);
		}
	}
	public struct QuaternionS
	{
		private Quaternion? q;

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public float w { get; set; }

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

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

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

		public static implicit operator QuaternionS(Quaternion quaternion)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new QuaternionS(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
		}
	}
	public struct ColorS
	{
		private Color? c;

		public float r { get; set; }

		public float g { get; set; }

		public float b { get; set; }

		public float a { get; set; }

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

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

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

		public static implicit operator ColorS(Color color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new ColorS(color.r, color.g, color.b, color.a);
		}
	}
	public struct Color32S
	{
		private Color32? c;

		public byte r { get; set; }

		public byte g { get; set; }

		public byte b { get; set; }

		public byte a { get; set; }

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

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

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

		public static implicit operator Color32S(Color32 color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Color32S(color.r, color.g, color.b, color.a);
		}
	}
	public struct RayS
	{
		private Ray? r;

		public Vector3S origin { get; set; }

		public Vector3S direction { get; set; }

		[JsonIgnore]
		public Ray Ray
		{
			get
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				if (!r.HasValue)
				{
					r = new Ray((Vector3)origin, (Vector3)direction);
				}
				return r.Value;
			}
		}

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

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

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

		public Vector2S origin { get; set; }

		public Vector2S direction { get; set; }

		[JsonIgnore]
		public Ray2D Ray
		{
			get
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				if (!r.HasValue)
				{
					r = new Ray2D((Vector2)origin, (Vector2)direction);
				}
				return r.Value;
			}
		}

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

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

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

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

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

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

		public static int AlivePlayerCount { get; private set; }

		public static ShipState ShipState { get; private set; }

		public static event Action PlayerDied;

		public static event Action LandOnMoon;

		public static event Action WentIntoOrbit;

		public static event Action ShipStartedLeaving;

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

		static GameState()
		{
			GameState.PlayerDied = NothingAction;
			GameState.LandOnMoon = NothingAction;
			GameState.WentIntoOrbit = NothingAction;
			GameState.ShipStartedLeaving = NothingAction;
		}
	}
	public class GameTips
	{
		private static List<string> tipHeaders = new List<string>();

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

		private static float lastMessageTime;

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

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

		internal static GameObject ItemNetworkPrefab { get; set; }

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


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

		public GrabbableObject GrabbableObject { get; private set; }

		public Item ItemProperties => GrabbableObject.itemProperties;

		public ScanNodeProperties ScanNodeProperties { get; set; }

		public bool IsHeld => GrabbableObject.isHeld;

		public bool IsTwoHanded => ItemProperties.twoHanded;

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

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

		public Vector3 Position
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return ((Component)GrabbableObject).transform.position;
			}
			set
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set item position on client.");
				}
				GrabbableObject.startFallingPosition = value;
				GrabbableObject.targetFloorPosition = value;
				((Component)GrabbableObject).transform.position = value;
				SetItemPositionClientRpc(value);
			}
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

		public void RemoveFromHolder(Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion))
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to remove item from player on client.");
			}
			if (IsHeld)
			{
				((NetworkBehaviour)this).NetworkObject.RemoveOwnership();
				Holder.Inventory.RemoveItem(this);
				RemoveFromHolderClientRpc();
				Position = position;
				Rotation = rotation;
			}
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			[ServerRpc]
			private void SetSlotServerRpc(int slot, ServerRpcParams serverRpcParams = default(ServerRpcParams))
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_00df: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e9: Invalid comparison between Unknown and I4
				//IL_010e: Unknown result type (might be due to invalid IL or missing references)
				//IL_010f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
				//IL_007a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0084: Invalid comparison between Unknown and I4
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
					{
						if ((int)networkManager.LogLevel <= 1)
						{
							Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
						}
						return;
					}
					FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1475903090u, serverRpcParams, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val, slot);
					((NetworkBehaviour)this).__endSendServerRpc(ref val, 1475903090u, serverRpcParams, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && serverRpcParams.Receive.SenderClientId == Player.ClientId)
				{
					SetSlotClientRpc(slot);
				}
			}

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

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

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

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

			public bool TryAddItemToSlot(Item item, int slot, bool switchTo = true)
			{
				//IL_007a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to add item from client.");
				}
				if (slot < Player.PlayerController.ItemSlots.Length && (Object)(object)Player.PlayerController.ItemSlots[slot] == (Object)null)
				{
					if (item.IsTwoHanded && !Player.HasFreeHands)
					{
						return false;
					}
					if (item.IsHeld)
					{
						item.RemoveFromHolder();
					}
					((NetworkBehaviour)item).NetworkObject.ChangeOwnership(Player.ClientId);
					if (item.IsTwoHanded)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (switchTo && Player.HasFreeHands)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (Player.PlayerController.currentItemSlot == slot)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else
					{
						SetItemInSlotClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					return true;
				}
				return false;
			}

			[ClientRpc]
			private void SetItemInSlotClientRpc(int slot, ulong itemId)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b0: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might b

BooBoo Building/BepInEx/plugins/5Bit-FPSSpectate/FPSSpectate.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("FPSSpectate")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("FPS spectate camera")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+ada41809ef3e18d1ac6f547212c170f1debd12d4")]
[assembly: AssemblyProduct("FPSSpectate")]
[assembly: AssemblyTitle("FPSSpectate")]
[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 FPSSpectate
{
	[BepInPlugin("5Bit.FPSSpectate", "FPSSpectate", "1.0.0")]
	public class FPSSpectate : BaseUnityPlugin
	{
		private const string modGUID = "5Bit.FPSSpectate";

		private const string modName = "FPSSpectate";

		private const string modVersion = "1.0.0";

		private readonly Harmony harmony = new Harmony("5Bit.FPSSpectate");

		private static FPSSpectate Instance;

		internal static ManualLogSource mls;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("5Bit.FPSSpectate");
			harmony.PatchAll();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FPSSpectate";

		public const string PLUGIN_NAME = "FPSSpectate";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace FPSSpectate.Patches
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class FPSSpectatePatch
	{
		private const float SPECTATE_OFFSET = 1.5f;

		private static bool firstPerson = true;

		private static bool debounced = false;

		[HarmonyPatch("LateUpdate")]
		[HarmonyPostfix]
		private static void LateUpdate(PlayerControllerB __instance)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			if (((ButtonControl)Keyboard.current.vKey).wasPressedThisFrame && !debounced)
			{
				firstPerson = !firstPerson;
				debounced = true;
			}
			if (((ButtonControl)Keyboard.current.vKey).wasReleasedThisFrame)
			{
				debounced = false;
			}
			if ((Object)(object)__instance.spectatedPlayerScript != (Object)null && firstPerson)
			{
				Transform transform = ((Component)__instance.spectateCameraPivot).transform;
				Transform transform2 = ((Component)__instance.spectatedPlayerScript.visorCamera).transform;
				Vector3 position = transform2.position;
				Vector3 forward = transform2.forward;
				transform.position = position + ((Vector3)(ref forward)).normalized * 1.5f;
				transform.rotation = transform2.rotation;
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/AlexCodesGames-AdditionalSuits/AdditionalSuits.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("AdditionalSuits")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AdditionalSuits")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("0c25b026-8574-4dd2-9af2-4265f618ef8a")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace AdditionalSuits;

[Serializable]
public class UnlockableSuitDef
{
	public string suitID;

	public string suitName;

	public string suitTexture;
}
public class UnlockableSuitDefListing
{
	public List<UnlockableSuitDef> unlockableSuits = new List<UnlockableSuitDef>();
}
[BepInPlugin("ACS.AdditionalSuits", "AdditionalSuits", "1.1.3")]
public class AdditionalSuitsBase : BaseUnityPlugin
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class acgAdditionalSuitsPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void acsStartOfRoundPatch(StartOfRound __instance)
		{
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Expected O, but got Unknown
			try
			{
				if (SuitsLoaded)
				{
					return;
				}
				UnlockableItem val = null;
				for (int i = 0; i < __instance.unlockablesList.unlockables.Count; i++)
				{
					UnlockableItem val2 = __instance.unlockablesList.unlockables[i];
					if (!((Object)(object)val2.suitMaterial == (Object)null) && val2.alreadyUnlocked)
					{
						val = val2;
						break;
					}
				}
				string text = Path.Combine(ModResourceFolder, "suit-defs.json");
				AddLog("attempting to parse json file: " + text);
				string text2 = File.ReadAllText(text);
				if (text2 == null)
				{
					AddLog("ERROR: json file was not found");
					return;
				}
				AddLog("converting json file to manifest...");
				string[] array = text2.Split(new char[1] { '[' });
				array = array[1].Split(new char[1] { ']' });
				array = array[0].Split(new char[1] { '{' });
				SuitDefManifest = new UnlockableSuitDefListing();
				for (int j = 1; j < array.Length; j++)
				{
					string text3 = "{" + array[j].Trim();
					if (j != array.Length - 1)
					{
						text3 = text3.Substring(0, text3.Length - 1);
					}
					UnlockableSuitDef item = JsonUtility.FromJson<UnlockableSuitDef>(text3);
					SuitDefManifest.unlockableSuits.Add(item);
				}
				AddLog("attempting to parse json file:  items were found...");
				foreach (UnlockableSuitDef unlockableSuit in SuitDefManifest.unlockableSuits)
				{
					AddLog("processing custom suit {id=" + unlockableSuit.suitID + ", name=" + unlockableSuit.suitName + "}...");
					UnlockableItem val3 = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)val));
					Texture2D val4 = new Texture2D(2, 2);
					ImageConversion.LoadImage(val4, File.ReadAllBytes(Path.Combine(ModResourceFolder, unlockableSuit.suitTexture)));
					Material val5 = Object.Instantiate<Material>(val3.suitMaterial);
					val5.mainTexture = (Texture)(object)val4;
					val3.suitMaterial = val5;
					val3.unlockableName = unlockableSuit.suitName;
					__instance.unlockablesList.unlockables.Add(val3);
					mls.LogInfo((object)("AdditionalSuits - added custom suit {id=" + unlockableSuit.suitID + ", name=" + unlockableSuit.suitName + "}!"));
				}
				mls.LogInfo((object)"AdditionalSuits - loaded item defs from json file!");
				SuitsLoaded = true;
			}
			catch (Exception ex)
			{
				mls.LogInfo((object)("AdditionalSuits - initialization failed!\nERROR: " + ex));
			}
		}
	}

	private static AdditionalSuitsBase Instance;

	private const string modGUID = "ACS.AdditionalSuits";

	private const string modName = "AdditionalSuits";

	private const string modVersion = "1.1.3";

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

	private static ManualLogSource mls;

	public static bool SuitsLoaded;

	public static string ModResourceFolder;

	public static UnlockableSuitDefListing SuitDefManifest;

	public string ModGUID => "ACS.AdditionalSuits";

	public string ModName => "AdditionalSuits";

	public string ModVersion => "1.1.3";

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

	private void Awake()
	{
		if ((Object)(object)Instance == (Object)null)
		{
			Instance = this;
		}
		mls = Logger.CreateLogSource("ACS.AdditionalSuits");
		AddLog("initializing...");
		ModResourceFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "resAdditionalSuits");
		harmony.PatchAll();
		AddLog("initialized!");
	}
}

BooBoo Building/BepInEx/plugins/anormaltwig-TerminalExtras/LethalAPI.TerminalCommands.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalAPI.TerminalCommands.Attributes;
using LethalAPI.TerminalCommands.Commands;
using LethalAPI.TerminalCommands.Configs;
using LethalAPI.TerminalCommands.Models;
using LethalAPI.TerminalCommands.Patches;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

[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("ShimmyMySherbet, LethalAPI Modding Team")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A library that allows the creation of custom terminal commands for Lethal Company mods")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+5290c6d02b20cc3e4c96dd09d0f7234c78366019")]
[assembly: AssemblyProduct("LethalAPI.TerminalCommands")]
[assembly: AssemblyTitle("LethalAPI.TerminalCommands")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/LethalCompany/LethalAPI.TerminalCommands")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.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 LethalAPI.TerminalCommands
{
	[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
	public static class ParseSentencePatch
	{
		[HarmonyPrefix]
		public static bool ParsePrefix(Terminal __instance, ref TerminalNode __state)
		{
			__state = null;
			string command = __instance.screenText.text.Substring(__instance.screenText.text.Length - __instance.textAdded);
			__state = CommandHandler.TryExecute(command, __instance);
			return (Object)(object)__state == (Object)null;
		}

		[HarmonyPostfix]
		public static TerminalNode ParsePostfix(TerminalNode __result, TerminalNode __state, Terminal __instance)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Invalid comparison between Unknown and I4
			if ((Object)(object)__state != (Object)null)
			{
				TerminalSubmitPatch.LastNode = __state;
				return __state;
			}
			if ((int)__instance.videoPlayer.source == 1)
			{
				__instance.videoPlayer.source = (VideoSource)0;
			}
			TerminalSubmitPatch.LastNode = __result;
			return __result;
		}
	}
	[BepInPlugin("LethalAPI.TerminalCommands", "LethalAPI.TerminalCommands", "1.1.0")]
	public class TerminalCommandsPlugin : BaseUnityPlugin
	{
		private Harmony HarmonyInstance = new Harmony("LethalAPI.TerminalCommands");

		private TerminalModRegistry Terminal;

		private TerminalConfig TerminalConfig;

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LethalAPI.TerminalCommands is loading...");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Installing patches");
			HarmonyInstance.PatchAll(typeof(TerminalCommandsPlugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Registering built-in Commands");
			Terminal = TerminalRegistry.CreateTerminalRegistry();
			Terminal.RegisterFrom<CommandInfoCommands>();
			TerminalConfig = Terminal.RegisterFrom<TerminalConfig>();
			Object.DontDestroyOnLoad((Object)(object)this);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LethalAPI.TerminalCommands is loaded!");
		}
	}
	public static class TerminalExtensions
	{
		public static void PlayVideoFile(this Terminal terminal, string filePath)
		{
			string url = "file:///" + filePath.Replace('\\', '/');
			terminal.PlayVideoLink(url);
		}

		public static void PlayVideoLink(this Terminal terminal, Uri url)
		{
			((MonoBehaviour)terminal).StartCoroutine(PlayVideoLink(url.AbsoluteUri, terminal));
		}

		public static void PlayVideoLink(this Terminal terminal, string url)
		{
			((MonoBehaviour)terminal).StartCoroutine(PlayVideoLink(url, terminal));
		}

		private static IEnumerator PlayVideoLink(string url, Terminal terminal)
		{
			yield return (object)new WaitForFixedUpdate();
			((Behaviour)terminal.terminalImage).enabled = true;
			terminal.terminalImage.texture = (Texture)(object)terminal.videoTexture;
			terminal.displayingPersistentImage = null;
			terminal.videoPlayer.clip = null;
			terminal.videoPlayer.source = (VideoSource)1;
			terminal.videoPlayer.url = url;
			((Behaviour)terminal.videoPlayer).enabled = true;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LethalAPI.TerminalCommands";

		public const string PLUGIN_NAME = "LethalAPI.TerminalCommands";

		public const string PLUGIN_VERSION = "1.1.0";
	}
}
namespace LethalAPI.TerminalCommands.Patches
{
	[HarmonyPatch(typeof(Terminal), "selectTextFieldDelayed")]
	public static class SelectTextFieldPatch
	{
		[HarmonyPrefix]
		public static bool Prefix()
		{
			return false;
		}

		[HarmonyPostfix]
		public static void Postfix(Terminal __instance, ref IEnumerator __result)
		{
			__result = Patch(__instance);
		}

		private static IEnumerator Patch(Terminal terminal)
		{
			yield return (object)new WaitForSeconds(0.2f);
			terminal.screenText.ActivateInputField();
			((Selectable)terminal.screenText).Select();
		}
	}
	[HarmonyPatch(typeof(Terminal), "OnSubmit")]
	public static class TerminalSubmitPatch
	{
		private static ManualLogSource m_LogSource = new ManualLogSource("LethalAPI.TerminalCommands");

		public static TerminalNode LastNode { get; set; }

		[HarmonyPrefix]
		public static void Prefix()
		{
			LastNode = null;
		}

		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			CodeInstruction[] array = instructions.ToArray();
			for (int num = array.Length - 1; num >= 0; num--)
			{
				if (!(array[num].opcode != OpCodes.Callvirt))
				{
					if (array[num + 1].opcode != OpCodes.Ldarg_0)
					{
						ReportTranspileError("Ldarg_0 expected after final callVirt, not found");
						return array;
					}
					array[num + 1] = new CodeInstruction(OpCodes.Ret, (object)null);
					return array;
				}
			}
			ReportTranspileError("Failed to find Callvirt in backward scan");
			return array;
		}

		private static void ReportTranspileError(string message)
		{
			m_LogSource.LogError((object)("Failed to transpile OnSubmit to remove Scroll To Bottom. Did the method get modified in an update? (" + message + ")"));
			m_LogSource.LogWarning((object)"This won't break the mod, but it will cause some odd terminal scrolling behavior");
		}

		[HarmonyPostfix]
		public static void Postfix(Terminal __instance, ref Coroutine ___forceScrollbarCoroutine)
		{
			if ((Object)(object)LastNode == (Object)null || LastNode.clearPreviousText)
			{
				ExecuteScrollCoroutine(__instance, ref ___forceScrollbarCoroutine);
			}
			else
			{
				((MonoBehaviour)__instance).StartCoroutine("forceScrollbarDown");
			}
		}

		private static void ExecuteScrollCoroutine(Terminal terminal, ref Coroutine forceScrollbarCoroutine)
		{
			if (forceScrollbarCoroutine != null)
			{
				((MonoBehaviour)terminal).StopCoroutine(forceScrollbarCoroutine);
			}
			forceScrollbarCoroutine = ((MonoBehaviour)terminal).StartCoroutine("forceScrollbarUp");
		}
	}
	[HarmonyPatch(typeof(Terminal), "TextPostProcess")]
	public static class TextPostProcessPatch
	{
		[HarmonyPrefix]
		public static void Prefix(ref string modifiedDisplayText)
		{
			modifiedDisplayText = modifiedDisplayText.TrimStart('\n', ' ');
			if (!modifiedDisplayText.EndsWith('\n'))
			{
				modifiedDisplayText += "\n";
			}
		}
	}
}
namespace LethalAPI.TerminalCommands.Models
{
	public enum AllowedCaller
	{
		None = -1,
		Player,
		Host
	}
	public class ArgumentStream
	{
		public string[] Arguments { get; }

		public int Index { get; set; }

		public bool EndOfStream => Index >= Arguments.Length;

		public ArgumentStream(string[] arguments)
		{
			Arguments = arguments;
		}

		public void Reset()
		{
			Index = 0;
		}

		public bool TryReadNext(Type type, out object value)
		{
			if (EndOfStream)
			{
				value = null;
				return false;
			}
			return StringConverter.TryConvert(Arguments[Index++], type, out value);
		}

		public bool TryReadRemaining(out string result)
		{
			if (EndOfStream)
			{
				result = null;
				return false;
			}
			result = string.Join(" ", Arguments.Skip(Index));
			return true;
		}

		public bool TryReadNext(out string value)
		{
			value = string.Empty;
			if (EndOfStream)
			{
				return false;
			}
			value = Arguments[Index++];
			return true;
		}

		public bool TryReadNext(out sbyte value)
		{
			value = 0;
			if (EndOfStream)
			{
				return false;
			}
			return sbyte.TryParse(Arguments[Index++], out value);
		}

		public bool TryReadNext(out byte value)
		{
			value = 0;
			if (EndOfStream)
			{
				return false;
			}
			return byte.TryParse(Arguments[Index++], out value);
		}

		public bool TryReadNext(out short value)
		{
			value = 0;
			if (EndOfStream)
			{
				return false;
			}
			return short.TryParse(Arguments[Index++], out value);
		}

		public bool TryReadNext(out ushort value)
		{
			value = 0;
			if (EndOfStream)
			{
				return false;
			}
			return ushort.TryParse(Arguments[Index++], out value);
		}

		public bool TryReadNext(out int value)
		{
			value = 0;
			if (EndOfStream)
			{
				return false;
			}
			return int.TryParse(Arguments[Index++], out value);
		}

		public bool TryReadNext(out uint value)
		{
			value = 0u;
			if (EndOfStream)
			{
				return false;
			}
			return uint.TryParse(Arguments[Index++], out value);
		}

		public bool TryReadNext(out long value)
		{
			value = 0L;
			if (EndOfStream)
			{
				return false;
			}
			return long.TryParse(Arguments[Index++], out value);
		}

		public bool TryReadNext(out ulong value)
		{
			value = 0uL;
			if (EndOfStream)
			{
				return false;
			}
			return ulong.TryParse(Arguments[Index++], out value);
		}

		public bool TryReadNext(out float value)
		{
			value = 0f;
			if (EndOfStream)
			{
				return false;
			}
			return float.TryParse(Arguments[Index++], out value);
		}

		public bool TryReadNext(out double value)
		{
			value = 0.0;
			if (EndOfStream)
			{
				return false;
			}
			return double.TryParse(Arguments[Index++], out value);
		}
	}
	public class CommandComparer : IComparer<TerminalCommand>
	{
		public int Compare(TerminalCommand x, TerminalCommand y)
		{
			if (x.Priority > y.Priority)
			{
				return 1;
			}
			if (x.Priority < y.Priority)
			{
				return -1;
			}
			return x.ArgumentCount.CompareTo(y.ArgumentCount);
		}
	}
	public static class CommandHandler
	{
		private static readonly Regex m_SplitRegex = new Regex("[\\\"](.+?)[\\\"]|([^ ]+)", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled);

		private static readonly CommandComparer m_Comparer = new CommandComparer();

		public static TerminalNode TryExecute(string command, Terminal terminal)
		{
			IEnumerable<string> source = from Match x in m_SplitRegex.Matches(command.Trim())
				select x.Value.Trim('"', ' ');
			string commandName = source.First();
			string[] arguments = source.Skip(1).ToArray();
			List<(TerminalCommand, Func<TerminalNode>)> list = new List<(TerminalCommand, Func<TerminalNode>)>();
			TerminalCommand[] array = TerminalRegistry.GetCommands(commandName).ToArray();
			foreach (TerminalCommand terminalCommand in array)
			{
				if (terminalCommand.CheckAllowed() && terminalCommand.TryCreateInvoker(arguments, terminal, out var invoker))
				{
					list.Add((terminalCommand, invoker));
				}
			}
			foreach (var item in list.OrderByDescending<(TerminalCommand, Func<TerminalNode>), TerminalCommand>(((TerminalCommand command, Func<TerminalNode> invoker) x) => x.command, m_Comparer))
			{
				TerminalNode val = item.Item2();
				if ((Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			return null;
		}
	}
	public static class DefaultStringConverters
	{
		[StringConverter]
		public static string ParseString(string input)
		{
			return input;
		}

		[StringConverter]
		public static sbyte ParseSByte(string input)
		{
			if (sbyte.TryParse(input, out var result))
			{
				return result;
			}
			throw new ArgumentException();
		}

		[StringConverter]
		public static byte ParseByte(string input)
		{
			if (byte.TryParse(input, out var result))
			{
				return result;
			}
			throw new ArgumentException();
		}

		[StringConverter]
		public static short ParseShort(string input)
		{
			if (short.TryParse(input, out var result))
			{
				return result;
			}
			throw new ArgumentException();
		}

		[StringConverter]
		public static ushort ParseUShort(string input)
		{
			if (ushort.TryParse(input, out var result))
			{
				return result;
			}
			throw new ArgumentException();
		}

		[StringConverter]
		public static int ParseInt(string input)
		{
			if (int.TryParse(input, out var result))
			{
				return result;
			}
			throw new ArgumentException();
		}

		[StringConverter]
		public static uint ParseUInt(string input)
		{
			if (uint.TryParse(input, out var result))
			{
				return result;
			}
			throw new ArgumentException();
		}

		[StringConverter]
		public static long ParseLong(string input)
		{
			if (long.TryParse(input, out var result))
			{
				return result;
			}
			throw new ArgumentException();
		}

		[StringConverter]
		public static ulong ParseULong(string input)
		{
			if (ulong.TryParse(input, out var result))
			{
				return result;
			}
			throw new ArgumentException();
		}

		[StringConverter]
		public static float ParseFloat(string input)
		{
			if (float.TryParse(input, out var result))
			{
				return result;
			}
			throw new ArgumentException();
		}

		[StringConverter]
		public static double ParseDouble(string input)
		{
			if (double.TryParse(input, out var result))
			{
				return result;
			}
			throw new ArgumentException();
		}

		[StringConverter]
		public static decimal ParseDecimal(string input)
		{
			if (decimal.TryParse(input, out var result))
			{
				return result;
			}
			throw new ArgumentException();
		}

		public static PlayerControllerB ParsePlayerControllerB(string value)
		{
			if ((Object)(object)StartOfRound.Instance == (Object)null)
			{
				throw new ArgumentException("Game has not started");
			}
			PlayerControllerB val = null;
			if (ulong.TryParse(value, out var steamID))
			{
				val = ((IEnumerable<PlayerControllerB>)StartOfRound.Instance.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB x) => x.playerSteamId == steamID));
			}
			if ((Object)(object)val == (Object)null)
			{
				val = ((IEnumerable<PlayerControllerB>)StartOfRound.Instance.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB x) => x.playerUsername.IndexOf(value, StringComparison.InvariantCultureIgnoreCase) != -1));
			}
			if ((Object)(object)val == (Object)null)
			{
				throw new ArgumentException("Failed to find player");
			}
			return val;
		}
	}
	public enum PersistType
	{
		LocalPlayer,
		Host,
		Save
	}
	public delegate object StringConversionHandler(string value);
	public static class StringConverter
	{
		private static bool m_Initialized = false;

		public static ConcurrentDictionary<Type, StringConversionHandler> StringConverters { get; } = new ConcurrentDictionary<Type, StringConversionHandler>();


		public static bool TryConvert(string value, Type type, out object result)
		{
			if (!m_Initialized)
			{
				m_Initialized = true;
				RegisterFromType(typeof(DefaultStringConverters), null, replaceExisting: false);
			}
			if (!StringConverters.TryGetValue(type, out var value2))
			{
				result = null;
				return false;
			}
			try
			{
				result = value2(value);
				return true;
			}
			catch (ArgumentException)
			{
			}
			result = null;
			return false;
		}

		public static void RegisterFrom<T>(T instance, bool replaceExisting = true) where T : class
		{
			RegisterFromType(typeof(T), instance, replaceExisting);
		}

		public static void RegisterFromType(Type type, object instance = null, bool replaceExisting = true)
		{
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo method in methods)
			{
				if (method.GetCustomAttribute<StringConverterAttribute>() == null)
				{
					continue;
				}
				ParameterInfo[] parameters = method.GetParameters();
				if (parameters.Length == 1 && !(parameters[0].ParameterType != typeof(string)))
				{
					Type returnType = method.ReturnType;
					StringConversionHandler value2 = (string value) => method.Invoke(instance, new object[1] { value });
					if (replaceExisting || !StringConverters.ContainsKey(returnType))
					{
						StringConverters[returnType] = value2;
					}
				}
			}
		}
	}
	public class TerminalCommand
	{
		private ManualLogSource m_LogSource = new ManualLogSource("LethalAPI.TerminalCommands");

		public string Name { get; }

		public MethodInfo Method { get; }

		public object Instance { get; }

		public bool ClearConsole { get; }

		public int ArgumentCount { get; }

		public string Syntax { get; }

		public string Description { get; }

		public int Priority { get; }

		public TerminalCommand(string name, MethodInfo method, object instance, bool clearConsole, string syntax = null, string description = null, int priority = 0)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			Name = name;
			Method = method;
			Instance = instance;
			ClearConsole = clearConsole;
			ArgumentCount = method.GetParameters().Length;
			Syntax = syntax;
			Description = description;
			Priority = priority;
		}

		public bool CheckAllowed()
		{
			foreach (AccessControlAttribute customAttribute in Method.GetCustomAttributes<AccessControlAttribute>())
			{
				if (!customAttribute.CheckAllowed())
				{
					return false;
				}
			}
			return true;
		}

		public static TerminalCommand FromMethod(MethodInfo info, object instance, string overrideName = null)
		{
			bool clearConsole = false;
			string syntax = null;
			string description = null;
			string text = overrideName;
			int priority = 0;
			TerminalCommandAttribute customAttribute = info.GetCustomAttribute<TerminalCommandAttribute>();
			if (customAttribute != null)
			{
				text = text ?? customAttribute.CommandName;
				clearConsole = customAttribute.ClearText;
			}
			CommandInfoAttribute customAttribute2 = info.GetCustomAttribute<CommandInfoAttribute>();
			if (customAttribute2 != null)
			{
				syntax = customAttribute2.Syntax;
				description = customAttribute2.Description;
			}
			CommandPriority customAttribute3 = info.GetCustomAttribute<CommandPriority>();
			if (customAttribute3 != null)
			{
				priority = customAttribute3.Priority;
			}
			return new TerminalCommand(text, info, instance, clearConsole, syntax, description, priority);
		}

		public bool TryCreateInvoker(string[] arguments, Terminal terminal, out Func<TerminalNode> invoker)
		{
			ParameterInfo[] parameters = Method.GetParameters();
			object[] values = new object[parameters.Length];
			ArgumentStream argumentStream = new ArgumentStream(arguments);
			invoker = null;
			for (int i = 0; i < parameters.Length; i++)
			{
				ParameterInfo parameterInfo = parameters[i];
				Type parameterType = parameterInfo.ParameterType;
				if (parameterType == typeof(Terminal))
				{
					values[i] = terminal;
				}
				else if (parameterType == typeof(ArgumentStream))
				{
					values[i] = argumentStream;
				}
				else if (parameterType == typeof(string[]))
				{
					values[i] = arguments;
				}
				else if (parameterType == typeof(string) && parameterInfo.GetCustomAttribute<RemainingTextAttribute>() != null)
				{
					if (!argumentStream.TryReadRemaining(out var result))
					{
						return false;
					}
					values[i] = result;
				}
				else
				{
					if (!argumentStream.TryReadNext(parameterType, out var value))
					{
						return false;
					}
					values[i] = value;
				}
			}
			argumentStream.Reset();
			invoker = () => ExecuteCommand(values);
			return true;
		}

		private TerminalNode ExecuteCommand(object[] arguments)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			object obj;
			try
			{
				obj = Method.Invoke(Instance, arguments);
			}
			catch (Exception ex)
			{
				m_LogSource.LogError((object)("Error caught while invoking command hander: " + ex.Message));
				m_LogSource.LogError((object)ex.StackTrace);
				return null;
			}
			if (obj == null)
			{
				return null;
			}
			Type type = obj.GetType();
			if (!typeof(TerminalNode).IsAssignableFrom(type))
			{
				TerminalNode obj2 = ScriptableObject.CreateInstance<TerminalNode>();
				obj2.displayText = obj.ToString() + "\n";
				obj2.clearPreviousText = ClearConsole;
				return obj2;
			}
			return (TerminalNode)obj;
		}
	}
	public class TerminalModRegistry
	{
		public List<TerminalCommand> Commands { get; } = new List<TerminalCommand>();


		public T RegisterFrom<T>() where T : class, new()
		{
			return RegisterFrom(new T());
		}

		public T RegisterFrom<T>(T instance) where T : class
		{
			foreach (MethodInfo commandMethod in TerminalRegistry.GetCommandMethods<T>())
			{
				TerminalCommand terminalCommand = TerminalCommand.FromMethod(commandMethod, instance);
				TerminalRegistry.RegisterCommand(terminalCommand);
				lock (Commands)
				{
					Commands.Add(terminalCommand);
				}
			}
			StringConverter.RegisterFrom(instance);
			return instance;
		}

		public void Deregister()
		{
			if (Commands != null)
			{
				for (int i = 0; i < Commands.Count; i++)
				{
					TerminalRegistry.Deregister(Commands[i]);
				}
			}
		}
	}
	public class TerminalRegistry
	{
		private static readonly ConcurrentDictionary<string, List<TerminalCommand>> m_RegisteredCommands = new ConcurrentDictionary<string, List<TerminalCommand>>(StringComparer.InvariantCultureIgnoreCase);

		public static TerminalModRegistry RegisterFrom<T>(T instance) where T : class
		{
			TerminalModRegistry terminalModRegistry = new TerminalModRegistry();
			foreach (MethodInfo commandMethod in GetCommandMethods<T>())
			{
				TerminalCommand terminalCommand = TerminalCommand.FromMethod(commandMethod, instance);
				RegisterCommand(terminalCommand);
				terminalModRegistry.Commands.Add(terminalCommand);
			}
			StringConverter.RegisterFrom(instance);
			return terminalModRegistry;
		}

		public static TerminalModRegistry CreateTerminalRegistry()
		{
			return new TerminalModRegistry();
		}

		public static void RegisterCommand(TerminalCommand command)
		{
			if (!m_RegisteredCommands.TryGetValue(command.Name, out var value))
			{
				value = new List<TerminalCommand>();
				m_RegisteredCommands[command.Name] = value;
			}
			lock (value)
			{
				value.Add(command);
			}
		}

		public static void Deregister(TerminalCommand command)
		{
			if (!m_RegisteredCommands.TryGetValue(command.Name, out var value))
			{
				return;
			}
			lock (value)
			{
				value.Remove(command);
			}
		}

		public static IReadOnlyList<TerminalCommand> GetCommands(string commandName)
		{
			if (m_RegisteredCommands.TryGetValue(commandName, out var value))
			{
				return value;
			}
			return new List<TerminalCommand>();
		}

		public static IEnumerable<TerminalCommand> EnumerateCommands(string name)
		{
			if (!m_RegisteredCommands.TryGetValue(name, out var value))
			{
				return Enumerable.Empty<TerminalCommand>();
			}
			return value;
		}

		public static IEnumerable<TerminalCommand> EnumerateCommands()
		{
			string[] keys = m_RegisteredCommands.Keys.ToArray();
			for (int i = 0; i < keys.Length; i++)
			{
				List<TerminalCommand> overloads = m_RegisteredCommands[keys[i]];
				for (int c = 0; c < overloads.Count; c++)
				{
					yield return overloads[c];
				}
			}
		}

		public static IEnumerable<MethodInfo> GetCommandMethods<T>()
		{
			MethodInfo[] methods = typeof(T).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				if (methodInfo.GetCustomAttribute<TerminalCommandAttribute>() != null)
				{
					yield return methodInfo;
				}
			}
		}
	}
}
namespace LethalAPI.TerminalCommands.Configs
{
	[ConfigGroup("Terminal", "Configure the behavior of the terminal")]
	public class TerminalConfig
	{
		[TerminalConfig("Enables/Disables terminal verb commands", null)]
		[ConfigPersist(PersistType.LocalPlayer, null)]
		public bool VerbsEnabled { get; set; }

		[TerminalConfig("Specifies if the Confirm/Deny pop-up should be shown", null)]
		[ConfigPersist(PersistType.LocalPlayer, null)]
		public bool AutoConfirm { get; set; }
	}
}
namespace LethalAPI.TerminalCommands.Commands
{
	public class CommandInfoCommands
	{
		[TerminalCommand("Other", true)]
		public string CommandList()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("Other commands:");
			stringBuilder.AppendLine();
			stringBuilder.AppendLine(">VIEW MONITOR");
			stringBuilder.AppendLine("To toggle on/off the main monitor's map cam");
			stringBuilder.AppendLine();
			stringBuilder.AppendLine(">SWITCH {RADAR}");
			stringBuilder.AppendLine("To switch the player view on the main monitor");
			stringBuilder.AppendLine();
			stringBuilder.AppendLine(">PING [Radar booster name]");
			stringBuilder.AppendLine("To switch the player view on the main monitor");
			stringBuilder.AppendLine();
			stringBuilder.AppendLine(">SCAN");
			stringBuilder.AppendLine("To scan for the number of items left on the current planet");
			stringBuilder.AppendLine();
			foreach (TerminalCommand item in TerminalRegistry.EnumerateCommands())
			{
				if (item.Description != null && item.CheckAllowed())
				{
					stringBuilder.AppendLine(">" + item.Name.ToUpper() + " " + item.Syntax?.ToUpper());
					stringBuilder.AppendLine(item.Description);
					stringBuilder.AppendLine();
				}
			}
			return stringBuilder.ToString();
		}

		[TerminalCommand("Help", false)]
		[CommandInfo("Shows further information about a command", "[Command]")]
		public string HelpCommand(string name)
		{
			StringBuilder stringBuilder = new StringBuilder();
			TerminalCommand[] array = TerminalRegistry.EnumerateCommands(name).ToArray();
			if (array.Length == 0)
			{
				return "Unknown command: '" + name + "'";
			}
			TerminalCommand[] array2 = array;
			foreach (TerminalCommand terminalCommand in array2)
			{
				stringBuilder.AppendLine(">" + terminalCommand.Name.ToUpper() + " " + terminalCommand.Syntax?.ToUpper());
				stringBuilder.AppendLine(terminalCommand.Description);
				if (!terminalCommand.CheckAllowed())
				{
					stringBuilder.AppendLine("[Host Only]");
				}
				stringBuilder.AppendLine();
			}
			return stringBuilder.ToString();
		}
	}
}
namespace LethalAPI.TerminalCommands.Attributes
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
	public abstract class AccessControlAttribute : Attribute
	{
		public abstract bool CheckAllowed();
	}
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
	public class AllowedCallerAttribute : AccessControlAttribute
	{
		public AllowedCaller Caller { get; }

		public AllowedCallerAttribute(AllowedCaller caller)
		{
			Caller = caller;
		}

		public override bool CheckAllowed()
		{
			switch (Caller)
			{
			case AllowedCaller.None:
				return false;
			case AllowedCaller.Player:
				return true;
			case AllowedCaller.Host:
				if ((Object)(object)StartOfRound.Instance == (Object)null)
				{
					return false;
				}
				return ((NetworkBehaviour)StartOfRound.Instance).IsHost;
			default:
				return true;
			}
		}
	}
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
	public class CommandInfoAttribute : Attribute
	{
		public string Syntax { get; }

		public string Description { get; }

		public CommandInfoAttribute(string description, string syntax = "")
		{
			Syntax = syntax;
			Description = description;
		}
	}
	public sealed class CommandPriority : Attribute
	{
		public int Priority { get; }

		public CommandPriority(int priority)
		{
			Priority = priority;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class ConfigGroupAttribute : Attribute
	{
		public string Name { get; }

		public string Description { get; }

		public ConfigGroupAttribute(string name, string description)
		{
			Name = name;
			Description = description;
		}
	}
	public class ConfigPersistAttribute : Attribute
	{
		public PersistType PersistType { get; }

		public string ConfigPath { get; }

		public ConfigPersistAttribute(PersistType persistType, string configPath = null)
		{
			PersistType = persistType;
			ConfigPath = configPath;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter)]
	public sealed class RemainingTextAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public sealed class StringConverterAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
	public class TerminalCommandAttribute : Attribute
	{
		public string CommandName { get; }

		public bool ClearText { get; }

		public TerminalCommandAttribute(string name, bool clearText = false)
		{
			CommandName = name;
			ClearText = clearText;
		}
	}
	[AttributeUsage(AttributeTargets.Property)]
	public class TerminalConfigAttribute : Attribute
	{
		public string Name { get; }

		public string Description { get; }

		public TerminalConfigAttribute(string description, string name = null)
		{
			Name = name;
			Description = description;
		}
	}
}

BooBoo Building/BepInEx/plugins/anormaltwig-TerminalExtras/TerminalExtras.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using GameNetcodeStuff;
using LethalAPI.TerminalCommands.Attributes;
using LethalAPI.TerminalCommands.Models;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Events;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("TerminalExtras")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+32be330519c446b28ad5234b103989d788463a62")]
[assembly: AssemblyProduct("TerminalExtras")]
[assembly: AssemblyTitle("TerminalExtras")]
[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 TerminalExtras
{
	public static class PluginInfo
	{
		public const string GUID = "twig.terminalextras";

		public const string Name = "Terminal Extras";

		public const string Version = "1.0.1";
	}
	[BepInPlugin("twig.terminalextras", "Terminal Extras", "1.0.1")]
	internal class Plugin : BaseUnityPlugin
	{
		private TerminalModRegistry commands;

		public void Awake()
		{
			commands = TerminalRegistry.RegisterFrom<ExtraCommands>(new ExtraCommands());
		}
	}
	public class ExtraCommands
	{
		[TerminalCommand("Door", false)]
		[CommandInfo("Toggles the door.", "")]
		public string DoorCommand()
		{
			InteractTrigger componentInChildren = GameObject.Find(StartOfRound.Instance.hangarDoorsClosed ? "StartButton" : "StopButton").GetComponentInChildren<InteractTrigger>();
			((UnityEvent<PlayerControllerB>)(object)componentInChildren.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
			return "Toggled door.";
		}

		[TerminalCommand("Doors", false)]
		[CommandInfo("Toggles the door.", "")]
		public string DoorsCommand()
		{
			return DoorCommand();
		}

		[TerminalCommand("Teleport", false)]
		[CommandInfo("Activate the teleporter.", "")]
		public string TeleportCommand()
		{
			GameObject val = GameObject.Find("Teleporter(Clone)");
			if (val == null)
			{
				return "You don't have a teleporter!";
			}
			ShipTeleporter component = val.GetComponent<ShipTeleporter>();
			if (component == null)
			{
				return "!! Can't find ShipTeleporter component !!";
			}
			if (!component.buttonTrigger.interactable)
			{
				return "Teleporter is on cooldown!";
			}
			((UnityEvent<PlayerControllerB>)(object)component.buttonTrigger.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
			return "Teleporting player";
		}

		[TerminalCommand("Lights", false)]
		[CommandInfo("Toggle the lights.", "")]
		public string LightsCommand()
		{
			InteractTrigger component = GameObject.Find("LightSwitch").GetComponent<InteractTrigger>();
			((UnityEvent<PlayerControllerB>)(object)component.onInteract).Invoke(GameNetworkManager.Instance.localPlayerController);
			return "Toggled lights";
		}

		[TerminalCommand("Light", false)]
		[CommandInfo("Toggle the lights.", "")]
		public string LightCommand()
		{
			return LightsCommand();
		}

		[TerminalCommand("Tp", false)]
		[CommandInfo("Activate the teleporter.", "")]
		public string TeleportCommandShort()
		{
			return TeleportCommand();
		}

		[TerminalCommand("Launch", false)]
		[CommandInfo("Pull the lever, Kronk!", "")]
		public string LaunchCommand()
		{
			GameObject val = GameObject.Find("StartGameLever");
			if (val == null)
			{
				return "!! Can't find StartGameLever !!";
			}
			StartMatchLever component = val.GetComponent<StartMatchLever>();
			if (component == null)
			{
				return "!! Can't find StartMatchLever componen !!";
			}
			if (StartOfRound.Instance.shipDoorsEnabled && !StartOfRound.Instance.shipHasLanded && !StartOfRound.Instance.shipIsLeaving)
			{
				return "Unable to comply. The ship is already in transit.";
			}
			if (!StartOfRound.Instance.shipDoorsEnabled && StartOfRound.Instance.travellingToNewLevel)
			{
				return "Unable to comply. The ship is already in transit.";
			}
			bool flag = !component.leverHasBeenPulled;
			component.PullLever();
			component.LeverAnimation();
			if (flag)
			{
				component.StartGame();
			}
			else
			{
				component.EndGame();
			}
			return "Initiating " + (component.leverHasBeenPulled ? "landing" : "launch") + " sequence.";
		}

		[TerminalCommand("Go", false)]
		[CommandInfo("Pull the lever, Kronk!", "")]
		public string GoCommand()
		{
			return LaunchCommand();
		}
	}
}

BooBoo Building/BepInEx/plugins/ATK-ShipClock/ShipClock.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

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

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace ShipClock
{
	[BepInPlugin("atk.lethalcompany.shipclock", "Ship Clock", "0.9.0")]
	public class Main : BaseUnityPlugin
	{
		private const string PluginGuid = "atk.lethalcompany.shipclock";

		private const string PluginName = "Ship Clock";

		private const string PluginVersion = "0.9.0";

		public void Awake()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			Harmony val = new Harmony("atk.lethalcompany.shipclock");
			val.PatchAll(typeof(Patches));
		}
	}
	[HarmonyPatch]
	internal class Patches
	{
		[HarmonyPatch(typeof(TimeOfDay), "SetInsideLightingDimness")]
		[HarmonyPostfix]
		public static void SetInsideLightingDimness()
		{
			if ((Object)(object)GameNetworkManager.Instance != (Object)null && !GameNetworkManager.Instance.localPlayerController.isPlayerDead)
			{
				HUDManager.Instance.SetClockVisible(!GameNetworkManager.Instance.localPlayerController.isInsideFactory);
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/BatTeam-LethalFashion/LethalFashion.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using 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("LethalFashion")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Adding immediate outfits for the crew")]
[assembly: AssemblyFileVersion("1.0.4.0")]
[assembly: AssemblyInformationalVersion("1.0.4")]
[assembly: AssemblyProduct("LethalFashion")]
[assembly: AssemblyTitle("LethalFashion")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.4.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalFashion
{
	[BepInPlugin("LethalFashion", "LethalFashion", "1.0.4")]
	public class Plugin : BaseUnityPlugin
	{
		public static ManualLogSource Log;

		private static Harmony harmonyInstance;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LethalFashion is loaded!");
			InitializeHarmony();
		}

		private void InitializeHarmony()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			if (harmonyInstance == null)
			{
				harmonyInstance = new Harmony("LethalFashion");
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Harmony instance created");
				try
				{
					harmonyInstance.PatchAll(typeof(SuitFashion));
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Patch applied successfully. You are now FASHIONABLE.");
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Error applying patch: " + ex.Message));
				}
			}
		}
	}
	public class SuitFashion
	{
		private static readonly MethodInfo unlockItem;

		private static bool isHost;

		static SuitFashion()
		{
			unlockItem = typeof(StartOfRound).GetMethod("SpawnUnlockable", BindingFlags.Instance | BindingFlags.NonPublic);
			if (unlockItem == null)
			{
				Plugin.Log.LogError((object)"SpawnUnlockable method not found in StartOfRound. Please check game/plugin version.");
			}
		}

		public static void SpawnUnlockableDelegate(StartOfRound instance, int ID)
		{
			if (unlockItem == null)
			{
				Plugin.Log.LogError((object)"Cannot invoke SpawnUnlockable - method reference is null. Please check game/plugin version.");
			}
			else if (!instance.SpawnedShipUnlockables.ContainsKey(ID))
			{
				try
				{
					unlockItem.Invoke(instance, new object[1] { ID });
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)("Error invoking SpawnUnlockable: " + ex.Message));
				}
			}
		}

		public static void PositionSuitsOnRack(StartOfRound startOfRoundInstance)
		{
			//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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: 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)
			UnlockableSuit[] array = Object.FindObjectsOfType<UnlockableSuit>();
			for (int i = 0; i < array.Length; i++)
			{
				UnlockableSuit val = array[i];
				AutoParentToShip component = ((Component)val).gameObject.GetComponent<AutoParentToShip>();
				if ((Object)(object)component != (Object)null)
				{
					component.overrideOffset = true;
					component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + startOfRoundInstance.rightmostSuitPosition.forward * 0.18f * (float)i;
					component.rotationOffset = new Vector3(0f, 90f, 0f);
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "Start")]
		[HarmonyPostfix]
		public static void StartOfRoundSuitPatch(StartOfRound __instance)
		{
			if (!isHost)
			{
				return;
			}
			int[] array = new int[3] { 1, 2, 3 };
			int[] array2 = array;
			foreach (int num in array2)
			{
				if (num >= 0 && num < __instance.unlockablesList.unlockables.Count)
				{
					UnlockableItem val = __instance.unlockablesList.unlockables[num];
					if (val != null)
					{
						val.alreadyUnlocked = true;
						val.hasBeenUnlockedByPlayer = true;
						val.inStorage = false;
						SpawnUnlockableDelegate(__instance, num);
					}
				}
			}
			PositionSuitsOnRack(__instance);
		}

		[HarmonyPatch(typeof(StartOfRound), "ResetShip")]
		[HarmonyPostfix]
		public static void ResetShipSuitPatch(StartOfRound __instance)
		{
			if (isHost)
			{
				StartOfRoundSuitPatch(__instance);
			}
		}

		[HarmonyPatch(typeof(RoundManager), "Start")]
		[HarmonyPrefix]
		private static void SetIsHost()
		{
			isHost = ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LethalFashion";

		public const string PLUGIN_NAME = "LethalFashion";

		public const string PLUGIN_VERSION = "1.0.4";
	}
}

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/BepInEx.MelonLoader.Loader/AssetRipper.VersionUtilities.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using AssetRipper.VersionUtilities.Extensions;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("VersionUtilities.Tests")]
[assembly: AssemblyCompany("AssetRipper")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2022 ds5678")]
[assembly: AssemblyDescription("Managed library for handling Unity versions")]
[assembly: AssemblyFileVersion("1.2.1.0")]
[assembly: AssemblyInformationalVersion("1.2.1.0")]
[assembly: AssemblyProduct("AssetRipper.VersionUtilities")]
[assembly: AssemblyTitle("AssetRipper.VersionUtilities")]
[assembly: AssemblyVersion("1.2.1.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace AssetRipper.VersionUtilities
{
	public struct CompactUnityVersion24 : IEquatable<CompactUnityVersion24>, IComparable, IComparable<CompactUnityVersion24>
	{
		private const int majorOffset = 3;

		private const int buildOffset = 9;

		private const int typeOffset = 6;

		private const uint bitMask3 = 7u;

		private const uint bitMask5 = 31u;

		private const uint bitMask6 = 63u;

		private const uint bitMask7 = 127u;

		private readonly byte m_MajorMinorByte;

		private readonly ushort m_BuildTypeShort;

		public const ushort MajorMaxValue = 2042;

		private byte MajorRaw => (byte)((ulong)(m_MajorMinorByte >> 3) & 0x1FuL);

		public ushort Major => ConvertMajorRawToNormal(MajorRaw);

		public byte Minor => (byte)(m_MajorMinorByte & 7u);

		public byte Build => (byte)((ulong)(m_BuildTypeShort >> 9) & 0x7FuL);

		public UnityVersionType Type => (UnityVersionType)((ulong)(m_BuildTypeShort >> 6) & 7uL);

		public byte TypeNumber => (byte)(m_BuildTypeShort & 0x3Fu);

		public static CompactUnityVersion24 MinVersion { get; } = new CompactUnityVersion24((byte)0, (ushort)0);


		public static CompactUnityVersion24 MaxVersion { get; } = new CompactUnityVersion24(byte.MaxValue, ushort.MaxValue);


		public CompactUnityVersion24(ushort major)
		{
			m_MajorMinorByte = (byte)(ConvertMajorRawToNormal(major) << 3);
			m_BuildTypeShort = 0;
		}

		public CompactUnityVersion24(ushort major, byte minor)
		{
			m_MajorMinorByte = (byte)((ConvertMajorRawToNormal(major) << 3) | CastToThreeBits(minor));
			m_BuildTypeShort = 0;
		}

		public CompactUnityVersion24(ushort major, byte minor, byte build)
		{
			m_MajorMinorByte = (byte)((ConvertMajorRawToNormal(major) << 3) | CastToThreeBits(minor));
			m_BuildTypeShort = (ushort)(CastToSevenBits(build) << 9);
		}

		public CompactUnityVersion24(ushort major, byte minor, byte build, UnityVersionType type)
		{
			m_MajorMinorByte = (byte)((ConvertMajorRawToNormal(major) << 3) | CastToThreeBits(minor));
			m_BuildTypeShort = (ushort)((CastToSevenBits(build) << 9) | (CastToThreeBits((byte)type) << 6));
		}

		public CompactUnityVersion24(ushort major, byte minor, byte build, UnityVersionType type, byte typeNumber)
		{
			m_MajorMinorByte = (byte)((ConvertMajorRawToNormal(major) << 3) | CastToThreeBits(minor));
			m_BuildTypeShort = (ushort)((CastToSevenBits(build) << 9) | (CastToThreeBits((byte)type) << 6) | CastToSixBits(typeNumber));
		}

		private CompactUnityVersion24(byte majorMinorByte, ushort buildTypeShort)
		{
			m_MajorMinorByte = majorMinorByte;
			m_BuildTypeShort = buildTypeShort;
		}

		public void GetBits(out byte majorMinorByte, out ushort buildTypeShort)
		{
			majorMinorByte = m_MajorMinorByte;
			buildTypeShort = m_BuildTypeShort;
		}

		public static CompactUnityVersion24 FromBits(byte majorMinorByte, ushort buildTypeShort)
		{
			return new CompactUnityVersion24(majorMinorByte, buildTypeShort);
		}

		private static ushort ConvertMajorRawToNormal(byte raw)
		{
			if (raw >= 6)
			{
				return (ushort)(raw + 2011);
			}
			return raw;
		}

		private static byte ConvertMajorRawToNormal(ushort major)
		{
			if (major < 6)
			{
				return (byte)major;
			}
			if (major >= 2017 && major <= 2042)
			{
				return (byte)(major - 2011);
			}
			throw new ArgumentOutOfRangeException("major");
		}

		private static byte CastToThreeBits(byte b)
		{
			if ((uint)b > 7u)
			{
				throw new ArgumentOutOfRangeException("b");
			}
			return b;
		}

		private static byte CastToSixBits(byte b)
		{
			if ((uint)b > 63u)
			{
				throw new ArgumentOutOfRangeException("b");
			}
			return b;
		}

		private static byte CastToSevenBits(byte b)
		{
			if ((uint)b > 127u)
			{
				throw new ArgumentOutOfRangeException("b");
			}
			return b;
		}

		public override string ToString()
		{
			return $"{Major}.{Minor}.{Build}{Type.ToCharacter()}{TypeNumber}";
		}

		public int CompareTo(object? obj)
		{
			if (!(obj is CompactUnityVersion24 other))
			{
				return 1;
			}
			return CompareTo(other);
		}

		public int CompareTo(CompactUnityVersion24 other)
		{
			if (this > other)
			{
				return 1;
			}
			if (this < other)
			{
				return -1;
			}
			return 0;
		}

		public override bool Equals(object? obj)
		{
			if (obj is CompactUnityVersion24 compactUnityVersion)
			{
				return this == compactUnityVersion;
			}
			return false;
		}

		public bool Equals(CompactUnityVersion24 other)
		{
			return this == other;
		}

		public override int GetHashCode()
		{
			return (m_MajorMinorByte << 16) | m_BuildTypeShort;
		}

		public static implicit operator UnityVersion(CompactUnityVersion24 version)
		{
			return new UnityVersion(version.Major, version.Minor, version.Build, version.Type, version.TypeNumber);
		}

		public static implicit operator CompactUnityVersion32(CompactUnityVersion24 version)
		{
			return new CompactUnityVersion32(version.Major, version.Minor, version.Build, version.Type, version.TypeNumber);
		}

		public static explicit operator CompactUnityVersion24(UnityVersion version)
		{
			return new CompactUnityVersion24(version.Major, (byte)version.Minor, (byte)version.Build, version.Type, version.TypeNumber);
		}

		public static explicit operator CompactUnityVersion24(CompactUnityVersion32 version)
		{
			return new CompactUnityVersion24(version.Major, version.Minor, version.Build, version.Type, version.TypeNumber);
		}

		public static bool operator ==(CompactUnityVersion24 left, CompactUnityVersion24 right)
		{
			if (left.m_MajorMinorByte == right.m_MajorMinorByte)
			{
				return left.m_BuildTypeShort == right.m_BuildTypeShort;
			}
			return false;
		}

		public static bool operator !=(CompactUnityVersion24 left, CompactUnityVersion24 right)
		{
			if (left.m_MajorMinorByte == right.m_MajorMinorByte)
			{
				return left.m_BuildTypeShort != right.m_BuildTypeShort;
			}
			return true;
		}

		public static bool operator >(CompactUnityVersion24 left, CompactUnityVersion24 right)
		{
			if (left.m_MajorMinorByte <= right.m_MajorMinorByte)
			{
				if (left.m_MajorMinorByte == right.m_MajorMinorByte)
				{
					return left.m_BuildTypeShort > right.m_BuildTypeShort;
				}
				return false;
			}
			return true;
		}

		public static bool operator >=(CompactUnityVersion24 left, CompactUnityVersion24 right)
		{
			if (left.m_MajorMinorByte <= right.m_MajorMinorByte)
			{
				if (left.m_MajorMinorByte == right.m_MajorMinorByte)
				{
					return left.m_BuildTypeShort >= right.m_BuildTypeShort;
				}
				return false;
			}
			return true;
		}

		public static bool operator <(CompactUnityVersion24 left, CompactUnityVersion24 right)
		{
			if (left.m_MajorMinorByte >= right.m_MajorMinorByte)
			{
				if (left.m_MajorMinorByte == right.m_MajorMinorByte)
				{
					return left.m_BuildTypeShort < right.m_BuildTypeShort;
				}
				return false;
			}
			return true;
		}

		public static bool operator <=(CompactUnityVersion24 left, CompactUnityVersion24 right)
		{
			if (left.m_MajorMinorByte >= right.m_MajorMinorByte)
			{
				if (left.m_MajorMinorByte == right.m_MajorMinorByte)
				{
					return left.m_BuildTypeShort <= right.m_BuildTypeShort;
				}
				return false;
			}
			return true;
		}
	}
	public struct CompactUnityVersion32 : IEquatable<CompactUnityVersion32>, IComparable, IComparable<CompactUnityVersion32>
	{
		private const int majorOffset = 24;

		private const int minorOffset = 20;

		private const int buildOffset = 12;

		private const int typeOffset = 8;

		private const uint byteMask = 255u;

		private const uint bitMask4 = 15u;

		private readonly uint m_data;

		public const ushort MajorMaxValue = 2266;

		private byte MajorRaw => (byte)((m_data >> 24) & 0xFFu);

		public ushort Major => ConvertMajorRawToNormal(MajorRaw);

		public byte Minor => (byte)((m_data >> 20) & 0xFu);

		public byte Build => (byte)((m_data >> 12) & 0xFFu);

		public UnityVersionType Type => (UnityVersionType)((m_data >> 8) & 0xFu);

		public byte TypeNumber => (byte)(m_data & 0xFFu);

		public static CompactUnityVersion32 MinVersion { get; } = new CompactUnityVersion32(0u);


		public static CompactUnityVersion32 MaxVersion { get; } = new CompactUnityVersion32(uint.MaxValue);


		public CompactUnityVersion32(ushort major)
		{
			m_data = (uint)(ConvertMajorRawToNormal(major) << 24);
		}

		public CompactUnityVersion32(ushort major, byte minor)
		{
			m_data = (uint)((ConvertMajorRawToNormal(major) << 24) | (CastToFourBits(minor) << 20));
		}

		public CompactUnityVersion32(ushort major, byte minor, byte build)
		{
			m_data = (uint)((ConvertMajorRawToNormal(major) << 24) | (CastToFourBits(minor) << 20) | (build << 12));
		}

		public CompactUnityVersion32(ushort major, byte minor, byte build, UnityVersionType type)
		{
			m_data = (uint)((ConvertMajorRawToNormal(major) << 24) | (CastToFourBits(minor) << 20) | (build << 12)) | ((uint)CastToFourBits(type) << 8);
		}

		public CompactUnityVersion32(ushort major, byte minor, byte build, UnityVersionType type, byte typeNumber)
		{
			m_data = (uint)((ConvertMajorRawToNormal(major) << 24) | (CastToFourBits(minor) << 20) | (build << 12)) | ((uint)CastToFourBits(type) << 8) | typeNumber;
		}

		private CompactUnityVersion32(uint data)
		{
			m_data = data;
		}

		public uint GetBits()
		{
			return m_data;
		}

		public static CompactUnityVersion32 FromBits(uint bits)
		{
			return new CompactUnityVersion32(bits);
		}

		private static ushort ConvertMajorRawToNormal(byte raw)
		{
			if (raw >= 6)
			{
				return (ushort)(raw + 2011);
			}
			return raw;
		}

		private static byte ConvertMajorRawToNormal(ushort major)
		{
			if (major < 6)
			{
				return (byte)major;
			}
			if (major >= 2017 && major <= 2266)
			{
				return (byte)(major - 2011);
			}
			throw new ArgumentOutOfRangeException("major");
		}

		private static byte CastToFourBits(byte b)
		{
			if ((uint)b > 15u)
			{
				throw new ArgumentOutOfRangeException("b");
			}
			return b;
		}

		private static UnityVersionType CastToFourBits(UnityVersionType type)
		{
			if (type > (UnityVersionType)15)
			{
				throw new ArgumentOutOfRangeException("type");
			}
			return type;
		}

		public override string ToString()
		{
			return $"{Major}.{Minor}.{Build}{Type.ToCharacter()}{TypeNumber}";
		}

		public int CompareTo(object? obj)
		{
			if (!(obj is CompactUnityVersion32 other))
			{
				return 1;
			}
			return CompareTo(other);
		}

		public int CompareTo(CompactUnityVersion32 other)
		{
			if (this > other)
			{
				return 1;
			}
			if (this < other)
			{
				return -1;
			}
			return 0;
		}

		public override bool Equals(object? obj)
		{
			if (obj is CompactUnityVersion32 compactUnityVersion)
			{
				return this == compactUnityVersion;
			}
			return false;
		}

		public bool Equals(CompactUnityVersion32 other)
		{
			return this == other;
		}

		public override int GetHashCode()
		{
			uint data = m_data;
			return data.GetHashCode();
		}

		public static implicit operator UnityVersion(CompactUnityVersion32 version)
		{
			return new UnityVersion(version.Major, version.Minor, version.Build, version.Type, version.TypeNumber);
		}

		public static explicit operator CompactUnityVersion32(UnityVersion version)
		{
			return new CompactUnityVersion32(version.Major, (byte)version.Minor, (byte)version.Build, version.Type, version.TypeNumber);
		}

		public static bool operator ==(CompactUnityVersion32 left, CompactUnityVersion32 right)
		{
			return left.m_data == right.m_data;
		}

		public static bool operator !=(CompactUnityVersion32 left, CompactUnityVersion32 right)
		{
			return left.m_data != right.m_data;
		}

		public static bool operator >(CompactUnityVersion32 left, CompactUnityVersion32 right)
		{
			return left.m_data > right.m_data;
		}

		public static bool operator >=(CompactUnityVersion32 left, CompactUnityVersion32 right)
		{
			return left.m_data >= right.m_data;
		}

		public static bool operator <(CompactUnityVersion32 left, CompactUnityVersion32 right)
		{
			return left.m_data < right.m_data;
		}

		public static bool operator <=(CompactUnityVersion32 left, CompactUnityVersion32 right)
		{
			return left.m_data <= right.m_data;
		}
	}
	public readonly struct UnityVersion : IEquatable<UnityVersion>, IComparable, IComparable<UnityVersion>
	{
		private const ulong subMajorMask = 281474976710655uL;

		private const ulong subMinorMask = 4294967295uL;

		private const ulong subBuildMask = 65535uL;

		private const ulong subTypeMask = 255uL;

		private const int majorOffset = 48;

		private const int minorOffset = 32;

		private const int buildOffset = 16;

		private const int typeOffset = 8;

		private const ulong byteMask = 255uL;

		private const ulong ushortMask = 65535uL;

		private readonly ulong m_data;

		public ushort Major => (ushort)((m_data >> 48) & 0xFFFF);

		public ushort Minor => (ushort)((m_data >> 32) & 0xFFFF);

		public ushort Build => (ushort)((m_data >> 16) & 0xFFFF);

		public UnityVersionType Type => (UnityVersionType)((m_data >> 8) & 0xFF);

		public byte TypeNumber => (byte)(m_data & 0xFF);

		public static UnityVersion MinVersion { get; } = new UnityVersion(0uL);


		public static UnityVersion MaxVersion { get; } = new UnityVersion(ulong.MaxValue);


		public bool IsEqual(ushort major)
		{
			return this == From(major);
		}

		public bool IsEqual(ushort major, ushort minor)
		{
			return this == From(major, minor);
		}

		public bool IsEqual(ushort major, ushort minor, ushort build)
		{
			return this == From(major, minor, build);
		}

		public bool IsEqual(ushort major, ushort minor, ushort build, UnityVersionType type)
		{
			return this == From(major, minor, build, type);
		}

		public bool IsEqual(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber)
		{
			return this == new UnityVersion(major, minor, build, type, typeNumber);
		}

		public bool IsEqual(string version)
		{
			return this == Parse(version);
		}

		public bool IsLess(ushort major)
		{
			return this < From(major);
		}

		public bool IsLess(ushort major, ushort minor)
		{
			return this < From(major, minor);
		}

		public bool IsLess(ushort major, ushort minor, ushort build)
		{
			return this < From(major, minor, build);
		}

		public bool IsLess(ushort major, ushort minor, ushort build, UnityVersionType type)
		{
			return this < From(major, minor, build, type);
		}

		public bool IsLess(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber)
		{
			return this < new UnityVersion(major, minor, build, type, typeNumber);
		}

		public bool IsLess(string version)
		{
			return this < Parse(version);
		}

		public bool IsLessEqual(ushort major)
		{
			return this <= From(major);
		}

		public bool IsLessEqual(ushort major, ushort minor)
		{
			return this <= From(major, minor);
		}

		public bool IsLessEqual(ushort major, ushort minor, ushort build)
		{
			return this <= From(major, minor, build);
		}

		public bool IsLessEqual(ushort major, ushort minor, ushort build, UnityVersionType type)
		{
			return this <= From(major, minor, build, type);
		}

		public bool IsLessEqual(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber)
		{
			return this <= new UnityVersion(major, minor, build, type, typeNumber);
		}

		public bool IsLessEqual(string version)
		{
			return this <= Parse(version);
		}

		public bool IsGreater(ushort major)
		{
			return this > From(major);
		}

		public bool IsGreater(ushort major, ushort minor)
		{
			return this > From(major, minor);
		}

		public bool IsGreater(ushort major, ushort minor, ushort build)
		{
			return this > From(major, minor, build);
		}

		public bool IsGreater(ushort major, ushort minor, ushort build, UnityVersionType type)
		{
			return this > From(major, minor, build, type);
		}

		public bool IsGreater(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber)
		{
			return this > new UnityVersion(major, minor, build, type, typeNumber);
		}

		public bool IsGreater(string version)
		{
			return this > Parse(version);
		}

		public bool IsGreaterEqual(ushort major)
		{
			return this >= From(major);
		}

		public bool IsGreaterEqual(ushort major, ushort minor)
		{
			return this >= From(major, minor);
		}

		public bool IsGreaterEqual(ushort major, ushort minor, ushort build)
		{
			return this >= From(major, minor, build);
		}

		public bool IsGreaterEqual(ushort major, ushort minor, ushort build, UnityVersionType type)
		{
			return this >= From(major, minor, build, type);
		}

		public bool IsGreaterEqual(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber)
		{
			return this >= new UnityVersion(major, minor, build, type, typeNumber);
		}

		public bool IsGreaterEqual(string version)
		{
			return this >= Parse(version);
		}

		private UnityVersion From(ushort major)
		{
			return new UnityVersion(((ulong)major << 48) | (0xFFFFFFFFFFFFuL & m_data));
		}

		private UnityVersion From(ushort major, ushort minor)
		{
			return new UnityVersion(((ulong)major << 48) | ((ulong)minor << 32) | (0xFFFFFFFFu & m_data));
		}

		private UnityVersion From(ushort major, ushort minor, ushort build)
		{
			return new UnityVersion(((ulong)major << 48) | ((ulong)minor << 32) | ((ulong)build << 16) | (0xFFFF & m_data));
		}

		private UnityVersion From(ushort major, ushort minor, ushort build, UnityVersionType type)
		{
			return new UnityVersion(((ulong)major << 48) | ((ulong)minor << 32) | ((ulong)build << 16) | ((ulong)type << 8) | (0xFF & m_data));
		}

		public UnityVersion(ushort major)
		{
			m_data = (ulong)major << 48;
		}

		public UnityVersion(ushort major, ushort minor)
		{
			m_data = ((ulong)major << 48) | ((ulong)minor << 32);
		}

		public UnityVersion(ushort major, ushort minor, ushort build)
		{
			m_data = ((ulong)major << 48) | ((ulong)minor << 32) | ((ulong)build << 16);
		}

		public UnityVersion(ushort major, ushort minor, ushort build, UnityVersionType type)
		{
			m_data = ((ulong)major << 48) | ((ulong)minor << 32) | ((ulong)build << 16) | ((ulong)type << 8);
		}

		public UnityVersion(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber)
		{
			m_data = ((ulong)major << 48) | ((ulong)minor << 32) | ((ulong)build << 16) | ((ulong)type << 8) | typeNumber;
		}

		private UnityVersion(ulong data)
		{
			m_data = data;
		}

		public ulong GetBits()
		{
			return m_data;
		}

		public static UnityVersion FromBits(ulong bits)
		{
			return new UnityVersion(bits);
		}

		public int CompareTo(object? obj)
		{
			if (!(obj is UnityVersion other))
			{
				return 1;
			}
			return CompareTo(other);
		}

		public int CompareTo(UnityVersion other)
		{
			if (this > other)
			{
				return 1;
			}
			if (this < other)
			{
				return -1;
			}
			return 0;
		}

		public override bool Equals(object? obj)
		{
			if (obj is UnityVersion unityVersion)
			{
				return this == unityVersion;
			}
			return false;
		}

		public bool Equals(UnityVersion other)
		{
			return this == other;
		}

		public override int GetHashCode()
		{
			ulong data = m_data;
			return 827 + 911 * data.GetHashCode();
		}

		public static UnityVersion Max(UnityVersion left, UnityVersion right)
		{
			if (!(left > right))
			{
				return right;
			}
			return left;
		}

		public static UnityVersion Min(UnityVersion left, UnityVersion right)
		{
			if (!(left < right))
			{
				return right;
			}
			return left;
		}

		public static ulong Distance(UnityVersion left, UnityVersion right)
		{
			if (left.m_data >= right.m_data)
			{
				return left.m_data - right.m_data;
			}
			return right.m_data - left.m_data;
		}

		public UnityVersion GetClosestVersion(UnityVersion[] versions)
		{
			if (versions == null)
			{
				throw new ArgumentNullException("versions");
			}
			if (versions.Length == 0)
			{
				throw new ArgumentException("Length cannot be zero", "versions");
			}
			UnityVersion unityVersion = versions[0];
			ulong num = Distance(this, unityVersion);
			for (int i = 1; i < versions.Length; i++)
			{
				ulong num2 = Distance(this, versions[i]);
				if (num2 < num)
				{
					num = num2;
					unityVersion = versions[i];
				}
			}
			return unityVersion;
		}

		public static bool operator ==(UnityVersion left, UnityVersion right)
		{
			return left.m_data == right.m_data;
		}

		public static bool operator !=(UnityVersion left, UnityVersion right)
		{
			return left.m_data != right.m_data;
		}

		public static bool operator >(UnityVersion left, UnityVersion right)
		{
			return left.m_data > right.m_data;
		}

		public static bool operator >=(UnityVersion left, UnityVersion right)
		{
			return left.m_data >= right.m_data;
		}

		public static bool operator <(UnityVersion left, UnityVersion right)
		{
			return left.m_data < right.m_data;
		}

		public static bool operator <=(UnityVersion left, UnityVersion right)
		{
			return left.m_data <= right.m_data;
		}

		public override string ToString()
		{
			return $"{Major}.{Minor}.{Build}{Type.ToCharacter()}{TypeNumber}";
		}

		public string ToString(bool hasUnderscorePrefix, bool useUnderscores, bool hasExtension)
		{
			StringBuilder stringBuilder = new StringBuilder();
			char value = (useUnderscores ? '_' : '.');
			if (hasUnderscorePrefix)
			{
				stringBuilder.Append('_');
			}
			stringBuilder.Append(Major);
			stringBuilder.Append(value);
			stringBuilder.Append(Minor);
			stringBuilder.Append(value);
			stringBuilder.Append(Build);
			stringBuilder.Append(value);
			stringBuilder.Append(Type.ToCharacter());
			stringBuilder.Append(TypeNumber);
			if (hasExtension)
			{
				stringBuilder.Append(".dll");
			}
			return stringBuilder.ToString();
		}

		public string ToStringWithoutType()
		{
			return $"{Major}.{Minor}.{Build}";
		}

		public static UnityVersion ParseFromDllName(string dllName)
		{
			if (string.IsNullOrEmpty(dllName))
			{
				throw new ArgumentNullException("dllName");
			}
			if (dllName[0] == '_')
			{
				dllName = dllName.Substring(1);
			}
			return Parse(dllName.Replace('_', '.').Replace(".dll", ""));
		}

		public static UnityVersion Parse(string version)
		{
			if (string.IsNullOrEmpty(version))
			{
				throw new ArgumentNullException("version");
			}
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			UnityVersionType type = UnityVersionType.Final;
			int num4 = 0;
			using StringReader stringReader = new StringReader(version);
			while (true)
			{
				int num5 = stringReader.Read();
				if (num5 == -1)
				{
					throw new ArgumentException("Invalid version formatting: " + version, "version");
				}
				char c = (char)num5;
				if (c == '.')
				{
					break;
				}
				num = num * 10 + c.ParseDigit();
			}
			while (true)
			{
				int num6 = stringReader.Read();
				if (num6 == -1)
				{
					break;
				}
				char c2 = (char)num6;
				if (c2 == '.')
				{
					break;
				}
				num2 = num2 * 10 + c2.ParseDigit();
			}
			while (true)
			{
				int num7 = stringReader.Read();
				if (num7 == -1)
				{
					break;
				}
				char c3 = (char)num7;
				if (char.IsDigit(c3))
				{
					num3 = num3 * 10 + c3.ParseDigit();
					continue;
				}
				type = c3.ToUnityVersionType();
				break;
			}
			while (true)
			{
				int num8 = stringReader.Read();
				if (num8 == -1)
				{
					break;
				}
				char @this = (char)num8;
				num4 = num4 * 10 + @this.ParseDigit();
			}
			return new UnityVersion((ushort)num, (ushort)num2, (ushort)num3, type, (byte)num4);
		}
	}
	public enum UnityVersionType : byte
	{
		Alpha = 0,
		Beta = 1,
		China = 2,
		Final = 3,
		Patch = 4,
		Experimental = 5,
		MinValue = 0,
		MaxValue = 5
	}
	public static class UnityVersionTypeExtentions
	{
		[Obsolete("Changed to ToCharacter", true)]
		public static char ToLiteral(this UnityVersionType _this)
		{
			return _this.ToCharacter();
		}

		public static char ToCharacter(this UnityVersionType type)
		{
			return type switch
			{
				UnityVersionType.Alpha => 'a', 
				UnityVersionType.Beta => 'b', 
				UnityVersionType.China => 'c', 
				UnityVersionType.Final => 'f', 
				UnityVersionType.Patch => 'p', 
				UnityVersionType.Experimental => 'x', 
				_ => 'u', 
			};
		}
	}
}
namespace AssetRipper.VersionUtilities.Extensions
{
	public static class BinaryReaderExtensions
	{
		public static UnityVersion ReadUnityVersion(this BinaryReader reader)
		{
			return UnityVersion.FromBits(reader.ReadUInt64());
		}

		public static CompactUnityVersion32 ReadCompactUnityVersion32(this BinaryReader reader)
		{
			return CompactUnityVersion32.FromBits(reader.ReadUInt32());
		}

		public static CompactUnityVersion24 ReadCompactUnityVersion24(this BinaryReader reader)
		{
			byte majorMinorByte = reader.ReadByte();
			ushort buildTypeShort = reader.ReadUInt16();
			return CompactUnityVersion24.FromBits(majorMinorByte, buildTypeShort);
		}
	}
	public static class BinaryWriterExtensions
	{
		public static void Write(this BinaryWriter writer, UnityVersion version)
		{
			writer.Write(version.GetBits());
		}

		public static void Write(this BinaryWriter writer, CompactUnityVersion32 version)
		{
			writer.Write(version.GetBits());
		}

		public static void Write(this BinaryWriter writer, CompactUnityVersion24 version)
		{
			version.GetBits(out var majorMinorByte, out var buildTypeShort);
			writer.Write(majorMinorByte);
			writer.Write(buildTypeShort);
		}
	}
	public static class CharacterExtensions
	{
		internal static int ParseDigit(this char _this)
		{
			return _this - 48;
		}

		public static UnityVersionType ToUnityVersionType(this char c)
		{
			return c switch
			{
				'a' => UnityVersionType.Alpha, 
				'b' => UnityVersionType.Beta, 
				'c' => UnityVersionType.China, 
				'f' => UnityVersionType.Final, 
				'p' => UnityVersionType.Patch, 
				'x' => UnityVersionType.Experimental, 
				_ => throw new ArgumentException($"There is no version type {c}", "c"), 
			};
		}
	}
}

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/BepInEx.MelonLoader.Loader/AssetsTools.NET.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.Text;
using System.Text.RegularExpressions;
using AssetsTools.NET.Extra;
using AssetsTools.NET.Extra.Decompressors.LZ4;
using LZ4ps;
using Mono.Cecil;
using Mono.Collections.Generic;
using SevenZip;
using SevenZip.Compression.LZ;
using SevenZip.Compression.LZMA;
using SevenZip.Compression.RangeCoder;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("AssetTools.NET")]
[assembly: AssemblyDescription("A remake and port of DerPopo's AssetTools")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("nesrak1")]
[assembly: AssemblyProduct("AssetTools.NET")]
[assembly: AssemblyCopyright("Written by nes")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("e09d5ac2-1a2e-4ec1-94ad-3f5e22f17658")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyVersion("2.0.0.0")]
namespace SevenZip
{
	internal class CRC
	{
		public static readonly uint[] Table;

		private uint _value = uint.MaxValue;

		static CRC()
		{
			Table = new uint[256];
			for (uint num = 0u; num < 256; num++)
			{
				uint num2 = num;
				for (int i = 0; i < 8; i++)
				{
					num2 = (((num2 & 1) == 0) ? (num2 >> 1) : ((num2 >> 1) ^ 0xEDB88320u));
				}
				Table[num] = num2;
			}
		}

		public void Init()
		{
			_value = uint.MaxValue;
		}

		public void UpdateByte(byte b)
		{
			_value = Table[(byte)_value ^ b] ^ (_value >> 8);
		}

		public void Update(byte[] data, uint offset, uint size)
		{
			for (uint num = 0u; num < size; num++)
			{
				_value = Table[(byte)_value ^ data[offset + num]] ^ (_value >> 8);
			}
		}

		public uint GetDigest()
		{
			return _value ^ 0xFFFFFFFFu;
		}

		private static uint CalculateDigest(byte[] data, uint offset, uint size)
		{
			CRC cRC = new CRC();
			cRC.Update(data, offset, size);
			return cRC.GetDigest();
		}

		private static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size)
		{
			return CalculateDigest(data, offset, size) == digest;
		}
	}
	internal class DataErrorException : ApplicationException
	{
		public DataErrorException()
			: base("Data Error")
		{
		}
	}
	internal class InvalidParamException : ApplicationException
	{
		public InvalidParamException()
			: base("Invalid Parameter")
		{
		}
	}
	public interface ICodeProgress
	{
		void SetProgress(long inSize, long outSize);
	}
	public interface ICoder
	{
		void Code(Stream inStream, Stream outStream, long inSize, long outSize, ICodeProgress progress);
	}
	public enum CoderPropID
	{
		DefaultProp,
		DictionarySize,
		UsedMemorySize,
		Order,
		BlockSize,
		PosStateBits,
		LitContextBits,
		LitPosBits,
		NumFastBytes,
		MatchFinder,
		MatchFinderCycles,
		NumPasses,
		Algorithm,
		NumThreads,
		EndMarker
	}
	public interface ISetCoderProperties
	{
		void SetCoderProperties(CoderPropID[] propIDs, object[] properties);
	}
	public interface IWriteCoderProperties
	{
		void WriteCoderProperties(Stream outStream);
	}
	public interface ISetDecoderProperties
	{
		void SetDecoderProperties(byte[] properties);
	}
}
namespace SevenZip.Compression.RangeCoder
{
	internal class Encoder
	{
		public const uint kTopValue = 16777216u;

		private Stream Stream;

		public ulong Low;

		public uint Range;

		private uint _cacheSize;

		private byte _cache;

		private long StartPosition;

		public void SetStream(Stream stream)
		{
			Stream = stream;
		}

		public void ReleaseStream()
		{
			Stream = null;
		}

		public void Init()
		{
			StartPosition = Stream.Position;
			Low = 0uL;
			Range = uint.MaxValue;
			_cacheSize = 1u;
			_cache = 0;
		}

		public void FlushData()
		{
			for (int i = 0; i < 5; i++)
			{
				ShiftLow();
			}
		}

		public void FlushStream()
		{
			Stream.Flush();
		}

		public void CloseStream()
		{
			Stream.Close();
		}

		public void Encode(uint start, uint size, uint total)
		{
			Low += start * (Range /= total);
			Range *= size;
			while (Range < 16777216)
			{
				Range <<= 8;
				ShiftLow();
			}
		}

		public void ShiftLow()
		{
			if ((uint)Low < 4278190080u || (int)(Low >> 32) == 1)
			{
				byte b = _cache;
				do
				{
					Stream.WriteByte((byte)(b + (Low >> 32)));
					b = byte.MaxValue;
				}
				while (--_cacheSize != 0);
				_cache = (byte)((uint)Low >> 24);
			}
			_cacheSize++;
			Low = (uint)((int)Low << 8);
		}

		public void EncodeDirectBits(uint v, int numTotalBits)
		{
			for (int num = numTotalBits - 1; num >= 0; num--)
			{
				Range >>= 1;
				if (((v >> num) & 1) == 1)
				{
					Low += Range;
				}
				if (Range < 16777216)
				{
					Range <<= 8;
					ShiftLow();
				}
			}
		}

		public void EncodeBit(uint size0, int numTotalBits, uint symbol)
		{
			uint num = (Range >> numTotalBits) * size0;
			if (symbol == 0)
			{
				Range = num;
			}
			else
			{
				Low += num;
				Range -= num;
			}
			while (Range < 16777216)
			{
				Range <<= 8;
				ShiftLow();
			}
		}

		public long GetProcessedSizeAdd()
		{
			return _cacheSize + Stream.Position - StartPosition + 4;
		}
	}
	internal class Decoder
	{
		public const uint kTopValue = 16777216u;

		public uint Range;

		public uint Code;

		public Stream Stream;

		public void Init(Stream stream)
		{
			Stream = stream;
			Code = 0u;
			Range = uint.MaxValue;
			for (int i = 0; i < 5; i++)
			{
				Code = (Code << 8) | (byte)Stream.ReadByte();
			}
		}

		public void ReleaseStream()
		{
			Stream = null;
		}

		public void CloseStream()
		{
			Stream.Close();
		}

		public void Normalize()
		{
			while (Range < 16777216)
			{
				Code = (Code << 8) | (byte)Stream.ReadByte();
				Range <<= 8;
			}
		}

		public void Normalize2()
		{
			if (Range < 16777216)
			{
				Code = (Code << 8) | (byte)Stream.ReadByte();
				Range <<= 8;
			}
		}

		public uint GetThreshold(uint total)
		{
			return Code / (Range /= total);
		}

		public void Decode(uint start, uint size, uint total)
		{
			Code -= start * Range;
			Range *= size;
			Normalize();
		}

		public uint DecodeDirectBits(int numTotalBits)
		{
			uint num = Range;
			uint num2 = Code;
			uint num3 = 0u;
			for (int num4 = numTotalBits; num4 > 0; num4--)
			{
				num >>= 1;
				uint num5 = num2 - num >> 31;
				num2 -= num & (num5 - 1);
				num3 = (num3 << 1) | (1 - num5);
				if (num < 16777216)
				{
					num2 = (num2 << 8) | (byte)Stream.ReadByte();
					num <<= 8;
				}
			}
			Range = num;
			Code = num2;
			return num3;
		}

		public uint DecodeBit(uint size0, int numTotalBits)
		{
			uint num = (Range >> numTotalBits) * size0;
			uint result;
			if (Code < num)
			{
				result = 0u;
				Range = num;
			}
			else
			{
				result = 1u;
				Code -= num;
				Range -= num;
			}
			Normalize();
			return result;
		}
	}
	internal struct BitEncoder
	{
		public const int kNumBitModelTotalBits = 11;

		public const uint kBitModelTotal = 2048u;

		private const int kNumMoveBits = 5;

		private const int kNumMoveReducingBits = 2;

		public const int kNumBitPriceShiftBits = 6;

		private uint Prob;

		private static uint[] ProbPrices;

		public void Init()
		{
			Prob = 1024u;
		}

		public void UpdateModel(uint symbol)
		{
			if (symbol == 0)
			{
				Prob += 2048 - Prob >> 5;
			}
			else
			{
				Prob -= Prob >> 5;
			}
		}

		public void Encode(Encoder encoder, uint symbol)
		{
			uint num = (encoder.Range >> 11) * Prob;
			if (symbol == 0)
			{
				encoder.Range = num;
				Prob += 2048 - Prob >> 5;
			}
			else
			{
				encoder.Low += num;
				encoder.Range -= num;
				Prob -= Prob >> 5;
			}
			if (encoder.Range < 16777216)
			{
				encoder.Range <<= 8;
				encoder.ShiftLow();
			}
		}

		static BitEncoder()
		{
			ProbPrices = new uint[512];
			for (int num = 8; num >= 0; num--)
			{
				int num2 = 1 << 9 - num - 1;
				uint num3 = (uint)(1 << 9 - num);
				for (uint num4 = (uint)num2; num4 < num3; num4++)
				{
					ProbPrices[num4] = (uint)(num << 6) + (num3 - num4 << 6 >> 9 - num - 1);
				}
			}
		}

		public uint GetPrice(uint symbol)
		{
			return ProbPrices[(((Prob - symbol) ^ (int)(0 - symbol)) & 0x7FF) >> 2];
		}

		public uint GetPrice0()
		{
			return ProbPrices[Prob >> 2];
		}

		public uint GetPrice1()
		{
			return ProbPrices[2048 - Prob >> 2];
		}
	}
	internal struct BitDecoder
	{
		public const int kNumBitModelTotalBits = 11;

		public const uint kBitModelTotal = 2048u;

		private const int kNumMoveBits = 5;

		private uint Prob;

		public void UpdateModel(int numMoveBits, uint symbol)
		{
			if (symbol == 0)
			{
				Prob += 2048 - Prob >> numMoveBits;
			}
			else
			{
				Prob -= Prob >> numMoveBits;
			}
		}

		public void Init()
		{
			Prob = 1024u;
		}

		public uint Decode(Decoder rangeDecoder)
		{
			uint num = (rangeDecoder.Range >> 11) * Prob;
			if (rangeDecoder.Code < num)
			{
				rangeDecoder.Range = num;
				Prob += 2048 - Prob >> 5;
				if (rangeDecoder.Range < 16777216)
				{
					rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte();
					rangeDecoder.Range <<= 8;
				}
				return 0u;
			}
			rangeDecoder.Range -= num;
			rangeDecoder.Code -= num;
			Prob -= Prob >> 5;
			if (rangeDecoder.Range < 16777216)
			{
				rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte();
				rangeDecoder.Range <<= 8;
			}
			return 1u;
		}
	}
	internal struct BitTreeEncoder
	{
		private BitEncoder[] Models;

		private int NumBitLevels;

		public BitTreeEncoder(int numBitLevels)
		{
			NumBitLevels = numBitLevels;
			Models = new BitEncoder[1 << numBitLevels];
		}

		public void Init()
		{
			for (uint num = 1u; num < 1 << NumBitLevels; num++)
			{
				Models[num].Init();
			}
		}

		public void Encode(Encoder rangeEncoder, uint symbol)
		{
			uint num = 1u;
			int num2 = NumBitLevels;
			while (num2 > 0)
			{
				num2--;
				uint num3 = (symbol >> num2) & 1u;
				Models[num].Encode(rangeEncoder, num3);
				num = (num << 1) | num3;
			}
		}

		public void ReverseEncode(Encoder rangeEncoder, uint symbol)
		{
			uint num = 1u;
			for (uint num2 = 0u; num2 < NumBitLevels; num2++)
			{
				uint num3 = symbol & 1u;
				Models[num].Encode(rangeEncoder, num3);
				num = (num << 1) | num3;
				symbol >>= 1;
			}
		}

		public uint GetPrice(uint symbol)
		{
			uint num = 0u;
			uint num2 = 1u;
			int num3 = NumBitLevels;
			while (num3 > 0)
			{
				num3--;
				uint num4 = (symbol >> num3) & 1u;
				num += Models[num2].GetPrice(num4);
				num2 = (num2 << 1) + num4;
			}
			return num;
		}

		public uint ReverseGetPrice(uint symbol)
		{
			uint num = 0u;
			uint num2 = 1u;
			for (int num3 = NumBitLevels; num3 > 0; num3--)
			{
				uint num4 = symbol & 1u;
				symbol >>= 1;
				num += Models[num2].GetPrice(num4);
				num2 = (num2 << 1) | num4;
			}
			return num;
		}

		public static uint ReverseGetPrice(BitEncoder[] Models, uint startIndex, int NumBitLevels, uint symbol)
		{
			uint num = 0u;
			uint num2 = 1u;
			for (int num3 = NumBitLevels; num3 > 0; num3--)
			{
				uint num4 = symbol & 1u;
				symbol >>= 1;
				num += Models[startIndex + num2].GetPrice(num4);
				num2 = (num2 << 1) | num4;
			}
			return num;
		}

		public static void ReverseEncode(BitEncoder[] Models, uint startIndex, Encoder rangeEncoder, int NumBitLevels, uint symbol)
		{
			uint num = 1u;
			for (int i = 0; i < NumBitLevels; i++)
			{
				uint num2 = symbol & 1u;
				Models[startIndex + num].Encode(rangeEncoder, num2);
				num = (num << 1) | num2;
				symbol >>= 1;
			}
		}
	}
	internal struct BitTreeDecoder
	{
		private BitDecoder[] Models;

		private int NumBitLevels;

		public BitTreeDecoder(int numBitLevels)
		{
			NumBitLevels = numBitLevels;
			Models = new BitDecoder[1 << numBitLevels];
		}

		public void Init()
		{
			for (uint num = 1u; num < 1 << NumBitLevels; num++)
			{
				Models[num].Init();
			}
		}

		public uint Decode(Decoder rangeDecoder)
		{
			uint num = 1u;
			for (int num2 = NumBitLevels; num2 > 0; num2--)
			{
				num = (num << 1) + Models[num].Decode(rangeDecoder);
			}
			return num - (uint)(1 << NumBitLevels);
		}

		public uint ReverseDecode(Decoder rangeDecoder)
		{
			uint num = 1u;
			uint num2 = 0u;
			for (int i = 0; i < NumBitLevels; i++)
			{
				uint num3 = Models[num].Decode(rangeDecoder);
				num <<= 1;
				num += num3;
				num2 |= num3 << i;
			}
			return num2;
		}

		public static uint ReverseDecode(BitDecoder[] Models, uint startIndex, Decoder rangeDecoder, int NumBitLevels)
		{
			uint num = 1u;
			uint num2 = 0u;
			for (int i = 0; i < NumBitLevels; i++)
			{
				uint num3 = Models[startIndex + num].Decode(rangeDecoder);
				num <<= 1;
				num += num3;
				num2 |= num3 << i;
			}
			return num2;
		}
	}
}
namespace SevenZip.Compression.LZ
{
	internal interface IInWindowStream
	{
		void SetStream(Stream inStream);

		void Init();

		void ReleaseStream();

		byte GetIndexByte(int index);

		uint GetMatchLen(int index, uint distance, uint limit);

		uint GetNumAvailableBytes();
	}
	internal interface IMatchFinder : IInWindowStream
	{
		void Create(uint historySize, uint keepAddBufferBefore, uint matchMaxLen, uint keepAddBufferAfter);

		uint GetMatches(uint[] distances);

		void Skip(uint num);
	}
	public class BinTree : InWindow, IMatchFinder, IInWindowStream
	{
		private uint _cyclicBufferPos;

		private uint _cyclicBufferSize;

		private uint _matchMaxLen;

		private uint[] _son;

		private uint[] _hash;

		private uint _cutValue = 255u;

		private uint _hashMask;

		private uint _hashSizeSum;

		private bool HASH_ARRAY = true;

		private const uint kHash2Size = 1024u;

		private const uint kHash3Size = 65536u;

		private const uint kBT2HashSize = 65536u;

		private const uint kStartMaxLen = 1u;

		private const uint kHash3Offset = 1024u;

		private const uint kEmptyHashValue = 0u;

		private const uint kMaxValForNormalize = 2147483647u;

		private uint kNumHashDirectBytes;

		private uint kMinMatchCheck = 4u;

		private uint kFixHashSize = 66560u;

		public void SetType(int numHashBytes)
		{
			HASH_ARRAY = numHashBytes > 2;
			if (HASH_ARRAY)
			{
				kNumHashDirectBytes = 0u;
				kMinMatchCheck = 4u;
				kFixHashSize = 66560u;
			}
			else
			{
				kNumHashDirectBytes = 2u;
				kMinMatchCheck = 3u;
				kFixHashSize = 0u;
			}
		}

		public new void SetStream(Stream stream)
		{
			base.SetStream(stream);
		}

		public new void ReleaseStream()
		{
			base.ReleaseStream();
		}

		public new void Init()
		{
			base.Init();
			for (uint num = 0u; num < _hashSizeSum; num++)
			{
				_hash[num] = 0u;
			}
			_cyclicBufferPos = 0u;
			ReduceOffsets(-1);
		}

		public new void MovePos()
		{
			if (++_cyclicBufferPos >= _cyclicBufferSize)
			{
				_cyclicBufferPos = 0u;
			}
			base.MovePos();
			if (_pos == int.MaxValue)
			{
				Normalize();
			}
		}

		public new byte GetIndexByte(int index)
		{
			return base.GetIndexByte(index);
		}

		public new uint GetMatchLen(int index, uint distance, uint limit)
		{
			return base.GetMatchLen(index, distance, limit);
		}

		public new uint GetNumAvailableBytes()
		{
			return base.GetNumAvailableBytes();
		}

		public void Create(uint historySize, uint keepAddBufferBefore, uint matchMaxLen, uint keepAddBufferAfter)
		{
			if (historySize > 2147483391)
			{
				throw new Exception();
			}
			_cutValue = 16 + (matchMaxLen >> 1);
			uint keepSizeReserv = (historySize + keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + 256;
			Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, keepSizeReserv);
			_matchMaxLen = matchMaxLen;
			uint num = historySize + 1;
			if (_cyclicBufferSize != num)
			{
				_son = new uint[(_cyclicBufferSize = num) * 2];
			}
			uint num2 = 65536u;
			if (HASH_ARRAY)
			{
				num2 = historySize - 1;
				num2 |= num2 >> 1;
				num2 |= num2 >> 2;
				num2 |= num2 >> 4;
				num2 |= num2 >> 8;
				num2 >>= 1;
				num2 |= 0xFFFFu;
				if (num2 > 16777216)
				{
					num2 >>= 1;
				}
				_hashMask = num2;
				num2++;
				num2 += kFixHashSize;
			}
			if (num2 != _hashSizeSum)
			{
				_hash = new uint[_hashSizeSum = num2];
			}
		}

		public uint GetMatches(uint[] distances)
		{
			uint num;
			if (_pos + _matchMaxLen <= _streamPos)
			{
				num = _matchMaxLen;
			}
			else
			{
				num = _streamPos - _pos;
				if (num < kMinMatchCheck)
				{
					MovePos();
					return 0u;
				}
			}
			uint num2 = 0u;
			uint num3 = ((_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0u);
			uint num4 = _bufferOffset + _pos;
			uint num5 = 1u;
			uint num6 = 0u;
			uint num7 = 0u;
			uint num10;
			if (HASH_ARRAY)
			{
				uint num8 = CRC.Table[_bufferBase[num4]] ^ _bufferBase[num4 + 1];
				num6 = num8 & 0x3FFu;
				int num9 = (int)num8 ^ (_bufferBase[num4 + 2] << 8);
				num7 = (uint)num9 & 0xFFFFu;
				num10 = ((uint)num9 ^ (CRC.Table[_bufferBase[num4 + 3]] << 5)) & _hashMask;
			}
			else
			{
				num10 = (uint)(_bufferBase[num4] ^ (_bufferBase[num4 + 1] << 8));
			}
			uint num11 = _hash[kFixHashSize + num10];
			if (HASH_ARRAY)
			{
				uint num12 = _hash[num6];
				uint num13 = _hash[1024 + num7];
				_hash[num6] = _pos;
				_hash[1024 + num7] = _pos;
				if (num12 > num3 && _bufferBase[_bufferOffset + num12] == _bufferBase[num4])
				{
					num5 = (distances[num2++] = 2u);
					distances[num2++] = _pos - num12 - 1;
				}
				if (num13 > num3 && _bufferBase[_bufferOffset + num13] == _bufferBase[num4])
				{
					if (num13 == num12)
					{
						num2 -= 2;
					}
					num5 = (distances[num2++] = 3u);
					distances[num2++] = _pos - num13 - 1;
					num12 = num13;
				}
				if (num2 != 0 && num12 == num11)
				{
					num2 -= 2;
					num5 = 1u;
				}
			}
			_hash[kFixHashSize + num10] = _pos;
			uint num14 = (_cyclicBufferPos << 1) + 1;
			uint num15 = _cyclicBufferPos << 1;
			uint val;
			uint val2 = (val = kNumHashDirectBytes);
			if (kNumHashDirectBytes != 0 && num11 > num3 && _bufferBase[_bufferOffset + num11 + kNumHashDirectBytes] != _bufferBase[num4 + kNumHashDirectBytes])
			{
				num5 = (distances[num2++] = kNumHashDirectBytes);
				distances[num2++] = _pos - num11 - 1;
			}
			uint cutValue = _cutValue;
			while (true)
			{
				if (num11 <= num3 || cutValue-- == 0)
				{
					_son[num14] = (_son[num15] = 0u);
					break;
				}
				uint num16 = _pos - num11;
				uint num17 = ((num16 <= _cyclicBufferPos) ? (_cyclicBufferPos - num16) : (_cyclicBufferPos - num16 + _cyclicBufferSize)) << 1;
				uint num18 = _bufferOffset + num11;
				uint num19 = Math.Min(val2, val);
				if (_bufferBase[num18 + num19] == _bufferBase[num4 + num19])
				{
					while (++num19 != num && _bufferBase[num18 + num19] == _bufferBase[num4 + num19])
					{
					}
					if (num5 < num19)
					{
						num5 = (distances[num2++] = num19);
						distances[num2++] = num16 - 1;
						if (num19 == num)
						{
							_son[num15] = _son[num17];
							_son[num14] = _son[num17 + 1];
							break;
						}
					}
				}
				if (_bufferBase[num18 + num19] < _bufferBase[num4 + num19])
				{
					_son[num15] = num11;
					num15 = num17 + 1;
					num11 = _son[num15];
					val = num19;
				}
				else
				{
					_son[num14] = num11;
					num14 = num17;
					num11 = _son[num14];
					val2 = num19;
				}
			}
			MovePos();
			return num2;
		}

		public void Skip(uint num)
		{
			do
			{
				uint num2;
				if (_pos + _matchMaxLen <= _streamPos)
				{
					num2 = _matchMaxLen;
				}
				else
				{
					num2 = _streamPos - _pos;
					if (num2 < kMinMatchCheck)
					{
						MovePos();
						continue;
					}
				}
				uint num3 = ((_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0u);
				uint num4 = _bufferOffset + _pos;
				uint num9;
				if (HASH_ARRAY)
				{
					uint num5 = CRC.Table[_bufferBase[num4]] ^ _bufferBase[num4 + 1];
					uint num6 = num5 & 0x3FFu;
					_hash[num6] = _pos;
					int num7 = (int)num5 ^ (_bufferBase[num4 + 2] << 8);
					uint num8 = (uint)num7 & 0xFFFFu;
					_hash[1024 + num8] = _pos;
					num9 = ((uint)num7 ^ (CRC.Table[_bufferBase[num4 + 3]] << 5)) & _hashMask;
				}
				else
				{
					num9 = (uint)(_bufferBase[num4] ^ (_bufferBase[num4 + 1] << 8));
				}
				uint num10 = _hash[kFixHashSize + num9];
				_hash[kFixHashSize + num9] = _pos;
				uint num11 = (_cyclicBufferPos << 1) + 1;
				uint num12 = _cyclicBufferPos << 1;
				uint val;
				uint val2 = (val = kNumHashDirectBytes);
				uint cutValue = _cutValue;
				while (true)
				{
					if (num10 <= num3 || cutValue-- == 0)
					{
						_son[num11] = (_son[num12] = 0u);
						break;
					}
					uint num13 = _pos - num10;
					uint num14 = ((num13 <= _cyclicBufferPos) ? (_cyclicBufferPos - num13) : (_cyclicBufferPos - num13 + _cyclicBufferSize)) << 1;
					uint num15 = _bufferOffset + num10;
					uint num16 = Math.Min(val2, val);
					if (_bufferBase[num15 + num16] == _bufferBase[num4 + num16])
					{
						while (++num16 != num2 && _bufferBase[num15 + num16] == _bufferBase[num4 + num16])
						{
						}
						if (num16 == num2)
						{
							_son[num12] = _son[num14];
							_son[num11] = _son[num14 + 1];
							break;
						}
					}
					if (_bufferBase[num15 + num16] < _bufferBase[num4 + num16])
					{
						_son[num12] = num10;
						num12 = num14 + 1;
						num10 = _son[num12];
						val = num16;
					}
					else
					{
						_son[num11] = num10;
						num11 = num14;
						num10 = _son[num11];
						val2 = num16;
					}
				}
				MovePos();
			}
			while (--num != 0);
		}

		private void NormalizeLinks(uint[] items, uint numItems, uint subValue)
		{
			for (uint num = 0u; num < numItems; num++)
			{
				uint num2 = items[num];
				num2 = ((num2 > subValue) ? (num2 - subValue) : 0u);
				items[num] = num2;
			}
		}

		private void Normalize()
		{
			uint subValue = _pos - _cyclicBufferSize;
			NormalizeLinks(_son, _cyclicBufferSize * 2, subValue);
			NormalizeLinks(_hash, _hashSizeSum, subValue);
			ReduceOffsets((int)subValue);
		}

		public void SetCutValue(uint cutValue)
		{
			_cutValue = cutValue;
		}
	}
	public class InWindow
	{
		public byte[] _bufferBase;

		private Stream _stream;

		private uint _posLimit;

		private bool _streamEndWasReached;

		private uint _pointerToLastSafePosition;

		public uint _bufferOffset;

		public uint _blockSize;

		public uint _pos;

		private uint _keepSizeBefore;

		private uint _keepSizeAfter;

		public uint _streamPos;

		public void MoveBlock()
		{
			uint num = _bufferOffset + _pos - _keepSizeBefore;
			if (num != 0)
			{
				num--;
			}
			uint num2 = _bufferOffset + _streamPos - num;
			for (uint num3 = 0u; num3 < num2; num3++)
			{
				_bufferBase[num3] = _bufferBase[num + num3];
			}
			_bufferOffset -= num;
		}

		public virtual void ReadBlock()
		{
			if (_streamEndWasReached)
			{
				return;
			}
			while (true)
			{
				int num = (int)(0 - _bufferOffset + _blockSize - _streamPos);
				if (num == 0)
				{
					return;
				}
				int num2 = _stream.Read(_bufferBase, (int)(_bufferOffset + _streamPos), num);
				if (num2 == 0)
				{
					break;
				}
				_streamPos += (uint)num2;
				if (_streamPos >= _pos + _keepSizeAfter)
				{
					_posLimit = _streamPos - _keepSizeAfter;
				}
			}
			_posLimit = _streamPos;
			if (_bufferOffset + _posLimit > _pointerToLastSafePosition)
			{
				_posLimit = _pointerToLastSafePosition - _bufferOffset;
			}
			_streamEndWasReached = true;
		}

		private void Free()
		{
			_bufferBase = null;
		}

		public void Create(uint keepSizeBefore, uint keepSizeAfter, uint keepSizeReserv)
		{
			_keepSizeBefore = keepSizeBefore;
			_keepSizeAfter = keepSizeAfter;
			uint num = keepSizeBefore + keepSizeAfter + keepSizeReserv;
			if (_bufferBase == null || _blockSize != num)
			{
				Free();
				_blockSize = num;
				_bufferBase = new byte[_blockSize];
			}
			_pointerToLastSafePosition = _blockSize - keepSizeAfter;
		}

		public void SetStream(Stream stream)
		{
			_stream = stream;
		}

		public void ReleaseStream()
		{
			_stream = null;
		}

		public void Init()
		{
			_bufferOffset = 0u;
			_pos = 0u;
			_streamPos = 0u;
			_streamEndWasReached = false;
			ReadBlock();
		}

		public void MovePos()
		{
			_pos++;
			if (_pos > _posLimit)
			{
				if (_bufferOffset + _pos > _pointerToLastSafePosition)
				{
					MoveBlock();
				}
				ReadBlock();
			}
		}

		public byte GetIndexByte(int index)
		{
			return _bufferBase[_bufferOffset + _pos + index];
		}

		public uint GetMatchLen(int index, uint distance, uint limit)
		{
			if (_streamEndWasReached && _pos + index + limit > _streamPos)
			{
				limit = _streamPos - (uint)(int)(_pos + index);
			}
			distance++;
			uint num = _bufferOffset + _pos + (uint)index;
			uint num2;
			for (num2 = 0u; num2 < limit && _bufferBase[num + num2] == _bufferBase[num + num2 - distance]; num2++)
			{
			}
			return num2;
		}

		public uint GetNumAvailableBytes()
		{
			return _streamPos - _pos;
		}

		public void ReduceOffsets(int subValue)
		{
			_bufferOffset += (uint)subValue;
			_posLimit -= (uint)subValue;
			_pos -= (uint)subValue;
			_streamPos -= (uint)subValue;
		}
	}
	public class OutWindow
	{
		private byte[] _buffer;

		private uint _pos;

		private uint _windowSize;

		private uint _streamPos;

		private Stream _stream;

		public uint TrainSize;

		public void Create(uint windowSize)
		{
			if (_windowSize != windowSize)
			{
				_buffer = new byte[windowSize];
			}
			_windowSize = windowSize;
			_pos = 0u;
			_streamPos = 0u;
		}

		public void Init(Stream stream, bool solid)
		{
			ReleaseStream();
			_stream = stream;
			if (!solid)
			{
				_streamPos = 0u;
				_pos = 0u;
				TrainSize = 0u;
			}
		}

		public bool Train(Stream stream)
		{
			long length = stream.Length;
			uint num = (TrainSize = (uint)((length < _windowSize) ? length : _windowSize));
			stream.Position = length - num;
			_streamPos = (_pos = 0u);
			while (num != 0)
			{
				uint num2 = _windowSize - _pos;
				if (num < num2)
				{
					num2 = num;
				}
				int num3 = stream.Read(_buffer, (int)_pos, (int)num2);
				if (num3 == 0)
				{
					return false;
				}
				num -= (uint)num3;
				_pos += (uint)num3;
				_streamPos += (uint)num3;
				if (_pos == _windowSize)
				{
					_streamPos = (_pos = 0u);
				}
			}
			return true;
		}

		public void ReleaseStream()
		{
			Flush();
			_stream = null;
		}

		public void Flush()
		{
			uint num = _pos - _streamPos;
			if (num != 0)
			{
				_stream.Write(_buffer, (int)_streamPos, (int)num);
				if (_pos >= _windowSize)
				{
					_pos = 0u;
				}
				_streamPos = _pos;
			}
		}

		public void CopyBlock(uint distance, uint len)
		{
			uint num = _pos - distance - 1;
			if (num >= _windowSize)
			{
				num += _windowSize;
			}
			while (len != 0)
			{
				if (num >= _windowSize)
				{
					num = 0u;
				}
				_buffer[_pos++] = _buffer[num++];
				if (_pos >= _windowSize)
				{
					Flush();
				}
				len--;
			}
		}

		public void PutByte(byte b)
		{
			_buffer[_pos++] = b;
			if (_pos >= _windowSize)
			{
				Flush();
			}
		}

		public byte GetByte(uint distance)
		{
			uint num = _pos - distance - 1;
			if (num >= _windowSize)
			{
				num += _windowSize;
			}
			return _buffer[num];
		}
	}
}
namespace SevenZip.Compression.LZMA
{
	internal abstract class Base
	{
		public struct State
		{
			public uint Index;

			public void Init()
			{
				Index = 0u;
			}

			public void UpdateChar()
			{
				if (Index < 4)
				{
					Index = 0u;
				}
				else if (Index < 10)
				{
					Index -= 3u;
				}
				else
				{
					Index -= 6u;
				}
			}

			public void UpdateMatch()
			{
				Index = ((Index < 7) ? 7u : 10u);
			}

			public void UpdateRep()
			{
				Index = ((Index < 7) ? 8u : 11u);
			}

			public void UpdateShortRep()
			{
				Index = ((Index < 7) ? 9u : 11u);
			}

			public bool IsCharState()
			{
				return Index < 7;
			}
		}

		public const uint kNumRepDistances = 4u;

		public const uint kNumStates = 12u;

		public const int kNumPosSlotBits = 6;

		public const int kDicLogSizeMin = 0;

		public const int kNumLenToPosStatesBits = 2;

		public const uint kNumLenToPosStates = 4u;

		public const uint kMatchMinLen = 2u;

		public const int kNumAlignBits = 4;

		public const uint kAlignTableSize = 16u;

		public const uint kAlignMask = 15u;

		public const uint kStartPosModelIndex = 4u;

		public const uint kEndPosModelIndex = 14u;

		public const uint kNumPosModels = 10u;

		public const uint kNumFullDistances = 128u;

		public const uint kNumLitPosStatesBitsEncodingMax = 4u;

		public const uint kNumLitContextBitsMax = 8u;

		public const int kNumPosStatesBitsMax = 4;

		public const uint kNumPosStatesMax = 16u;

		public const int kNumPosStatesBitsEncodingMax = 4;

		public const uint kNumPosStatesEncodingMax = 16u;

		public const int kNumLowLenBits = 3;

		public const int kNumMidLenBits = 3;

		public const int kNumHighLenBits = 8;

		public const uint kNumLowLenSymbols = 8u;

		public const uint kNumMidLenSymbols = 8u;

		public const uint kNumLenSymbols = 272u;

		public const uint kMatchMaxLen = 273u;

		public static uint GetLenToPosState(uint len)
		{
			len -= 2;
			if (len < 4)
			{
				return len;
			}
			return 3u;
		}
	}
	public class Decoder : ICoder, ISetDecoderProperties
	{
		private class LenDecoder
		{
			private BitDecoder m_Choice;

			private BitDecoder m_Choice2;

			private BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[16];

			private BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[16];

			private BitTreeDecoder m_HighCoder = new BitTreeDecoder(8);

			private uint m_NumPosStates;

			public void Create(uint numPosStates)
			{
				for (uint num = m_NumPosStates; num < numPosStates; num++)
				{
					m_LowCoder[num] = new BitTreeDecoder(3);
					m_MidCoder[num] = new BitTreeDecoder(3);
				}
				m_NumPosStates = numPosStates;
			}

			public void Init()
			{
				m_Choice.Init();
				for (uint num = 0u; num < m_NumPosStates; num++)
				{
					m_LowCoder[num].Init();
					m_MidCoder[num].Init();
				}
				m_Choice2.Init();
				m_HighCoder.Init();
			}

			public uint Decode(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, uint posState)
			{
				if (m_Choice.Decode(rangeDecoder) == 0)
				{
					return m_LowCoder[posState].Decode(rangeDecoder);
				}
				uint num = 8u;
				if (m_Choice2.Decode(rangeDecoder) == 0)
				{
					return num + m_MidCoder[posState].Decode(rangeDecoder);
				}
				num += 8;
				return num + m_HighCoder.Decode(rangeDecoder);
			}
		}

		private class LiteralDecoder
		{
			private struct Decoder2
			{
				private BitDecoder[] m_Decoders;

				public void Create()
				{
					m_Decoders = new BitDecoder[768];
				}

				public void Init()
				{
					for (int i = 0; i < 768; i++)
					{
						m_Decoders[i].Init();
					}
				}

				public byte DecodeNormal(SevenZip.Compression.RangeCoder.Decoder rangeDecoder)
				{
					uint num = 1u;
					do
					{
						num = (num << 1) | m_Decoders[num].Decode(rangeDecoder);
					}
					while (num < 256);
					return (byte)num;
				}

				public byte DecodeWithMatchByte(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, byte matchByte)
				{
					uint num = 1u;
					do
					{
						uint num2 = (uint)(matchByte >> 7) & 1u;
						matchByte <<= 1;
						uint num3 = m_Decoders[(1 + num2 << 8) + num].Decode(rangeDecoder);
						num = (num << 1) | num3;
						if (num2 != num3)
						{
							while (num < 256)
							{
								num = (num << 1) | m_Decoders[num].Decode(rangeDecoder);
							}
							break;
						}
					}
					while (num < 256);
					return (byte)num;
				}
			}

			private Decoder2[] m_Coders;

			private int m_NumPrevBits;

			private int m_NumPosBits;

			private uint m_PosMask;

			public void Create(int numPosBits, int numPrevBits)
			{
				if (m_Coders == null || m_NumPrevBits != numPrevBits || m_NumPosBits != numPosBits)
				{
					m_NumPosBits = numPosBits;
					m_PosMask = (uint)((1 << numPosBits) - 1);
					m_NumPrevBits = numPrevBits;
					uint num = (uint)(1 << m_NumPrevBits + m_NumPosBits);
					m_Coders = new Decoder2[num];
					for (uint num2 = 0u; num2 < num; num2++)
					{
						m_Coders[num2].Create();
					}
				}
			}

			public void Init()
			{
				uint num = (uint)(1 << m_NumPrevBits + m_NumPosBits);
				for (uint num2 = 0u; num2 < num; num2++)
				{
					m_Coders[num2].Init();
				}
			}

			private uint GetState(uint pos, byte prevByte)
			{
				return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> 8 - m_NumPrevBits);
			}

			public byte DecodeNormal(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte)
			{
				return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder);
			}

			public byte DecodeWithMatchByte(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte)
			{
				return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte);
			}
		}

		private OutWindow m_OutWindow = new OutWindow();

		private SevenZip.Compression.RangeCoder.Decoder m_RangeDecoder = new SevenZip.Compression.RangeCoder.Decoder();

		private BitDecoder[] m_IsMatchDecoders = new BitDecoder[192];

		private BitDecoder[] m_IsRepDecoders = new BitDecoder[12];

		private BitDecoder[] m_IsRepG0Decoders = new BitDecoder[12];

		private BitDecoder[] m_IsRepG1Decoders = new BitDecoder[12];

		private BitDecoder[] m_IsRepG2Decoders = new BitDecoder[12];

		private BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[192];

		private BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[4];

		private BitDecoder[] m_PosDecoders = new BitDecoder[114];

		private BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(4);

		private LenDecoder m_LenDecoder = new LenDecoder();

		private LenDecoder m_RepLenDecoder = new LenDecoder();

		private LiteralDecoder m_LiteralDecoder = new LiteralDecoder();

		private uint m_DictionarySize;

		private uint m_DictionarySizeCheck;

		private uint m_PosStateMask;

		private bool _solid;

		public Decoder()
		{
			m_DictionarySize = uint.MaxValue;
			for (int i = 0; (long)i < 4L; i++)
			{
				m_PosSlotDecoder[i] = new BitTreeDecoder(6);
			}
		}

		private void SetDictionarySize(uint dictionarySize)
		{
			if (m_DictionarySize != dictionarySize)
			{
				m_DictionarySize = dictionarySize;
				m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1u);
				uint windowSize = Math.Max(m_DictionarySizeCheck, 4096u);
				m_OutWindow.Create(windowSize);
			}
		}

		private void SetLiteralProperties(int lp, int lc)
		{
			if (lp > 8)
			{
				throw new InvalidParamException();
			}
			if (lc > 8)
			{
				throw new InvalidParamException();
			}
			m_LiteralDecoder.Create(lp, lc);
		}

		private void SetPosBitsProperties(int pb)
		{
			if (pb > 4)
			{
				throw new InvalidParamException();
			}
			uint num = (uint)(1 << pb);
			m_LenDecoder.Create(num);
			m_RepLenDecoder.Create(num);
			m_PosStateMask = num - 1;
		}

		private void Init(Stream inStream, Stream outStream)
		{
			m_RangeDecoder.Init(inStream);
			m_OutWindow.Init(outStream, _solid);
			for (uint num = 0u; num < 12; num++)
			{
				for (uint num2 = 0u; num2 <= m_PosStateMask; num2++)
				{
					uint num3 = (num << 4) + num2;
					m_IsMatchDecoders[num3].Init();
					m_IsRep0LongDecoders[num3].Init();
				}
				m_IsRepDecoders[num].Init();
				m_IsRepG0Decoders[num].Init();
				m_IsRepG1Decoders[num].Init();
				m_IsRepG2Decoders[num].Init();
			}
			m_LiteralDecoder.Init();
			for (uint num = 0u; num < 4; num++)
			{
				m_PosSlotDecoder[num].Init();
			}
			for (uint num = 0u; num < 114; num++)
			{
				m_PosDecoders[num].Init();
			}
			m_LenDecoder.Init();
			m_RepLenDecoder.Init();
			m_PosAlignDecoder.Init();
		}

		public void Code(Stream inStream, Stream outStream, long inSize, long outSize, ICodeProgress progress)
		{
			Init(inStream, outStream);
			Base.State state = default(Base.State);
			state.Init();
			uint num = 0u;
			uint num2 = 0u;
			uint num3 = 0u;
			uint num4 = 0u;
			ulong num5 = 0uL;
			if (num5 < (ulong)outSize)
			{
				if (m_IsMatchDecoders[state.Index << 4].Decode(m_RangeDecoder) != 0)
				{
					throw new DataErrorException();
				}
				state.UpdateChar();
				byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0u, 0);
				m_OutWindow.PutByte(b);
				num5++;
			}
			while (num5 < (ulong)outSize)
			{
				uint num6 = (uint)(int)num5 & m_PosStateMask;
				if (m_IsMatchDecoders[(state.Index << 4) + num6].Decode(m_RangeDecoder) == 0)
				{
					byte @byte = m_OutWindow.GetByte(0u);
					byte b2 = (state.IsCharState() ? m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)num5, @byte) : m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder, (uint)num5, @byte, m_OutWindow.GetByte(num)));
					m_OutWindow.PutByte(b2);
					state.UpdateChar();
					num5++;
					continue;
				}
				uint num8;
				if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1)
				{
					if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0)
					{
						if (m_IsRep0LongDecoders[(state.Index << 4) + num6].Decode(m_RangeDecoder) == 0)
						{
							state.UpdateShortRep();
							m_OutWindow.PutByte(m_OutWindow.GetByte(num));
							num5++;
							continue;
						}
					}
					else
					{
						uint num7;
						if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0)
						{
							num7 = num2;
						}
						else
						{
							if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0)
							{
								num7 = num3;
							}
							else
							{
								num7 = num4;
								num4 = num3;
							}
							num3 = num2;
						}
						num2 = num;
						num = num7;
					}
					num8 = m_RepLenDecoder.Decode(m_RangeDecoder, num6) + 2;
					state.UpdateRep();
				}
				else
				{
					num4 = num3;
					num3 = num2;
					num2 = num;
					num8 = 2 + m_LenDecoder.Decode(m_RangeDecoder, num6);
					state.UpdateMatch();
					uint num9 = m_PosSlotDecoder[Base.GetLenToPosState(num8)].Decode(m_RangeDecoder);
					if (num9 >= 4)
					{
						int num10 = (int)((num9 >> 1) - 1);
						num = (2 | (num9 & 1)) << num10;
						if (num9 < 14)
						{
							num += BitTreeDecoder.ReverseDecode(m_PosDecoders, num - num9 - 1, m_RangeDecoder, num10);
						}
						else
						{
							num += m_RangeDecoder.DecodeDirectBits(num10 - 4) << 4;
							num += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder);
						}
					}
					else
					{
						num = num9;
					}
				}
				if (num >= m_OutWindow.TrainSize + num5 || num >= m_DictionarySizeCheck)
				{
					if (num == uint.MaxValue)
					{
						break;
					}
					throw new DataErrorException();
				}
				m_OutWindow.CopyBlock(num, num8);
				num5 += num8;
			}
			m_OutWindow.Flush();
			m_OutWindow.ReleaseStream();
			m_RangeDecoder.ReleaseStream();
		}

		public void SetDecoderProperties(byte[] properties)
		{
			if (properties.Length < 5)
			{
				throw new InvalidParamException();
			}
			int lc = properties[0] % 9;
			int num = properties[0] / 9;
			int lp = num % 5;
			int num2 = num / 5;
			if (num2 > 4)
			{
				throw new InvalidParamException();
			}
			uint num3 = 0u;
			for (int i = 0; i < 4; i++)
			{
				num3 += (uint)(properties[1 + i] << i * 8);
			}
			SetDictionarySize(num3);
			SetLiteralProperties(lp, lc);
			SetPosBitsProperties(num2);
		}

		public bool Train(Stream stream)
		{
			_solid = true;
			return m_OutWindow.Train(stream);
		}
	}
	public class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties
	{
		private enum EMatchFinderType
		{
			BT2,
			BT4
		}

		private class LiteralEncoder
		{
			public struct Encoder2
			{
				private BitEncoder[] m_Encoders;

				public void Create()
				{
					m_Encoders = new BitEncoder[768];
				}

				public void Init()
				{
					for (int i = 0; i < 768; i++)
					{
						m_Encoders[i].Init();
					}
				}

				public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte symbol)
				{
					uint num = 1u;
					for (int num2 = 7; num2 >= 0; num2--)
					{
						uint num3 = (uint)(symbol >> num2) & 1u;
						m_Encoders[num].Encode(rangeEncoder, num3);
						num = (num << 1) | num3;
					}
				}

				public void EncodeMatched(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol)
				{
					uint num = 1u;
					bool flag = true;
					for (int num2 = 7; num2 >= 0; num2--)
					{
						uint num3 = (uint)(symbol >> num2) & 1u;
						uint num4 = num;
						if (flag)
						{
							uint num5 = (uint)(matchByte >> num2) & 1u;
							num4 += 1 + num5 << 8;
							flag = num5 == num3;
						}
						m_Encoders[num4].Encode(rangeEncoder, num3);
						num = (num << 1) | num3;
					}
				}

				public uint GetPrice(bool matchMode, byte matchByte, byte symbol)
				{
					uint num = 0u;
					uint num2 = 1u;
					int num3 = 7;
					if (matchMode)
					{
						while (num3 >= 0)
						{
							uint num4 = (uint)(matchByte >> num3) & 1u;
							uint num5 = (uint)(symbol >> num3) & 1u;
							num += m_Encoders[(1 + num4 << 8) + num2].GetPrice(num5);
							num2 = (num2 << 1) | num5;
							if (num4 != num5)
							{
								num3--;
								break;
							}
							num3--;
						}
					}
					while (num3 >= 0)
					{
						uint num6 = (uint)(symbol >> num3) & 1u;
						num += m_Encoders[num2].GetPrice(num6);
						num2 = (num2 << 1) | num6;
						num3--;
					}
					return num;
				}
			}

			private Encoder2[] m_Coders;

			private int m_NumPrevBits;

			private int m_NumPosBits;

			private uint m_PosMask;

			public void Create(int numPosBits, int numPrevBits)
			{
				if (m_Coders == null || m_NumPrevBits != numPrevBits || m_NumPosBits != numPosBits)
				{
					m_NumPosBits = numPosBits;
					m_PosMask = (uint)((1 << numPosBits) - 1);
					m_NumPrevBits = numPrevBits;
					uint num = (uint)(1 << m_NumPrevBits + m_NumPosBits);
					m_Coders = new Encoder2[num];
					for (uint num2 = 0u; num2 < num; num2++)
					{
						m_Coders[num2].Create();
					}
				}
			}

			public void Init()
			{
				uint num = (uint)(1 << m_NumPrevBits + m_NumPosBits);
				for (uint num2 = 0u; num2 < num; num2++)
				{
					m_Coders[num2].Init();
				}
			}

			public Encoder2 GetSubCoder(uint pos, byte prevByte)
			{
				return m_Coders[(int)((pos & m_PosMask) << m_NumPrevBits) + (prevByte >> 8 - m_NumPrevBits)];
			}
		}

		private class LenEncoder
		{
			private BitEncoder _choice;

			private BitEncoder _choice2;

			private BitTreeEncoder[] _lowCoder = new BitTreeEncoder[16];

			private BitTreeEncoder[] _midCoder = new BitTreeEncoder[16];

			private BitTreeEncoder _highCoder = new BitTreeEncoder(8);

			public LenEncoder()
			{
				for (uint num = 0u; num < 16; num++)
				{
					_lowCoder[num] = new BitTreeEncoder(3);
					_midCoder[num] = new BitTreeEncoder(3);
				}
			}

			public void Init(uint numPosStates)
			{
				_choice.Init();
				_choice2.Init();
				for (uint num = 0u; num < numPosStates; num++)
				{
					_lowCoder[num].Init();
					_midCoder[num].Init();
				}
				_highCoder.Init();
			}

			public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, uint symbol, uint posState)
			{
				if (symbol < 8)
				{
					_choice.Encode(rangeEncoder, 0u);
					_lowCoder[posState].Encode(rangeEncoder, symbol);
					return;
				}
				symbol -= 8;
				_choice.Encode(rangeEncoder, 1u);
				if (symbol < 8)
				{
					_choice2.Encode(rangeEncoder, 0u);
					_midCoder[posState].Encode(rangeEncoder, symbol);
				}
				else
				{
					_choice2.Encode(rangeEncoder, 1u);
					_highCoder.Encode(rangeEncoder, symbol - 8);
				}
			}

			public void SetPrices(uint posState, uint numSymbols, uint[] prices, uint st)
			{
				uint price = _choice.GetPrice0();
				uint price2 = _choice.GetPrice1();
				uint num = price2 + _choice2.GetPrice0();
				uint num2 = price2 + _choice2.GetPrice1();
				uint num3 = 0u;
				for (num3 = 0u; num3 < 8; num3++)
				{
					if (num3 >= numSymbols)
					{
						return;
					}
					prices[st + num3] = price + _lowCoder[posState].GetPrice(num3);
				}
				for (; num3 < 16; num3++)
				{
					if (num3 >= numSymbols)
					{
						return;
					}
					prices[st + num3] = num + _midCoder[posState].GetPrice(num3 - 8);
				}
				for (; num3 < numSymbols; num3++)
				{
					prices[st + num3] = num2 + _highCoder.GetPrice(num3 - 8 - 8);
				}
			}
		}

		private class LenPriceTableEncoder : LenEncoder
		{
			private uint[] _prices = new uint[4352];

			private uint _tableSize;

			private uint[] _counters = new uint[16];

			public void SetTableSize(uint tableSize)
			{
				_tableSize = tableSize;
			}

			public uint GetPrice(uint symbol, uint posState)
			{
				return _prices[posState * 272 + symbol];
			}

			private void UpdateTable(uint posState)
			{
				SetPrices(posState, _tableSize, _prices, posState * 272);
				_counters[posState] = _tableSize;
			}

			public void UpdateTables(uint numPosStates)
			{
				for (uint num = 0u; num < numPosStates; num++)
				{
					UpdateTable(num);
				}
			}

			public new void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, uint symbol, uint posState)
			{
				base.Encode(rangeEncoder, symbol, posState);
				if (--_counters[posState] == 0)
				{
					UpdateTable(posState);
				}
			}
		}

		private class Optimal
		{
			public Base.State State;

			public bool Prev1IsChar;

			public bool Prev2;

			public uint PosPrev2;

			public uint BackPrev2;

			public uint Price;

			public uint PosPrev;

			public uint BackPrev;

			public uint Backs0;

			public uint Backs1;

			public uint Backs2;

			public uint Backs3;

			public void MakeAsChar()
			{
				BackPrev = uint.MaxValue;
				Prev1IsChar = false;
			}

			public void MakeAsShortRep()
			{
				BackPrev = 0u;
				Prev1IsChar = false;
			}

			public bool IsShortRep()
			{
				return BackPrev == 0;
			}
		}

		private const uint kIfinityPrice = 268435455u;

		private static byte[] g_FastPos;

		private Base.State _state;

		private byte _previousByte;

		private uint[] _repDistances = new uint[4];

		private const int kDefaultDictionaryLogSize = 22;

		private const uint kNumFastBytesDefault = 32u;

		private const uint kNumLenSpecSymbols = 16u;

		private const uint kNumOpts = 4096u;

		private Optimal[] _optimum = new Optimal[4096];

		private IMatchFinder _matchFinder;

		private SevenZip.Compression.RangeCoder.Encoder _rangeEncoder = new SevenZip.Compression.RangeCoder.Encoder();

		private BitEncoder[] _isMatch = new BitEncoder[192];

		private BitEncoder[] _isRep = new BitEncoder[12];

		private BitEncoder[] _isRepG0 = new BitEncoder[12];

		private BitEncoder[] _isRepG1 = new BitEncoder[12];

		private BitEncoder[] _isRepG2 = new BitEncoder[12];

		private BitEncoder[] _isRep0Long = new BitEncoder[192];

		private BitTreeEncoder[] _posSlotEncoder = new BitTreeEncoder[4];

		private BitEncoder[] _posEncoders = new BitEncoder[114];

		private BitTreeEncoder _posAlignEncoder = new BitTreeEncoder(4);

		private LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder();

		private LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder();

		private LiteralEncoder _literalEncoder = new LiteralEncoder();

		private uint[] _matchDistances = new uint[548];

		private uint _numFastBytes = 32u;

		private uint _longestMatchLength;

		private uint _numDistancePairs;

		private uint _additionalOffset;

		private uint _optimumEndIndex;

		private uint _optimumCurrentIndex;

		private bool _longestMatchWasFound;

		private uint[] _posSlotPrices = new uint[256];

		private uint[] _distancesPrices = new uint[512];

		private uint[] _alignPrices = new uint[16];

		private uint _alignPriceCount;

		private uint _distTableSize = 44u;

		private int _posStateBits = 2;

		private uint _posStateMask = 3u;

		private int _numLiteralPosStateBits;

		private int _numLiteralContextBits = 3;

		private uint _dictionarySize = 4194304u;

		private uint _dictionarySizePrev = uint.MaxValue;

		private uint _numFastBytesPrev = uint.MaxValue;

		private long nowPos64;

		private bool _finished;

		private Stream _inStream;

		private EMatchFinderType _matchFinderType = EMatchFinderType.BT4;

		private bool _writeEndMark;

		private bool _needReleaseMFStream;

		private uint[] reps = new uint[4];

		private uint[] repLens = new uint[4];

		private const int kPropSize = 5;

		private byte[] properties = new byte[5];

		private uint[] tempPrices = new uint[128];

		private uint _matchPriceCount;

		private static string[] kMatchFinderIDs;

		private uint _trainSize;

		static Encoder()
		{
			g_FastPos = new byte[2048];
			kMatchFinderIDs = new string[2] { "BT2", "BT4" };
			int num = 2;
			g_FastPos[0] = 0;
			g_FastPos[1] = 1;
			for (byte b = 2; b < 22; b++)
			{
				uint num2 = (uint)(1 << (b >> 1) - 1);
				uint num3 = 0u;
				while (num3 < num2)
				{
					g_FastPos[num] = b;
					num3++;
					num++;
				}
			}
		}

		private static uint GetPosSlot(uint pos)
		{
			if (pos < 2048)
			{
				return g_FastPos[pos];
			}
			if (pos < 2097152)
			{
				return (uint)(g_FastPos[pos >> 10] + 20);
			}
			return (uint)(g_FastPos[pos >> 20] + 40);
		}

		private static uint GetPosSlot2(uint pos)
		{
			if (pos < 131072)
			{
				return (uint)(g_FastPos[pos >> 6] + 12);
			}
			if (pos < 134217728)
			{
				return (uint)(g_FastPos[pos >> 16] + 32);
			}
			return (uint)(g_FastPos[pos >> 26] + 52);
		}

		private void BaseInit()
		{
			_state.Init();
			_previousByte = 0;
			for (uint num = 0u; num < 4; num++)
			{
				_repDistances[num] = 0u;
			}
		}

		private void Create()
		{
			if (_matchFinder == null)
			{
				BinTree binTree = new BinTree();
				int type = 4;
				if (_matchFinderType == EMatchFinderType.BT2)
				{
					type = 2;
				}
				binTree.SetType(type);
				_matchFinder = binTree;
			}
			_literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits);
			if (_dictionarySize != _dictionarySizePrev || _numFastBytesPrev != _numFastBytes)
			{
				_matchFinder.Create(_dictionarySize, 4096u, _numFastBytes, 274u);
				_dictionarySizePrev = _dictionarySize;
				_numFastBytesPrev = _numFastBytes;
			}
		}

		public Encoder()
		{
			for (int i = 0; (long)i < 4096L; i++)
			{
				_optimum[i] = new Optimal();
			}
			for (int j = 0; (long)j < 4L; j++)
			{
				_posSlotEncoder[j] = new BitTreeEncoder(6);
			}
		}

		private void SetWriteEndMarkerMode(bool writeEndMarker)
		{
			_writeEndMark = writeEndMarker;
		}

		private void Init()
		{
			BaseInit();
			_rangeEncoder.Init();
			for (uint num = 0u; num < 12; num++)
			{
				for (uint num2 = 0u; num2 <= _posStateMask; num2++)
				{
					uint num3 = (num << 4) + num2;
					_isMatch[num3].Init();
					_isRep0Long[num3].Init();
				}
				_isRep[num].Init();
				_isRepG0[num].Init();
				_isRepG1[num].Init();
				_isRepG2[num].Init();
			}
			_literalEncoder.Init();
			for (uint num = 0u; num < 4; num++)
			{
				_posSlotEncoder[num].Init();
			}
			for (uint num = 0u; num < 114; num++)
			{
				_posEncoders[num].Init();
			}
			_lenEncoder.Init((uint)(1 << _posStateBits));
			_repMatchLenEncoder.Init((uint)(1 << _posStateBits));
			_posAlignEncoder.Init();
			_longestMatchWasFound = false;
			_optimumEndIndex = 0u;
			_optimumCurrentIndex = 0u;
			_additionalOffset = 0u;
		}

		private void ReadMatchDistances(out uint lenRes, out uint numDistancePairs)
		{
			lenRes = 0u;
			numDistancePairs = _matchFinder.GetMatches(_matchDistances);
			if (numDistancePairs != 0)
			{
				lenRes = _matchDistances[numDistancePairs - 2];
				if (lenRes == _numFastBytes)
				{
					lenRes += _matchFinder.GetMatchLen((int)(lenRes - 1), _matchDistances[numDistancePairs - 1], 273 - lenRes);
				}
			}
			_additionalOffset++;
		}

		private void MovePos(uint num)
		{
			if (num != 0)
			{
				_matchFinder.Skip(num);
				_additionalOffset += num;
			}
		}

		private uint GetRepLen1Price(Base.State state, uint posState)
		{
			return _isRepG0[state.Index].GetPrice0() + _isRep0Long[(state.Index << 4) + posState].GetPrice0();
		}

		private uint GetPureRepPrice(uint repIndex, Base.State state, uint posState)
		{
			uint price;
			if (repIndex == 0)
			{
				price = _isRepG0[state.Index].GetPrice0();
				return price + _isRep0Long[(state.Index << 4) + posState].GetPrice1();
			}
			price = _isRepG0[state.Index].GetPrice1();
			if (repIndex == 1)
			{
				return price + _isRepG1[state.Index].GetPrice0();
			}
			price += _isRepG1[state.Index].GetPrice1();
			return price + _isRepG2[state.Index].GetPrice(repIndex - 2);
		}

		private uint GetRepPrice(uint repIndex, uint len, Base.State state, uint posState)
		{
			return _repMatchLenEncoder.GetPrice(len - 2, posState) + GetPureRepPrice(repIndex, state, posState);
		}

		private uint GetPosLenPrice(uint pos, uint len, uint posState)
		{
			uint lenToPosState = Base.GetLenToPosState(len);
			uint num = ((pos >= 128) ? (_posSlotPrices[(lenToPosState << 6) + GetPosSlot2(pos)] + _alignPrices[pos & 0xF]) : _distancesPrices[lenToPosState * 128 + pos]);
			return num + _lenEncoder.GetPrice(len - 2, posState);
		}

		private uint Backward(out uint backRes, uint cur)
		{
			_optimumEndIndex = cur;
			uint posPrev = _optimum[cur].PosPrev;
			uint backPrev = _optimum[cur].BackPrev;
			do
			{
				if (_optimum[cur].Prev1IsChar)
				{
					_optimum[posPrev].MakeAsChar();
					_optimum[posPrev].PosPrev = posPrev - 1;
					if (_optimum[cur].Prev2)
					{
						_optimum[posPrev - 1].Prev1IsChar = false;
						_optimum[posPrev - 1].PosPrev = _optimum[cur].PosPrev2;
						_optimum[posPrev - 1].BackPrev = _optimum[cur].BackPrev2;
					}
				}
				uint num = posPrev;
				uint backPrev2 = backPrev;
				backPrev = _optimum[num].BackPrev;
				posPrev = _optimum[num].PosPrev;
				_optimum[num].BackPrev = backPrev2;
				_optimum[num].PosPrev = cur;
				cur = num;
			}
			while (cur != 0);
			backRes = _optimum[0].BackPrev;
			_optimumCurrentIndex = _optimum[0].PosPrev;
			return _optimumCurrentIndex;
		}

		private uint GetOptimum(uint position, out uint backRes)
		{
			if (_optimumEndIndex != _optimumCurrentIndex)
			{
				uint result = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex;
				backRes = _optimum[_optimumCurrentIndex].BackPrev;
				_optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev;
				return result;
			}
			_optimumCurrentIndex = (_optimumEndIndex = 0u);
			uint lenRes;
			uint numDistancePairs;
			if (!_longestMatchWasFound)
			{
				ReadMatchDistances(out lenRes, out numDistancePairs);
			}
			else
			{
				lenRes = _longestMatchLength;
				numDistancePairs = _numDistancePairs;
				_longestMatchWasFound = false;
			}
			uint num = _matchFinder.GetNumAvailableBytes() + 1;
			if (num < 2)
			{
				backRes = uint.MaxValue;
				return 1u;
			}
			if (num > 273)
			{
				num = 273u;
			}
			uint num2 = 0u;
			for (uint num3 = 0u; num3 < 4; num3++)
			{
				reps[num3] = _repDistances[num3];
				repLens[num3] = _matchFinder.GetMatchLen(-1, reps[num3], 273u);
				if (repLens[num3] > repLens[num2])
				{
					num2 = num3;
				}
			}
			if (repLens[num2] >= _numFastBytes)
			{
				backRes = num2;
				uint num4 = repLens[num2];
				MovePos(num4 - 1);
				return num4;
			}
			if (lenRes >= _numFastBytes)
			{
				backRes = _matchDistances[numDistancePairs - 1] + 4;
				MovePos(lenRes - 1);
				return lenRes;
			}
			byte indexByte = _matchFinder.GetIndexByte(-1);
			byte indexByte2 = _matchFinder.GetIndexByte((int)(0 - _repDistances[0] - 1 - 1));
			if (lenRes < 2 && indexByte != indexByte2 && repLens[num2] < 2)
			{
				backRes = uint.MaxValue;
				return 1u;
			}
			_optimum[0].State = _state;
			uint num5 = position & _posStateMask;
			_optimum[1].Price = _isMatch[(_state.Index << 4) + num5].GetPrice0() + _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), indexByte2, indexByte);
			_optimum[1].MakeAsChar();
			uint price = _isMatch[(_state.Index << 4) + num5].GetPrice1();
			uint num6 = price + _isRep[_state.Index].GetPrice1();
			if (indexByte2 == indexByte)
			{
				uint num7 = num6 + GetRepLen1Price(_state, num5);
				if (num7 < _optimum[1].Price)
				{
					_optimum[1].Price = num7;
					_optimum[1].MakeAsShortRep();
				}
			}
			uint num8 = ((lenRes >= repLens[num2]) ? lenRes : repLens[num2]);
			if (num8 < 2)
			{
				backRes = _optimum[1].BackPrev;
				return 1u;
			}
			_optimum[1].PosPrev = 0u;
			_optimum[0].Backs0 = reps[0];
			_optimum[0].Backs1 = reps[1];
			_optimum[0].Backs2 = reps[2];
			_optimum[0].Backs3 = reps[3];
			uint num9 = num8;
			do
			{
				_optimum[num9--].Price = 268435455u;
			}
			while (num9 >= 2);
			for (uint num3 = 0u; num3 < 4; num3++)
			{
				uint num10 = repLens[num3];
				if (num10 < 2)
				{
					continue;
				}
				uint num11 = num6 + GetPureRepPrice(num3, _state, num5);
				do
				{
					uint num12 = num11 + _repMatchLenEncoder.GetPrice(num10 - 2, num5);
					Optimal optimal = _optimum[num10];
					if (num12 < optimal.Price)
					{
						optimal.Price = num12;
						optimal.PosPrev = 0u;
						optimal.BackPrev = num3;
						optimal.Prev1IsChar = false;
					}
				}
				while (--num10 >= 2);
			}
			uint num13 = price + _isRep[_state.Index].GetPrice0();
			num9 = ((repLens[0] >= 2) ? (repLens[0] + 1) : 2u);
			if (num9 <= lenRes)
			{
				uint num14;
				for (num14 = 0u; num9 > _matchDistances[num14]; num14 += 2)
				{
				}
				while (true)
				{
					uint num15 = _matchDistances[num14 + 1];
					uint num16 = num13 + GetPosLenPrice(num15, num9, num5);
					Optimal optimal2 = _optimum[num9];
					if (num16 < optimal2.Price)
					{
						optimal2.Price = num16;
						optimal2.PosPrev = 0u;
						optimal2.BackPrev = num15 + 4;
						optimal2.Prev1IsChar = false;
					}
					if (num9 == _matchDistances[num14])
					{
						num14 += 2;
						if (num14 == numDistancePairs)
						{
							break;
						}
					}
					num9++;
				}
			}
			uint num17 = 0u;
			uint lenRes2;
			while (true)
			{
				num17++;
				if (num17 == num8)
				{
					return Backward(out backRes, num17);
				}
				ReadMatchDistances(out lenRes2, out numDistancePairs);
				if (lenRes2 >= _numFastBytes)
				{
					break;
				}
				position++;
				uint num18 = _optimum[num17].PosPrev;
				Base.State state;
				if (_optimum[num17].Prev1IsChar)
				{
					num18--;
					if (_optimum[num17].Prev2)
					{
						state = _optimum[_optimum[num17].PosPrev2].State;
						if (_optimum[num17].BackPrev2 < 4)
						{
							state.UpdateRep();
						}
						else
						{
							state.UpdateMatch();
						}
					}
					else
					{
						state = _optimum[num18].State;
					}
					state.UpdateChar();
				}
				else
				{
					state = _optimum[num18].State;
				}
				if (num18 == num17 - 1)
				{
					if (_optimum[num17].IsShortRep())
					{
						state.UpdateShortRep();
					}
					else
					{
						state.UpdateChar();
					}
				}
				else
				{
					uint num19;
					if (_optimum[num17].Prev1IsChar && _optimum[num17].Prev2)
					{
						num18 = _optimum[num17].PosPrev2;
						num19 = _optimum[num17].BackPrev2;
						state.UpdateRep();
					}
					else
					{
						num19 = _optimum[num17].BackPrev;
						if (num19 < 4)
						{
							state.UpdateRep();
						}
						else
						{
							state.UpdateMatch();
						}
					}
					Optimal optimal3 = _optimum[num18];
					switch (num19)
					{
					case 0u:
						reps[0] = optimal3.Backs0;
						reps[1] = optimal3.Backs1;
						reps[2] = optimal3.Backs2;
						reps[3] = optimal3.Backs3;
						break;
					case 1u:
						reps[0] = optimal3.Backs1;
						reps[1] = optimal3.Backs0;
						reps[2] = optimal3.Backs2;
						reps[3] = optimal3.Backs3;
						break;
					case 2u:
						reps[0] = optimal3.Backs2;
						reps[1] = optimal3.Backs0;
						reps[2] = optimal3.Backs1;
						reps[3] = optimal3.Backs3;
						break;
					case 3u:
						reps[0] = optimal3.Backs3;
						reps[1] = optimal3.Backs0;
						reps[2] = optimal3.Backs1;
						reps[3] = optimal3.Backs2;
						break;
					default:
						reps[0] = num19 - 4;
						reps[1] = optimal3.Backs0;
						reps[2] = optimal3.Backs1;
						reps[3] = optimal3.Backs2;
						break;
					}
				}
				_optimum[num17].State = state;
				_optimum[num17].Backs0 = reps[0];
				_optimum[num17].Backs1 = reps[1];
				_optimum[num17].Backs2 = reps[2];
				_optimum[num17].Backs3 = reps[3];
				uint price2 = _optimum[num17].Price;
				indexByte = _matchFinder.GetIndexByte(-1);
				indexByte2 = _matchFinder.GetIndexByte((int)(0 - reps[0] - 1 - 1));
				num5 = position & _posStateMask;
				uint num20 = price2 + _isMatch[(state.Index << 4) + num5].GetPrice0() + _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(-2)).GetPrice(!state.IsCharState(), indexByte2, indexByte);
				Optimal optimal4 = _optimum[num17 + 1];
				bool flag = false;
				if (num20 < optimal4.Price)
				{
					optimal4.Price = num20;
					optimal4.PosPrev = num17;
					optimal4.MakeAsChar();
					flag = true;
				}
				price = price2 + _isMatch[(state.Index << 4) + num5].GetPrice1();
				num6 = price + _isRep[state.Index].GetPrice1();
				if (indexByte2 == indexByte && (optimal4.PosPrev >= num17 || optimal4.BackPrev != 0))
				{
					uint num21 = num6 + GetRepLen1Price(state, num5);
					if (num21 <= optimal4.Price)
					{
						optimal4.Price = num21;
						optimal4.PosPrev = num17;
						optimal4.MakeAsShortRep();
						flag = true;
					}
				}
				uint val = _matchFinder.GetNumAvailableBytes() + 1;
				val = Math.Min(4095 - num17, val);
				num = val;
				if (num < 2)
				{
					continue;
				}
				if (num > _numFastBytes)
				{
					num = _numFastBytes;
				}
				if (!flag && indexByte2 != indexByte)
				{
					uint limit = Math.Min(val - 1, _numFastBytes);
					uint matchLen = _matchFinder.GetMatchLen(0, reps[0], limit);
					if (matchLen >= 2)
					{
						Base.State state2 = state;
						state2.UpdateChar();
						uint num22 = (position + 1) & _posStateMask;
						uint num23 = num20 + _isMatch[(state2.Index << 4) + num22].GetPrice1() + _isRep[state2.Index].GetPrice1();
						uint num24 = num17 + 1 + matchLen;
						while (num8 < num24)
						{
							_optimum[++num8].Price = 268435455u;
						}
						uint num25 = num23 + GetRepPrice(0u, matchLen, state2, num22);
						Optimal optimal5 = _optimum[num24];
						if (num25 < optimal5.Price)
						{
							optimal5.Price = num25;
							optimal5.PosPrev = num17 + 1;
							optimal5.BackPrev = 0u;
							optimal5.Prev1IsChar = true;
							optimal5.Prev2 = false;
						}
					}
				}
				uint num26 = 2u;
				for (uint num27 = 0u; num27 < 4; num27++)
				{
					uint num28 = _matchFinder.GetMatchLen(-1, reps[num27], num);
					if (num28 < 2)
					{
						continue;
					}
					uint num29 = num28;
					while (true)
					{
						if (num8 < num17 + num28)
						{
							_optimum[++num8].Price = 268435455u;
							continue;
						}
						uint num30 = num6 + GetRepPrice(num27, num28, state, num5);
						Optimal optimal6 = _optimum[num17 + num28];
						if (num30 < optimal6.Price)
						{
							optimal6.Price = num30;
							optimal6.PosPrev = num17;
							optimal6.BackPrev = num27;
							optimal6.Prev1IsChar = false;
						}
						if (--num28 < 2)
						{
							break;
						}
					}
					num28 = num29;
					if (num27 == 0)
					{
						num26 = num28 + 1;
					}
					if (num28 >= val)
					{
						continue;
					}
					uint limit2 = Math.Min(val - 1 - num28, _numFastBytes);
					uint matchLen2 = _matchFinder.GetMatchLen((int)num28, reps[num27], limit2);
					if (matchLen2 >= 2)
					{
						Base.State state3 = state;
						state3.UpdateRep();
						uint num31 = (position + num28) & _posStateMask;
						uint num32 = num6 + GetRepPrice(num27, num28, state, num5) + _isMatch[(state3.Index << 4) + num31].GetPrice0() + _literalEncoder.GetSubCoder(position + num28, _matchFinder.GetIndexByte((int)(num28 - 1 - 1))).GetPrice(matchMode: true, _matchFinder.GetIndexByte((int)(num28 - 1 - (reps[num27] + 1))), _matchFinder.GetIndexByte((int)(num28 - 1)));
						state3.UpdateChar();
						num31 = (position + num28 + 1) & _posStateMask;
						uint num33 = num32 + _isMatch[(state3.Index << 4) + num31].GetPrice1() + _isRep[state3.Index].GetPrice1();
						uint num34 = num28 + 1 + matchLen2;
						while (num8 < num17 + num34)
						{
							_optimum[++num8].Price = 268435455u;
						}
						uint num35 = num33 + GetRepPrice(0u, matchLen2, state3, num31);
						Optimal optimal7 = _optimum[num17 + num34];
						if (num35 < optimal7.Price)
						{
							optimal7.Price = num35;
							optimal7.PosPrev = num17 + num28 + 1;
							optimal7.BackPrev = 0u;
							optimal7.Prev1IsChar = true;
							optimal7.Prev2 = true;
							optimal7.PosPrev2 = num17;
							optimal7.BackPrev2 = num27;
						}
					}
				}
				if (lenRes2 > num)
				{
					lenRes2 = num;
					for (numDistancePairs = 0u; lenRes2 > _matchDistances[numDistancePairs]; numDistancePairs += 2)
					{
					}
					_matchDistances[numDistancePairs] = lenRes2;
					numDistancePairs += 2;
				}
				if (lenRes2 < num26)
				{
					continue;
				}
				num13 = price + _isRep[state.Index].GetPrice0();
				while (num8 < num17 + lenRes2)
				{
					_optimum[++num8].Price = 268435455u;
				}
				uint num36;
				for (num36 = 0u; num26 > _matchDistances[num36]; num36 += 2)
				{
				}
				uint num37 = num26;
				while (true)
				{
					uint num38 = _matchDistances[num36 + 1];
					uint num39 = num13 + GetPosLenPrice(num38, num37, num5);
					Optimal optimal8 = _optimum[num17 + num37];
					if (num39 < optimal8.Price)
					{
						optimal8.Price = num39;
						optimal8.PosPrev = num17;
						optimal8.BackPrev = num38 + 4;
						optimal8.Prev1IsChar = false;
					}
					if (num37 == _matchDistances[num36])
					{
						if (num37 < val)
						{
							uint limit3 = Math.Min(val - 1 - num37, _numFastBytes);
							uint matchLen3 = _matchFinder.GetMatchLen((int)num37, num38, limit3);
							if (matchLen3 >= 2)
							{
								Base.State state4 = state;
								state4.UpdateMatch();
								uint num40 = (position + num37) & _posStateMask;
								uint num41 = num39 + _isMatch[(state4.Index << 4) + num40].GetPrice0() + _literalEncoder.GetSubCoder(position + num37, _matchFinder.GetIndexByte((int)(num37 - 1 - 1))).GetPrice(matchMode: true, _matchFinder.GetIndexByte((int)(num37 - (num38 + 1) - 1)), _matchFinder.GetIndexByte((int)(num37 - 1)));
								state4.UpdateChar();
								num40 = (position + num37 + 1) & _posStateMask;
								uint num42 = num41 + _isMatch[(state4.Index << 4) + num40].GetPrice1() + _isRep[state4.Index].GetPrice1();
								uint num43 = num37 + 1 + matchLen3;
								while (num8 < num17 + num43)
								{
									_optimum[++num8].Price = 268435455u;
								}
								num39 = num42 + GetRepPrice(0u, matchLen3, state4, num40);
								optimal8 = _optimum[num17 + num43];
								if (num39 < optimal8.Price)
								{
									optimal8.Price = num39;
									optimal8.PosPrev = num17 + num37 + 1;
									optimal8.BackPrev = 0u;
									optimal8.Prev1IsChar = true;
									optimal8.Prev2 = true;
									optimal8.PosPrev2 = num17;
									optimal8.BackPrev2 = num38 + 4;
								}
							}
						}
						num36 += 2;
						if (num36 == numDistancePairs)
						{
							break;
						}
					}
					num37++;
				}
			}
			_numDistancePairs = numDistancePairs;
			_longestMatchLength = lenRes2;
			_longestMatchWasFound = true;
			return Backward(out backRes, num17);
		}

		private bool ChangePair(uint smallDist, uint bigDist)
		{
			if (smallDist < 33554432)
			{
				return bigDist >= smallDist << 7;
			}
			return false;
		}

		private void WriteEndMarker(uint posState)
		{
			if (_writeEndMark)
			{
				_isMatch[(_state.Index << 4) + posState].Encode(_rangeEncoder, 1u);
				_isRep[_state.Index].Encode(_rangeEncoder, 0u);
				_state.UpdateMatch();
				uint num = 2u;
				_lenEncoder.Encode(_rangeEncoder, num - 2, posState);
				uint symbol = 63u;
				uint lenToPosState = Base.GetLenToPosState(num);
				_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, symbol);
				int num2 = 30;
				uint num3 = (uint)((1 << num2) - 1);
				_rangeEncoder.EncodeDirectBits(num3 >> 4, num2 - 4);
				_posAlignEncoder.ReverseEncode(_rangeEncoder, num3 & 0xFu);
			}
		}

		private void Flush(uint nowPos)
		{
			ReleaseMFStream();
			WriteEndMarker(nowPos & _posStateMask);
			_rangeEncoder.FlushData();
			_rangeEncoder.FlushStream();
		}

		public void CodeOneBlock(out long inSize, out long outSize, out bool finished)
		{
			inSize = 0L;
			outSize = 0L;
			finished = true;
			if (_inStream != null)
			{
				_matchFinder.SetStream(_inStream);
				_matchFinder.Init();
				_needReleaseMFStream = true;
				_inStream = null;
				if (_trainSize != 0)
				{
					_matchFinder.Skip(_trainSize);
				}
			}
			if (_finished)
			{
				return;
			}
			_finished = true;
			long num = nowPos64;
			if (nowPos64 == 0L)
			{
				if (_matchFinder.GetNumAvailableBytes() == 0)
				{
					Flush((uint)nowPos64);
					return;
				}
				ReadMatchDistances(out var _, out var _);
				uint num2 = (uint)(int)nowPos64 & _posStateMask;
				_isMatch[(_state.Index << 4) + num2].Encode(_rangeEncoder, 0u);
				_state.UpdateChar();
				byte indexByte = _matchFinder.GetIndexByte((int)(0 - _additionalOffset));
				_literalEncoder.GetSubCoder((uint)nowPos64, _previousByte).Encode(_rangeEncoder, indexByte);
				_previousByte = indexByte;
				_additionalOffset--;
				nowPos64++;
			}
			if (_matchFinder.GetNumAvailableBytes() == 0)
			{
				Flush((uint)nowPos64);
				return;
			}
			while (true)
			{
				uint backRes;
				uint optimum = GetOptimum((uint)nowPos64, out backRes);
				uint num3 = (uint)(int)nowPos64 & _posStateMask;
				uint num4 = (_state.Index << 4) + num3;
				if (optimum == 1 && backRes == uint.MaxValue)
				{
					_isMatch[num4].Encode(_rangeEncoder, 0u);
					byte indexByte2 = _matchFinder.GetIndexByte((int)(0 - _additionalOffset));
					LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((uint)nowPos64, _previousByte);
					if (!_state.IsCharState())
					{
						byte indexByte3 = _matchFinder.GetIndexByte((int)(0 - _repDistances[0] - 1 - _additionalOffset));
						subCoder.EncodeMatched(_rangeEncoder, indexByte3, indexByte2);
					}
					else
					{
						subCoder.Encode(_rangeEncoder, indexByte2);
					}
					_previousByte = indexByte2;
					_state.UpdateChar();
				}
				else
				{
					_isMatch[num4].Encode(_rangeEncoder, 1u);
					if (backRes < 4)
					{
						_isRep[_state.Index].Encode(_rangeEncoder, 1u);
						if (backRes == 0)
						{
							_isRepG0[_state.Index].Encode(_rangeEncoder, 0u);
							if (optimum == 1)
							{
								_isRep0Long[num4].Encode(_rangeEncoder, 0u);
							}
							else
							{
								_isRep0Long[num4].Encode(_rangeEncoder, 1u);
							}
						}
						else
						{
							_isRepG0[_state.Index].Encode(_rangeEncoder, 1u);
							if (backRes == 1)
							{
								_isRepG1[_state.Index].Encode(_rangeEncoder, 0u);
							}
							else
							{
								_isRepG1[_state.Index].Encode(_rangeEncoder, 1u);
								_isRepG2[_state.Index].Encode(_rangeEncoder, backRes - 2);
							}
						}
						if (optimum == 1)
						{
							_state.UpdateShortRep();
						}
						else
						{
							_repMatchLenEncoder.Encode(_rangeEncoder, optimum - 2, num3);
							_state.UpdateRep();
						}
						uint num5 = _repDistances[backRes];
						if (backRes != 0)
						{
							for (uint num6 = backRes; num6 >= 1; num6--)
							{
								_repDistances[num6] = _repDistances[num6 - 1];
							}
							_repDistances[0] = num5;
						}
					}
					else
					{
						_isRep[_state.Index].Encode(_rangeEncoder, 0u);
						_state.UpdateMatch();
						_lenEncoder.Encode(_rangeEncoder, optimum - 2, num3);
						backRes -= 4;
						uint posSlot = GetPosSlot(backRes);
						uint lenToPosState = Base.GetLenToPosState(optimum);
						_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
						if (posSlot >= 4)
						{
							int num7 = (int)((posSlot >> 1) - 1);
							uint num8 = (2 | (posSlot & 1)) << num7;
							uint num9 = backRes - num8;
							if (posSlot < 14)
							{
								BitTreeEncoder.ReverseEncode(_posEncoders, num8 - posSlot - 1, _rangeEncoder, num7, num9);
							}
							else
							{
								_rangeEncoder.EncodeDirectBits(num9 >> 4, num7 - 4);
								_posAlignEncoder.ReverseEncode(_rangeEncoder, num9 & 0xFu);
								_alignPriceCount++;
							}
						}
						uint num10 = backRes;
						for (uint num11 = 3u; num11 >= 1; num11--)
						{
							_repDistances[num11] = _repDistances[num11 - 1];
						}
						_repDistances[0] = num10;
						_matchPriceCount++;
					}
					_previousByte = _matchFinder.GetIndexByte((int)(optimum - 1 - _additionalOffset));
				}
				_additionalOffset -= optimum;
				nowPos64 += optimum;
				if (_additionalOffset == 0)
				{
					if (_matchPriceCount >= 128)
					{
						FillDistancesPrices();
					}
					if (_alignPriceCount >= 16)
					{
						FillAlignPrices();
					}
					inSize = nowPos64;
					outSize = _rangeEncoder.GetProcessedSizeAdd();
					if (_matchFinder.GetNumAvailableBytes() == 0)
					{
						Flush((uint)nowPos64);
						return;
					}
					if (nowPos64 - num >= 4096)
					{
						break;
					}
				}
			}
			_finished = false;
			finished = false;
		}

		private void ReleaseMFStream()
		{
			if (_matchFinder != null && _needReleaseMFStream)
			{
				_matchFinder.ReleaseStream();
				_needReleaseMFStream = false;
			}
		}

		private void SetOutStream(Stream outStream)
		{
			_rangeEncoder.SetStream(outStream);
		}

		private void ReleaseOutStream()
		{
			_rangeEncoder.ReleaseStream();
		}

		private void ReleaseStreams()
		{
			ReleaseMFStream();
			ReleaseOutStream();
		}

		private void SetStreams(Stream inStream, Stream outStream, long inSize, long outSize)
		{
			_inStream = inStream;
			_finished = false;
			Create();
			SetOutStream(outStream);
			Init();
			FillDistancesPrices();
			FillAlignPrices();
			_lenEncoder.SetTableSize(_numFastBytes + 1 - 2);
			_lenEncoder.UpdateTables((uint)(1 << _posStateBits));
			_repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - 2);
			_repMatchLenEncoder.UpdateTables((uint)(1 << _posStateBits));
			nowPos64 = 0L;
		}

		public void Code(Stream inStream, Stream outStream, long inSize, long outSize, ICodeProgress progress)
		{
			_needReleaseMFStream = false;
			try
			{
				SetStreams(inStream, outStream, inSize, outSize);
				while (true)
				{
					CodeOneBlock(out var inSize2, out var outSize2, out var finished);
					if (finished)
					{
						break;
					}
					progress?.SetProgress(inSize2, outSize2);
				}
			}
			finally
			{
				ReleaseStreams();
			}
		}

		public void WriteCoderProperties(Stream outStream)
		{
			properties[0] = (byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits);
			for (int i = 0; i < 4; i++)
			{
				properties[1 + i] = (byte)((_dictionarySize >> 8 * i) & 0xFFu);
			}
			outStream.Write(properties, 0, 5);
		}

		private void FillDistancesPrices()
		{
			for (uint num = 4u; num < 128; num++)
			{
				uint posSlot = GetPosSlot(num);
				int num2 = (int)((posSlot >> 1) - 1);
				uint num3 = (2 | (posSlot & 1)) << num2;
				tempPrices[num] = BitTreeEncoder.ReverseGetPrice(_posEncoders, num3 - posSlot - 1, num2, num - num3);
			}
			for (uint num4 = 0u; num4 < 4; num4++)
			{
				BitTreeEncoder bitTreeEncoder = _posSlotEncoder[num4];
				uint num5 = num4 << 6;
				for (uint num6 = 0u; num6 < _distTableSize; num6++)
				{
					_posSlotPrices[num5 + num6] = bitTreeEncoder.GetPrice(num6);
				}
				for (uint num6 = 14u; num6 < _distTableSize; num6++)
				{
					_posSlotPrices[num5 + num6] += (num6 >> 1) - 1 - 4 << 6;
				}
				uint num7 = num4 * 128;
				uint num8;
				for (num8 = 0u; num8 < 4; num8++)
				{
					_distancesPrices[num7 + num8] = _posSlotPrices[num5 + num8];
				}
				for (; num8 < 128; num8++)
				{
					_distancesPrices[num7 + num8] = _posSlotPrices[num5 + GetPosSlot(num8)] + tempPrices[num8];
				}
			}
			_matchPriceCount = 0u;
		}

		private void FillAlignPrices()
		{
			for (uint num = 0u; num < 16; num++)
			{
				_alignPrices[num] = _posAlignEncoder.ReverseGetPrice(num);
			}
			_alignPriceCount = 0u;
		}

		private static int FindMatchFinder(string s)
		{
			for (int i = 0; i < kMatchFinderIDs.Length; i++)
			{
				if (s == kMatchFinderIDs[i])
				{
					return i;
				}
			}
			return -1;
		}

		public void SetCoderProperties(CoderPropID[] propIDs, object[] properties)
		{
			for (uint num = 0u; num < properties.Length; num++)
			{
				object obj = properties[num];
				switch (propIDs[num])
				{
				case CoderPropID.NumFastBytes:
					if (!(obj is int num2))
					{
						throw new InvalidParamException();
					}
					if (num2 < 5 || (long)num2 > 273L)
					{
						throw new InvalidParamException();
					}
					_numFastBytes = (uint)num2;
					break;
				case CoderPropID.MatchFinder:
				{
					if (!(obj is string))
					{
						throw new InvalidParamException();
					}
					EMatchFinderType matchFinderType = _matchFinderType;
					int num6 = FindMatchFinder(((string)obj).ToUpper());
					if (num6 < 0)
					{
						throw new InvalidParamException();
					}
					_matchFinderType = (EMatchFinderType)num6;
					if (_matchFinder != null && matchFinderType != _matchFinderType)
					{
						_dictionarySizePrev = uint.MaxValue;
						_matchFinder = null;
					}
					break;
				}
				case CoderPropID.DictionarySize:
				{
					if (!(obj is int num7))
					{
						throw new InvalidParamException();
					}
					if ((long)num7 < 1L || (long)num7 > 1073741824L)
					{
						throw new InvalidParamException();
					}
					_dictionarySize = (uint)num7;
					int i;
					for (i = 0; (long)i < 30L && num7 > (uint)(1 << i); i++)
					{
					}
					_distTableSize = (uint)(i * 2);
					break;
				}
				case CoderPropID.PosStateBits:
					if (!(obj is int num3))
					{
						throw new InvalidParamException();
					}
					if (num3 < 0 || (long)num3 > 4L)
					{
						throw new InvalidParamException();
					}
					_posStateBits = num3;
					_posStateMask = (uint)((1 << _posStateBits) - 1);
					break;
				case CoderPropID.LitPosBits:
					if (!(obj is int num5))
					{
						throw new InvalidParamException();
					}
					if (num5 < 0 || (long)num5 > 4L)
					{
						throw new InvalidParamException();
					}
					_numLiteralPosStateBits = num5;
					break;
				case CoderPropID.LitContextBits:
					if (!(obj is int num4))
					{
						throw new InvalidParamException();
					}
					if (num4 < 0 || (long)num4 > 8L)
					{
						throw new InvalidParamException();
					}
					_numLiteralContextBits = num4;
					break;
				case CoderPropID.EndMarker:
					if (!(obj is bool))
					{
						throw new InvalidParamException();
					}
					SetWriteEndMarkerMode((bool)obj);
					break;
				default:
					throw new InvalidParamException();
				case CoderPropID.Algorithm:
					break;
				}
			}
		}

		public void SetTrainSize(uint trainSize)
		{
			_trainSize = trainSize;
		}
	}
	public static class SevenZipHelper
	{
		private static CoderPropID[] propIDs = new CoderPropID[8]
		{
			CoderPropID.DictionarySize,
			CoderPropID.PosStateBits,
			CoderPropID.LitContextBits,
			CoderPropID.LitPosBits,
			CoderPropID.Algorithm,
			CoderPropID.NumFastBytes,
			CoderPropID.MatchFinder,
			CoderPropID.EndMarker
		};

		private static object[] properties = new object[8] { 2097152, 2, 3, 0, 2, 32, "bt4", false };

		public static byte[] Compress(byte[] inputBytes, ICodeProgress progress = null)
		{
			MemoryStream inStream = new MemoryStream(inputBytes);
			MemoryStream memoryStream = new MemoryStream();
			Compress(inStream, memoryStream, progress);
			return memoryStream.ToArray();
		}

		public static void Compress(Stream inStream, Stream outStream, ICodeProgress progress = null)
		{
			Encoder encoder = new Encoder();
			encoder.SetCoderProperties(propIDs, properties);
			encoder.WriteCoderProperties(outStream);
			encoder.Code(inStream, outStream, -1L, -1L, progress);
		}

		public static byte[] Decompress(byte[] inputBytes)
		{
			MemoryStream memoryStream = new MemoryStream(inputBytes);
			Decoder decoder = new Decoder();
			memoryStream.Seek(0L, SeekOrigin.Begin);
			MemoryStream memoryStream2 = new MemoryStream();
			byte[] array = new byte[5];
			if (memoryStream.Read(array, 0, 5) != 5)
			{
				throw new Exception("input .lzma is too short");
			}
			long num = 0L;
			for (int i = 0; i < 8; i++)
			{
				int num2 = memoryStream.ReadByte();
				if (num2 < 0)
				{
					throw new Exception("Can't Read 1");
				}
				num |= (long)((ulong)(byte)num2 << 8 * i);
			}
			decoder.SetDecoderProperties(array);
			long inSize = memoryStream.Length - memoryStream.Position;
			decoder.Code(memoryStream, memoryStream2, inSize, num, null);
			return memoryStream2.ToArray();
		}

		public static MemoryStream StreamDecompress(MemoryStream newInStream)
		{
			Decoder decoder = new Decoder();
			newInStream.Seek(0L, SeekOrigin.Begin);
			MemoryStream memoryStream = new MemoryStream();
			byte[] array = new byte[5];
			if (newInStream.Read(array, 0, 5) != 5)
			{
				throw new Exception("input .lzma is too short");
			}
			long num = 0L;
			for (int i = 0; i < 8; i++)
			{
				int num2 = newInStream.ReadByte();
				if (num2 < 0)
				{
					throw new Exception("Can't Read 1");
				}
				num |= (long)((ulong)(byte)num2 << 8 * i);
			}
			decoder.SetDecoderProperties(array);
			long inSize = newInStream.Length - newInStream.Position;
			decoder.Code(newInStream, memoryStream, inSize, num, null);
			memoryStream.Position = 0L;
			return memoryStream;
		}

		public static MemoryStream StreamDecompress(MemoryStream newInStream, long outSize)
		{
			Decoder decoder = new Decoder();
			newInStream.Seek(0L, SeekOrigin.Begin);
			MemoryStream memoryStream = new MemoryStream();
			byte[] array = new byte[5];
			if (newInStream.Read(array, 0, 5) != 5)
			{
				throw new Exception("input .lzma is too short");
			}
			decoder.SetDecoderProperties(array);
			long inSize = newInStream.Length - newInStream.Position;
			decoder.Code(newInStream, memoryStream, inSize, outSize, null);
			memoryStream.Position = 0L;
			return memoryStream;
		}

		public static void StreamDecompress(Stream compressedStream, Stream decompressedStream, long compressedSize, long decompressedSize)
		{
			long position = compressedStream.Position;
			Decoder decoder = new Decoder();
			byte[] array = new byte[5];
			if (compressedStream.Read(array, 0, 5) != 5)
			{
				throw new Exception("input .lzma is too short");
			}
			decoder.SetDecoderProperties(array);
			decoder.Code(compressedStream, decompressedStream, compressedSize - 5, decompressedSize, null);
			compressedStream.Position = position + compressedSize;
		}
	}
}
namespace SevenZip.Buffer
{
	public class InBuffer
	{
		private byte[] m_Buffer;

		private uint m_Pos;

		private uint m_Limit;

		private uint m_BufferSize;

		private Stream m_Stream;

		private bool m_StreamWasExhausted;

		private ulong m_ProcessedSize;

		public InBuffer(uint bufferSize)
		{
			m_Buffer = new byte[bufferSize];
			m_BufferSize = bufferSize;
		}

		public void Init(Stream stream)
		{
			m_Stream = stream;
			m_ProcessedSize = 0uL;
			m_Limit = 0u;
			m_Pos = 0u;
			m_StreamWasExhausted = false;
		}

		public bool ReadBlock()
		{
			if (m_StreamWasExhausted)
			{
				return false;
			}
			m_ProcessedSize += m_Pos;
			int num = m_Stream.Read(m_Buffer, 0, (int)m_BufferSize);
			m_Pos = 0u;
			m_Limit = (uint)num;
			m_StreamWasExhausted = num == 0;
			return !m_StreamWasExhausted;
		}

		public void ReleaseStream()
		{
			m_Stream = null;
		}

		public bool ReadByte(byte b)
		{
			if (m_Pos >= m_Limit && !ReadBlock())
			{
				return false;
			}
			b = m_Buffer[m_Pos++];
			return true;
		}

		public byte ReadByte()
		{
			if (m_Pos >= m_Limit && !ReadBlock())
			{
				return byte.MaxValue;
			}
			return m_Buffer[m_Pos++];
		}

		public ulong GetProcessedSize()
		{
			return m_ProcessedSize + m_Pos;
		}
	}
	public class OutBuffer
	{
		private byte[] m_Buffer;

		private uint m_Pos;

		private uint m_BufferSize;

		private Stream m_Stream;

		private ulong m_ProcessedSize;

		public OutBuffer(uint bufferSize)
		{
			m_Buffer = new byte[bufferSize];
			m_BufferSize = bufferSize;
		}

		public void SetStream(Stream stream)
		{
			m_Stream = stream;
		}

		public void FlushStream()
		{
			m_Stream.Flush();
		}

		public void CloseStream()
		{
			m_Stream.Close();
		}

		public void ReleaseStream()
		{
			m_Stream = null;
		}

		public void Init()
		{
			m_ProcessedSize = 0uL;
			m_Pos = 0u;
		}

		public void WriteByte(byte b)
		{
			m_Buffer[m_Pos++] = b;
			if (m_Pos >= m_BufferSize)
			{
				FlushData();
			}
		}

		public void FlushData()
		{
			if (m_Pos != 0)
			{
				m_Stream.Write(m_Buffer, 0, (int)m_Pos);
				m_Pos = 0u;
			}
		}

		public ulong GetProcessedSize()
		{
			return m_ProcessedSize + m_Pos;
		}
	}
}
namespace SevenZip.CommandLineParser
{
	public enum SwitchType
	{
		Simple,
		PostMinus,
		LimitedPostString,
		UnLimitedPostString,
		PostChar
	}
	public class SwitchForm
	{
		public string IDString;

		public SwitchType Type;

		public bool Multi;

		public int MinLen;

		public int MaxLen;

		public string PostCharSet;

		public SwitchForm(string idString, SwitchType type, bool multi, int minLen, int maxLen, string postCharSet)
		{
			IDString = idString;
			Type = type;
			Multi = multi;
			MinLen = minLen;
			MaxLen = maxLen;
			PostCharSet = postCharSet;
		}

		public SwitchForm(string idString, SwitchType type, bool multi, int minLen)
			: this(idString, type, multi, minLen, 0, "")
		{
		}

		public SwitchForm(string idString, SwitchType type, bool multi)
			: this(idString, type, multi, 0)
		{
		}
	}
	public class SwitchResult
	{
		public bool ThereIs;

		public bool WithMinus;

		public ArrayList PostStrings = new ArrayList();

		public int PostCharIndex;

		public SwitchResult()
		{
			ThereIs = false;
		}
	}
	public class Parser
	{
		public ArrayList NonSwitchStrings = new ArrayList();

		private SwitchResult[] _switches;

		private const char kSwitchID1 = '-';

		private const char kSwitchID2 = '/';

		private const char kSwitchMinus = '-';

		private const string kStopSwitchParsing = "--";

		public SwitchResult this[int index] => _switches[index];

		public Parser(int numSwitches)
		{
			_switches = new SwitchResult[numSwitches];
			for (int i = 0; i < numSwitches; i++)
			{
				_switches[i] = new SwitchResult();
			}
		}

		private bool ParseString(string srcString, SwitchForm[] switchForms)
		{
			int length = srcString.Length;
			if (length == 0)
			{
				return false;
			}
			int num = 0;
			if (!IsItSwitchChar(srcString[num]))
			{
				return false;
			}
			while (num < length)
			{
				if (IsItSwitchChar(srcString[num]))
				{
					num++;
				}
				int num2 = 0;
				int num3 = -1;
				for (int i = 0; i < _switches.Length; i++)
				{
					int length2 = switchForms[i].IDString.Length;
					if (length2 > num3 && num + length2 <= length && string.Compare(switchForms[i].IDString, 0, srcString, num, length2, ignoreCase: true) == 0)
					{
						num2 = i;
						num3 = length2;
					}
				}
				if (num3 == -1)
				{
					throw new Exception("maxLen == kNoLen");
				}
				SwitchResult switchResult = _switches[num2];
				SwitchForm switchForm = switchForms[num2];
				if (!switchForm.Multi && switchResult.ThereIs)
				{
					throw new Exception("switch must be single");
				}
				switchResult.ThereIs = true;
				num += num3;
				int num4 = length - num;
				SwitchType type = switchForm.Type;
				switch (type)
				{
				case SwitchType.PostMinus:
					if (num4 == 0)
					{
						switchResult.WithMinus = false;
						break;
					}
					switchResult.WithMinus = srcString[num] == '-';
					if (switchResult.WithMinus)
					{
						num++;
					}
					break;
				case SwitchType.PostChar:
				{
					if (num4 < switchForm.MinLen)
					{
						throw new Exception("switch is not full");
					}
					string postCharSet = switchForm.PostCharSet;
					if (num4 == 0)
					{
						switchResult.PostCharIndex = -1;
						break;
					}
					int num6 = postCharSet.IndexOf(srcString[num]);
					if (num6 < 0)
					{
						switchResult.PostCharIndex = -1;
						break;
					}
					switchResult.PostCharIndex = num6;
					num++;
					break;
				}
				case SwitchType.LimitedPostString:
				case SwitchType.UnLimitedPostString:
				{
					int minLen = switchForm.MinLen;
					if (num4 < minLen)
					{
						throw new Exception("switch is not full");
					}
					if (type == SwitchType.UnLimitedPostString)
					{
						switchResult.PostStrings.Add(srcString.Substring(num));
						return true;
					}
					string text = srcString.Substring(num, minLen);
					num += minLen;
					int num5 = minLen;
					while (num5 < switchForm.MaxLen && num < length)
					{
						char c = srcString[num];
						if (IsItSwitchChar(c))
						{
							break;
						}
						text += c;
						num5++;
						num++;
					}
					switchResult.PostStrings.Add(text);
					break;
				}
				}
			}
			return true;
		}

		public void ParseStrings(SwitchForm[] switchForms, string[] commandStrings)
		{
			int num = commandStrings.Length;
			bool flag = false;
			for (int i = 0; i < num; i++)
			{
				string text = commandStrings[i];
				if (flag)
				{
					NonSwitchStrings.Add(text);
				}
				else if (text == "--")
				{
					flag = true;
				}
				else if (!ParseString(text, switchForms))
				{
					NonSwitchStrings.Add(text);
				}
			}
		}

		public static int ParseCommand(CommandForm[] commandForms, string commandString, out string postString)
		{
			for (int i = 0; i < commandForms.Length; i++)
			{
				string iDString = commandForms[i].IDString;
				if (commandForms[i].PostStringMode)
				{
					if (commandString.IndexOf(iDString) == 0)
					{
						postString = commandString.Substring(iDString.Length);
						return i;
					}
				}
				else if (commandString == iDString)
				{
					postString = "";
					return i;
				}
			}
			postString = "";
			return -1;
		}

		private static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms, string commandString, ArrayList indices)
		{
			indices.Clear();
			int num = 0;
			for (int i = 0; i < numForms; i++)
			{
				CommandSubCharsSet commandSubCharsSet = forms[i];
				int num2 = -1;
				int length = commandSubCharsSet.Chars.Length;
				for (int j = 0; j < length; j++)
				{
					char value = commandSubCharsSet.Chars[j];
					int num3 = commandString.IndexOf(value);
					if (num3 >= 0)
					{
						if (num2 >= 0)
						{
							return false;
						}
						if (commandString.IndexOf(value, num3 + 1) >= 0)
						{
							return false;
						}
						num2 = j;
						num++;
					}
				}
				if (num2 == -1 && !commandSubCharsSet.EmptyAllowed)
				{
					return false;
				}
				indices.Add(num2);
			}
			return num == commandString.Length;
		}

		private static bool IsItSwitchChar(char c)
		{
			if (c != '-')
			{
				return c == '/';
			}
			return true;
		}
	}
	public class CommandForm
	{
		public string IDString = "";

		public bool PostStringMode;

		public CommandForm(string idString, bool postStringMode)
		{
			IDString = idString;
			PostStringMode = postStringMode;
		}
	}
	internal class CommandSubCharsSet
	{
		public string Chars = "";

		public bool EmptyAllowed;
	}
}
namespace LZ4ps
{
	public static class LZ4Codec
	{
		private class LZ4HC_Data_Structure
		{
			public byte[] src;

			public int src_base;

			public int src_end;

			public int src_LASTLITERALS;

			public byte[] dst;

			public int dst_base;

			public int dst_len;

			public int dst_end;

			public int[] hashTable;

			public ushort[] chainTable;

			public int nextToUpdate;
		}

		private const int MEMORY_USAGE = 14;

		private const int NOTCOMPRESSIBLE_DETECTIONLEVEL = 6;

		private const int BLOCK_COPY_LIMIT = 16;

		private const int MINMATCH = 4;

		private const int SKIPSTRENGTH = 6;

		private const int COPYLENGTH = 8;

		private const int LASTLITERALS = 5;

		private const int MFLIMIT = 12;

		private const int MINLENGTH = 13;

		private const int MAXD_LOG = 16;

		private const int MAXD = 65536;

		private const int MAXD_MASK = 65535;

		private const int MAX_DISTANCE = 65535;

		private const int ML_BITS = 4;

		private const int ML_MASK = 15;

		private const int RUN_BITS = 4;

		private const int RUN_MASK = 15;

		private const int STEPSIZE_64 = 8;

		private const int STEPSIZE_32 = 4;

		private const int LZ4_64KLIMIT = 65547;

		private const int HASH_LOG = 12;

		private const int HASH_TABLESIZE = 4096;

		private const int HASH_ADJUST = 20;

		private const int HASH64K_LOG = 13;

		private const int HASH64K_TABLESIZE = 8192;

		private const int HASH64K_ADJUST = 19;

		private const int HASHHC_LOG = 15;

		private const int HASHHC_TABLESIZE = 32768;

		private const int HASHHC_ADJUST = 17;

		private static readonly int[] DECODER_TABLE_32 = new int[8] { 0, 3, 2, 3, 0, 0, 0, 0 };

		private static readonly int[] DECODER_TABLE_64 = new int[8] { 0, 0, 0, -1, 0, 1, 2, 3 };

		private static readonly int[] DEBRUIJN_TABLE_32 = new int[32]
		{
			0, 0, 3, 0, 3, 1, 3, 0, 3, 2,
			2, 1, 3, 2, 0, 1, 3, 3, 1, 2,
			2, 2, 2, 0, 3, 1, 2, 0, 1, 0,
			1, 1
		};

		private static readonly int[] DEBRUIJN_TABLE_64 = new int[64]
		{
			0, 0, 0, 0, 0, 1, 1, 2, 0, 3,
			1, 3, 1, 4, 2, 7, 0, 2, 3, 6,
			1, 5, 3, 5, 1, 3, 4, 4, 2, 5,
			6, 7, 7, 0, 1, 2, 3, 3, 4, 6,
			2, 6, 5, 5, 3, 4, 5, 6, 7, 1,
			2, 4, 6, 4, 4, 5, 7, 2, 6, 5,
			7, 6, 7, 7
		};

		private const int MAX_NB_ATTEMPTS = 256;

		private const int OPTIMAL_ML = 18;

		public static int MaximumOutputLength(int inputLength)
		{
			return inputLength + inputLength / 255 + 16;
		}

		internal static void CheckArguments(byte[] input, int inputOffset, ref int inputLength, byte[] output, int outputOffset, ref int outputLength)
		{
			if (inputLength < 0)
			{
				inputLength = input.Length - inputOffset;
			}
			if (inputLength == 0)
			{
				outputLength = 0;
				return;
			}
			if (input == null)
			{
				throw new ArgumentNullException("input");
			}
			if (inputOffset < 0 || inputOffset + inputLength > input.Length)
			{
				throw new ArgumentException("inputOffset and inputLength are invalid for given input");
			}
			if (outputLength < 0)
			{
				outputLength = output.Length - outputOffset;
			}
			if (output == null)
			{
				throw new ArgumentNullException("output");
			}
			if (outputOffset >= 0 && outputOffset + outputLength <= output.Length)
			{
				return;
			}
			throw new ArgumentException("outputOffset and outputLength are invalid for given output");
		}

		[Conditional("DEBUG")]
		private static void Assert(bool condition, string errorMessage)
		{
			if (!condition)
			{
				throw new ArgumentException(errorMessage);
			}
		}

		internal static void Poke2(byte[] buffer, int offset, ushort value)
		{
			buffer[offset] = (byte)value;
			buffer[offset + 1] = (byte)(value >> 8);
		}

		internal static ushort Peek2(byte[] buffer, int offset)
		{
			return (ushort)(buffer[offset] | (buffer[offset + 1] << 8));
		}

		internal static uint Peek4(byte[] buffer, int offset)
		{
			return (uint)(buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24));
		}

		private static uint Xor4(byte[] buffer, int offset1, int offset2)
		{
			int num = buffer[offset1] | (buffer[offset1 + 1] << 8) | (buffer[offset1 + 2] << 16) | (buffer[offset1 + 3] << 24);
			uint num2 = (uint)(buffer[offset2] | (buffer[offset2 + 1] << 8) | (buffer[offset2 + 2] << 16) | (buffer[offset2 + 3] << 24));
			return (uint)num ^ num2;
		}

		private static ulong Xor8(byte[] buffer, int offset1, int offset2)
		{
			ulong num = buffer[offset1] | ((ulong)buffer[offset1 + 1] << 8) | ((ulong)buffer[offset1 + 2] << 16) | ((ulong)buffer[offset1 + 3] << 24) | ((ulong)buffer[offset1 + 4] << 32) | ((ulong)buffer[offset1 + 5] << 40) | ((ulong)buffer[offset1 + 6] << 48) | ((ulong)buffer[offset1 + 7] << 56);
			ulong num2 = buffer[offset2] | ((ulong)buffer[offset2 + 1] << 8) | ((ulong)buffer[offset2 + 2] << 16) | ((ulong)buffer[offset2 + 3] << 24) | ((ulong)buffer[offset2 + 4] << 32) | ((ulong)buffer[offset2 + 5] << 40) | ((ulong)buffer[offset2 + 6] << 48) | ((ulong)buffer[offset2 + 7] << 56);
			return num ^ num2;
		}

		private static bool Equal2(byte[] buffer, int offset1, int offset2)
		{
			if (buffer[offset1] != buffer[offset2])
			{
				return false;
			}
			return buffer[offset1 + 1] == buffer[offset2 + 1];
		}

		private static bool Equal4(byte[] buffer, int offset1, int offset2)
		{
			if (buffer[offset1] != buffer[offset2])
			{
				return false;
			}
			if (buffer[offset1 + 1] != buffer[offset2 + 1])
			{
				return false;
			}
			if (buffer[offset1 + 2] != buffer[offset2 + 2])
			{
				return false;
			}
			return buffer[offset1 + 3] == buffer[offset2 + 3];
		}

		private static void Copy4(byte[] buf, int src, int dst)
		{
			buf[dst + 3] = buf[src + 3];
			buf[dst + 2] = buf[src + 2];
			buf[dst + 1] = buf[src + 1];
			buf[dst] = buf[src];
		}

		private static void Copy8(byte[] buf, int src, int dst)
		{
			buf[dst + 7] = buf[src + 7];
			buf[dst + 6] = buf[src + 6];
			buf[dst + 5] = buf[src + 5];
			buf[dst + 4] = buf[src + 4];
			buf[dst + 3] = buf[src + 3];
			buf[dst + 2] = buf[src + 2];
			buf[dst + 1] = buf[src + 1];
			buf[dst] = buf[src];
		}

		private static void BlockCopy(byte[] src, int src_0, byte[] dst, int dst_0, int len)
		{
			if (len >= 16)
			{
				Buffer.BlockCopy(src, src_0, dst, dst_0, len);
				return;
			}
			while (len >= 8)
			{
				dst[dst_0] = src[src_0];
				dst[dst_0 + 1] = src[src_0 + 1];
				dst[dst_0 + 2] = src[src_0 + 2];
				dst[dst_0 + 3] = src[src_0 + 3];
				dst[dst_0 + 4] = src[src_0 + 4];
				dst[dst_0 + 5] = src[src_0 + 5];
				dst[dst_0 + 6] = src[src_0 + 6];
				dst[dst_0 + 7] = src[src_0 + 7];
				len -= 8;
				src_0 += 8;
				dst_0 += 8;
			}
			while (len >= 4)
			{
				dst[dst_0] = src[src_0];
				dst[dst_0 + 1] = src[src_0 + 1];
				dst[dst_0 + 2] = src[src_0 + 2];
				dst[dst_0 + 3] = src[src_0 + 3];
				len -= 4;
				src_0 += 4;
				dst_0 += 4;
			}
			while (len-- > 0)
			{
				dst[dst_0++] = src[src_0++];
			}
		}

		private static int WildCopy(byte[] src, int src_0, byte[] dst, int dst_0, int dst_end)
		{
			int num = dst_end - dst_0;
			if (num >= 16)
			{
				Buffer.BlockCopy(src, src_0, dst, dst_0, num);
			}
			else
			{
				while (num >= 4)
				{
					dst[dst_0] = src[src_0];
					dst[dst_0 + 1] = src[src_0 + 1];
					dst[dst_0 + 2] = src[src_0 + 2];
					dst[dst_0 + 3] = src[src_0 + 3];
					num -= 4;
					src_0 += 4;
					dst_0 += 4;
				}
				while (num-- > 0)
				{
					dst[dst_0++] = src[src_0++];
				}
			}
			return num;
		}

		private static int SecureCopy(byte[] buffer, int src, int dst, int dst_end)
		{
			int num = dst - src;
			int num2 = dst_end - dst;
			int num3 = num2;
			if (num >= 16)
			{
				if (num >= num2)
				{
					Buffer.BlockCopy(buffer, src, buffer, dst, num2);
					return num2;
				}
				do
				{
					Buffer.BlockCopy(buffer, src, buffer, dst, num);
					src += num;
					dst += num;
					num3 -= num;
				}
				while (num3 >= num);
			}
			while (num3 >= 4)
			{
				buffer[dst] = buffer[src];
				buffer[dst + 1] = buffer[src + 1];
				buffer[dst + 2] = buffer[src + 2];
				buffer[dst + 3] = buffer[src + 3];
				dst += 4;
				src += 4;
				num3 -= 4;
			}
			while (num3-- > 0)
			{
				buffer[dst++] = buffer[src++];
			}
			return num2;
		}

		public static int Encode32(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int outputLength)
		{
			CheckArguments(input, inputOffset, ref inputLength, output, outputOffset, ref outputLength);
			if (outputLength == 0)
			{
				return 0;
			}
			if (inputLength < 65547)
			{
				return LZ4_compress64kCtx_safe32(new ushort[8192], input, output, inputOffset, outputOffset, inputLength, outputLength);
			}
			return LZ4_compressCtx_safe32(new int[4096], input, output, inputOffset, outputOffset, inputLength, outputLength);
		}

		public static byte[] Encode32(byte[] input, int inputOffset, int inputLength)
		{
			if (inputLength < 0)
			{
				inputLength = input.Length - inputOffset;
			}
			if (input == null)
			{
				throw new ArgumentNullException("input");
			}
			if (inputOffset < 0 || inputOffset + inputLength > input.Length)
			{
				throw new ArgumentException("inputOffset and inputLength are invalid for given input");
			}
			byte[] array = new byte[MaximumOutputLength(inputLength)];
			int num = Encode32(input, inputOffset, inputLength, array, 0, array.Length);
			if (num != array.Length)
			{
				if (num < 0)
				{
					throw new InvalidOperationException("Compression has been corrupted");
				}
				byte[] array2 = new byte[num];
				Buffer.BlockCopy(array, 0, array2, 0, num);
				return array2;
			}
			return array;
		}

		public static int Encode64(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int outputLength)
		{
			CheckArguments(input, inputOffset, ref inputLength, output, outputOffset, ref outputLength);
			if (outputLength == 0)
			{
				return 0;
			}
			if (inputLength < 65547)
			{
				return LZ4_compress64kCtx_safe64(new ushort[8192], input, output, inputOffset, outputOffset, inputLength, outputLength);
			}
			return LZ4_compressCtx_safe64(new int[4096], input, output, inputOffset, outputOffset, inputLength, outputLength);
		}

		public static byte[] Encode64(byte[] input, int inputOffset, int inputLength)
		{
			if (inputLength < 0)
			{
				inputLength = input.Length - inputOffset;
			}
			if (input == null)
			{
				throw new ArgumentNullException("input");
			}
			if (inputOffset < 0 || inputOffset + inputLength > input.Length)
			{
				throw new ArgumentException("inputOffset and inputLength are invalid for given input");
			}
			byte[] array = new byte[MaximumOutputLength(inputLength)];
			int num = Encode64(input, inputOffset, inputLength, array, 0, array.Length);
			if (num != array.Length)
			{
				if (num < 0)
				{
					throw new InvalidOperationException("Compression has been corrupted");
				}
				byte[] array2 = new byte[num];
				Buffer.BlockCopy(array, 0, array2, 0, num);
				return array2;
			}
			return array;
		}

		public static int Decode32(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int outputLength, bool knownOutputLength)
		{
			CheckArguments(input, inputOffset, ref inputLength, output, outputOffset, ref outputLength);
			if (outputLength == 0)
			{
				return 0;
			}
			if (knownOutputLength)
			{
				if (LZ4_uncompress_safe32(input, output, inputOffset, 

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/BepInEx.MelonLoader.Loader/BepInEx.MelonLoader.Loader.UnityMono.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using MelonLoader;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyCompany("BepInEx.MelonLoader.Loader.UnityMono")]
[assembly: AssemblyConfiguration("BepInEx5")]
[assembly: AssemblyDescription("MelonLoader loader for UnityMono games")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0")]
[assembly: AssemblyProduct("BepInEx.MelonLoader.Loader.UnityMono")]
[assembly: AssemblyTitle("BepInEx.MelonLoader.Loader.UnityMono")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.1.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 BepInEx.MelonLoader.Loader.UnityMono
{
	[BepInPlugin("BepInEx.MelonLoader.Loader.UnityMono", "BepInEx.MelonLoader.Loader.UnityMono", "2.1.0")]
	public class Plugin : BaseUnityPlugin
	{
		private void Awake()
		{
			AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) => args.Name.Contains("MelonLoader") ? typeof(Core).Assembly : null;
			Core.Initialize(((BaseUnityPlugin)this).Config, false);
			Core.PreStart();
			Core.Start();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "BepInEx.MelonLoader.Loader.UnityMono";

		public const string PLUGIN_NAME = "BepInEx.MelonLoader.Loader.UnityMono";

		public const string PLUGIN_VERSION = "2.1.0";
	}
}

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/BepInEx.MelonLoader.Loader/bHapticsLib.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Timers;
using WebSocketDotNet;
using WebSocketDotNet.Messages;
using bHapticsLib.Internal;
using bHapticsLib.Internal.Models.Connection;
using bHapticsLib.Internal.SimpleJSON;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("bHapticsLib")]
[assembly: AssemblyCompany("Lava Gang")]
[assembly: AssemblyProduct("bHapticsLib")]
[assembly: AssemblyCopyright("Created by Herp Derpinstine")]
[assembly: AssemblyTrademark("Lava Gang")]
[assembly: Guid("C55CC59C-138B-48DF-95CC-FA956D064600")]
[assembly: AssemblyFileVersion("1.0.6")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("1.0.6.0")]
namespace bHapticsLib
{
	public class bHapticsConnection : ThreadedTask
	{
		private static readonly Type intType = typeof(int);

		private static readonly Type byteType = typeof(byte);

		private static readonly Type dotPointType = typeof(DotPoint);

		private List<RegisterRequest> RegisterCache = new List<RegisterRequest>();

		private ThreadSafeQueue<RegisterRequest> RegisterQueue = new ThreadSafeQueue<RegisterRequest>();

		private ThreadSafeQueue<SubmitRequest> SubmitQueue = new ThreadSafeQueue<SubmitRequest>();

		internal static int Port = 15881;

		internal static string Endpoint = "v2/feedbacks";

		private IPAddress _ipaddress = IPAddress.Loopback;

		private string _id;

		private string _name;

		public bool TryToReconnect;

		private int _maxRetries = 5;

		internal WebSocketConnection Socket;

		private PlayerPacket Packet = new PlayerPacket();

		private bool ShouldRun = true;

		public IPAddress IPAddress
		{
			get
			{
				return _ipaddress;
			}
			set
			{
				if (value == null)
				{
					RestartAndRunAction(delegate
					{
						_ipaddress = IPAddress.Loopback;
					});
				}
				else
				{
					RestartAndRunAction(delegate
					{
						_ipaddress = value;
					});
				}
			}
		}

		public string ID
		{
			get
			{
				return _id;
			}
			set
			{
				if (string.IsNullOrEmpty(value))
				{
					throw new ArgumentNullException("value");
				}
				RestartAndRunAction(delegate
				{
					_id = value.Replace(" ", "_");
				});
			}
		}

		public string Name
		{
			get
			{
				return _name;
			}
			set
			{
				if (string.IsNullOrEmpty(value))
				{
					throw new ArgumentNullException("value");
				}
				RestartAndRunAction(delegate
				{
					_name = value.Replace(" ", "_");
				});
			}
		}

		public int MaxRetries
		{
			get
			{
				return _maxRetries;
			}
			set
			{
				_maxRetries = value.Clamp(0, int.MaxValue);
			}
		}

		public bHapticsStatus Status
		{
			get
			{
				if (IsAlive())
				{
					if (IsConnected())
					{
						return bHapticsStatus.Connected;
					}
					return bHapticsStatus.Connecting;
				}
				return bHapticsStatus.Disconnected;
			}
		}

		internal bHapticsConnection()
		{
		}

		public bHapticsConnection(string id, string name, bool tryToReconnect = true, int maxRetries = 5)
			: this(null, id, name, tryToReconnect, maxRetries)
		{
		}

		public bHapticsConnection(IPAddress ipaddress, string id, string name, bool tryToReconnect = true, int maxRetries = 5)
		{
			Setup(ipaddress, id, name, tryToReconnect, maxRetries);
		}

		internal void Setup(IPAddress ipaddress, string id, string name, bool tryToReconnect, int maxRetries)
		{
			if (string.IsNullOrEmpty(id))
			{
				throw new ArgumentNullException("id");
			}
			if (string.IsNullOrEmpty(name))
			{
				throw new ArgumentNullException("name");
			}
			ID = id;
			Name = name;
			TryToReconnect = tryToReconnect;
			MaxRetries = maxRetries;
			IPAddress = ipaddress;
		}

		internal override bool BeginInitInternal()
		{
			if (Socket != null)
			{
				EndInit();
			}
			Socket = new WebSocketConnection(this);
			ShouldRun = true;
			return true;
		}

		internal override bool EndInitInternal()
		{
			if (Socket == null)
			{
				return false;
			}
			ShouldRun = false;
			while (IsAlive())
			{
				Thread.Sleep(1);
			}
			RegisterCache.Clear();
			Socket.Dispose();
			Socket = null;
			return true;
		}

		internal override void WithinThread()
		{
			while (ShouldRun)
			{
				if (Socket.FirstTry)
				{
					Socket.FirstTry = false;
					Socket.TryConnect();
				}
				if (IsConnected())
				{
					RegisterRequest aItem;
					while ((aItem = RegisterQueue.Dequeue()) != null)
					{
						Packet.Register.Add(aItem);
					}
					SubmitRequest aItem2;
					while ((aItem2 = SubmitQueue.Dequeue()) != null)
					{
						Packet.Submit.Add(aItem2);
					}
					if (!Packet.IsEmpty())
					{
						Socket.Send(Packet);
						Packet.Clear();
					}
				}
				if (ShouldRun)
				{
					Thread.Sleep(1);
				}
			}
		}

		internal void QueueRegisterCache()
		{
			int count = RegisterCache.Count;
			if (count <= 0)
			{
				return;
			}
			for (int i = 0; i < count; i++)
			{
				RegisterRequest registerRequest = RegisterCache[i];
				if (!(registerRequest == null) && !registerRequest.IsNull)
				{
					RegisterQueue.Enqueue(registerRequest);
				}
			}
		}

		private void RestartAndRunAction(Action whileDisconnected)
		{
			bool num = Socket != null;
			if (num)
			{
				EndInit();
			}
			whileDisconnected();
			if (num)
			{
				BeginInit();
			}
		}

		internal bool IsConnected()
		{
			return Socket?.IsConnected() ?? false;
		}

		public int GetConnectedDeviceCount()
		{
			return (Socket?.LastResponse?.ConnectedDeviceCount).GetValueOrDefault();
		}

		public bool IsDeviceConnected(PositionID type)
		{
			if (type == PositionID.VestFront || type == PositionID.VestBack)
			{
				type = PositionID.Vest;
			}
			return (Socket?.LastResponse?.ConnectedPositions?.ContainsValue(type.ToPacketString())).GetValueOrDefault();
		}

		public int[] GetDeviceStatus(PositionID type)
		{
			if (Socket == null || Socket.LastResponse == null)
			{
				return null;
			}
			JSONNode status = Socket.LastResponse.Status;
			if (type == PositionID.Vest)
			{
				JSONNode jSONNode = status[PositionID.VestFront.ToPacketString()];
				JSONNode jSONNode2 = status[PositionID.VestBack.ToPacketString()];
				int num = jSONNode.Count + jSONNode2.Count;
				int[] array = new int[num];
				for (int i = 0; i < num; i++)
				{
					if (i < jSONNode.Count)
					{
						array[i] = jSONNode[i].AsInt;
					}
					else
					{
						array[i] = jSONNode2[i - jSONNode.Count].AsInt;
					}
				}
				return array;
			}
			JSONNode jSONNode3 = status[type.ToPacketString()];
			int count = jSONNode3.Count;
			int[] array2 = new int[count];
			for (int j = 0; j < count; j++)
			{
				array2[j] = jSONNode3[j].AsInt;
			}
			return array2;
		}

		public bool IsPlaying(string key)
		{
			return (Socket?.LastResponse?.ActiveKeys?.ContainsValue(key)).GetValueOrDefault();
		}

		public bool IsPlayingAny()
		{
			WebSocketConnection socket = Socket;
			if (socket == null)
			{
				return false;
			}
			return socket.LastResponse?.ActiveKeys?.Count > 0;
		}

		public void StopPlaying(string key)
		{
			if (IsAlive() && IsConnected())
			{
				SubmitQueue.Enqueue(new SubmitRequest
				{
					key = key,
					type = "turnOff"
				});
			}
		}

		public void StopPlayingAll()
		{
			if (IsAlive() && IsConnected())
			{
				SubmitQueue.Enqueue(new SubmitRequest
				{
					type = "turnOffAll"
				});
			}
		}

		public bool IsPatternRegistered(string key)
		{
			return (Socket?.LastResponse?.RegisteredKeys?.ContainsValue(key)).GetValueOrDefault();
		}

		public void RegisterPatternFromFile(string key, string tactFilePath)
		{
			if (File.Exists(tactFilePath))
			{
				RegisterPatternFromJson(key, File.ReadAllText(tactFilePath));
			}
		}

		public void RegisterPatternFromJson(string key, string tactFileJson)
		{
			if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(tactFileJson))
			{
				return;
			}
			JSONNode jSONNode = JSON.Parse(tactFileJson);
			if (!jSONNode.HasKey("project"))
			{
				return;
			}
			JSONNode jSONNode2 = jSONNode["project"];
			if (!(jSONNode2 == null) && !jSONNode2.IsNull && jSONNode2.IsObject)
			{
				RegisterRequest registerRequest = new RegisterRequest();
				registerRequest.key = key;
				registerRequest.project = jSONNode2.AsObject;
				RegisterCache.Add(registerRequest);
				if (IsConnected())
				{
					RegisterQueue.Enqueue(registerRequest);
				}
			}
		}

		public void RegisterPatternSwappedFromFile(string key, string tactFilePath)
		{
			if (File.Exists(tactFilePath))
			{
				RegisterPatternSwappedFromJson(key, File.ReadAllText(tactFilePath));
			}
		}

		public void RegisterPatternSwappedFromJson(string key, string tactFileJson)
		{
			if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(tactFileJson))
			{
				return;
			}
			JSONNode jSONNode = JSON.Parse(tactFileJson);
			if (!jSONNode.HasKey("project"))
			{
				return;
			}
			JSONNode jSONNode2 = jSONNode["project"];
			if (!(jSONNode2 == null) && !jSONNode2.IsNull && jSONNode2.IsObject)
			{
				RegisterRequest registerRequest = new RegisterRequest();
				registerRequest.key = key;
				JSONObject asObject = jSONNode2.AsObject;
				JSONArray asArray = asObject["tracks"].AsArray;
				LoopTracks(asArray, delegate(JSONObject effect)
				{
					JSONNode jSONNode3 = effect["modes"];
					JSONNode value = jSONNode3[0];
					JSONNode value2 = jSONNode3[1];
					jSONNode3[0] = value2;
					jSONNode3[1] = value;
					effect["modes"] = jSONNode3;
				});
				asObject["tracks"] = asArray;
				registerRequest.project = asObject;
				RegisterCache.Add(registerRequest);
				if (IsConnected())
				{
					RegisterQueue.Enqueue(registerRequest);
				}
			}
		}

		private static void LoopTracks(JSONArray tracks, Action<JSONObject> act)
		{
			for (int i = 0; i < tracks.Count; i++)
			{
				JSONObject asObject = tracks[i].AsObject;
				JSONArray asArray = asObject["effects"].AsArray;
				for (int j = 0; j < asArray.Count; j++)
				{
					JSONObject asObject2 = asArray[j].AsObject;
					act(asObject2);
					asArray[j] = asObject2;
				}
				asObject["effects"] = asArray;
				tracks[i] = asObject;
			}
		}

		public void Play<A, B>(string key, int durationMillis, PositionID position, A dotPoints, B pathPoints, MirrorDirection dotMirrorDirection = MirrorDirection.None) where A : IList, ICollection where B : IList<PathPoint>, ICollection<PathPoint>
		{
			if (!IsAlive())
			{
				return;
			}
			if (position == PositionID.Vest)
			{
				Play(key + "Front", durationMillis, PositionID.VestFront, dotPoints, pathPoints, dotMirrorDirection);
				Play(key + "Back", durationMillis, PositionID.VestBack, dotPoints, pathPoints, dotMirrorDirection);
				return;
			}
			SubmitRequest submitRequest = new SubmitRequest
			{
				key = key,
				type = "frame"
			};
			submitRequest.Frame.durationMillis = durationMillis;
			submitRequest.Frame.position = position.ToPacketString();
			if (dotPoints != null && dotPoints.Count > 0)
			{
				object[] dotPoints2 = null;
				if (dotMirrorDirection != 0)
				{
					dotPoints2 = new object[dotPoints.Count];
					for (int i = 0; i < dotPoints.Count; i++)
					{
						dotPoints2[i] = dotPoints[i];
					}
					switch (dotMirrorDirection)
					{
					case MirrorDirection.Horizontal:
						MirrorHorizontal(ref dotPoints2, position);
						break;
					case MirrorDirection.Vertical:
						MirrorVertical(ref dotPoints2, position);
						break;
					case MirrorDirection.Both:
						MirrorHorizontal(ref dotPoints2, position);
						MirrorVertical(ref dotPoints2, position);
						break;
					}
				}
				Type type = null;
				for (int j = 0; j < ((dotPoints2 == null) ? dotPoints.Count : dotPoints2.Length); j++)
				{
					object obj = ((dotPoints2 == null) ? dotPoints[j] : dotPoints2[j]);
					if (obj == null)
					{
						continue;
					}
					if ((object)type == null)
					{
						type = obj.GetType();
					}
					if ((object)type == intType || (object)type == byteType)
					{
						JSONObject jSONObject = new JSONObject();
						jSONObject["index"] = j.Clamp(0, 20);
						if ((object)type == intType)
						{
							jSONObject["intensity"] = Extensions.Clamp<int>((int)obj, 0, 500);
						}
						else if ((object)type == byteType)
						{
							jSONObject["intensity"] = Extensions.Clamp((byte)obj, (byte)0, (byte)200);
						}
						submitRequest.Frame.dotPoints.Add(jSONObject);
					}
					else if ((object)type == dotPointType)
					{
						submitRequest.Frame.dotPoints.Add((obj as DotPoint).node);
					}
				}
			}
			SubmitQueue.Enqueue(submitRequest);
		}

		public void PlayRegistered(string key, string altKey = null, ScaleOption scaleOption = null, RotationOption rotationOption = null)
		{
			if (IsAlive())
			{
				SubmitRequest submitRequest = new SubmitRequest
				{
					key = key,
					type = "key"
				};
				if (!string.IsNullOrEmpty(altKey))
				{
					submitRequest.Parameters["altKey"] = altKey;
				}
				if (scaleOption != null)
				{
					submitRequest.Parameters["scaleOption"] = scaleOption.node;
				}
				if (rotationOption != null)
				{
					submitRequest.Parameters["rotationOption"] = rotationOption.node;
				}
				SubmitQueue.Enqueue(submitRequest);
			}
		}

		public void PlayRegisteredMillis(string key, int startTimeMillis = 0)
		{
			if (IsAlive())
			{
				SubmitRequest submitRequest = new SubmitRequest
				{
					key = key,
					type = "key"
				};
				submitRequest.Parameters["startTimeMillis"] = startTimeMillis;
				SubmitQueue.Enqueue(submitRequest);
			}
		}

		private static void MirrorHorizontal<A>(ref A dotPoints, PositionID position) where A : IList, ICollection
		{
			int count = dotPoints.Count;
			int num = count / 2;
			if (count != 20)
			{
				dotPoints.Reverse(0, count);
				return;
			}
			switch (position)
			{
			case PositionID.Head:
				dotPoints.Reverse(0, count);
				break;
			case PositionID.VestFront:
			case PositionID.VestBack:
				dotPoints.Reverse(0, 4);
				dotPoints.Reverse(4, 4);
				dotPoints.Reverse(8, 4);
				dotPoints.Reverse(12, 4);
				dotPoints.Reverse(16, 4);
				break;
			case PositionID.FootLeft:
			case PositionID.FootRight:
			case PositionID.ArmLeft:
			case PositionID.ArmRight:
				dotPoints.Reverse(0, num);
				dotPoints.Reverse(num + 1, count);
				break;
			}
		}

		private static void MirrorVertical<A>(ref A dotPoints, PositionID position) where A : IList, ICollection
		{
			int count = dotPoints.Count;
			if (count != 20)
			{
				dotPoints.Reverse(0, count);
				return;
			}
			switch (position)
			{
			case PositionID.VestFront:
			case PositionID.VestBack:
				dotPoints.Swap(0, 16);
				dotPoints.Swap(1, 17);
				dotPoints.Swap(2, 18);
				dotPoints.Swap(3, 19);
				dotPoints.Swap(4, 12);
				dotPoints.Swap(5, 13);
				dotPoints.Swap(6, 14);
				dotPoints.Swap(7, 15);
				break;
			case PositionID.ArmLeft:
			case PositionID.ArmRight:
				dotPoints.Swap(0, 3);
				dotPoints.Swap(1, 4);
				dotPoints.Swap(2, 5);
				break;
			case PositionID.HandLeft:
			case PositionID.HandRight:
				dotPoints.Reverse(0, count);
				break;
			}
		}
	}
	public static class bHapticsManager
	{
		public const int MaxIntensityInInt = 500;

		public const byte MaxIntensityInByte = 200;

		public const int MaxMotorsPerDotPoint = 20;

		public const int MaxMotorsPerPathPoint = 3;

		private static bHapticsConnection Connection = new bHapticsConnection();

		public static bHapticsStatus Status => Connection.Status;

		public static bool Connect(string id, string name, bool tryToReconnect = true, int maxRetries = 5)
		{
			Connection.Setup(null, id, name, tryToReconnect, maxRetries);
			if (Status == bHapticsStatus.Disconnected)
			{
				return Connection.BeginInit();
			}
			return true;
		}

		public static bool Disconnect()
		{
			if (Status == bHapticsStatus.Disconnected)
			{
				return true;
			}
			StopPlayingAll();
			return Connection.EndInit();
		}

		public static int GetConnectedDeviceCount()
		{
			return Connection.GetConnectedDeviceCount();
		}

		public static bool IsAnyDevicesConnected()
		{
			return GetConnectedDeviceCount() > 0;
		}

		public static bool IsDeviceConnected(PositionID type)
		{
			return Connection.IsDeviceConnected(type);
		}

		public static int[] GetDeviceStatus(PositionID type)
		{
			return Connection.GetDeviceStatus(type);
		}

		public static bool IsAnyMotorActive(PositionID type)
		{
			return GetDeviceStatus(type)?.ContainsValueMoreThan(0) ?? false;
		}

		public static bool IsPlaying(string key)
		{
			return Connection.IsPlaying(key);
		}

		public static bool IsPlayingAny()
		{
			return Connection.IsPlayingAny();
		}

		public static void StopPlaying(string key)
		{
			Connection.StopPlaying(key);
		}

		public static void StopPlayingAll()
		{
			Connection.StopPlayingAll();
		}

		public static bool IsPatternRegistered(string key)
		{
			return Connection.IsPatternRegistered(key);
		}

		public static void RegisterPatternFromJson(string key, string tactFileJson)
		{
			Connection.RegisterPatternFromJson(key, tactFileJson);
		}

		public static void RegisterPatternFromFile(string key, string tactFilePath)
		{
			Connection.RegisterPatternFromFile(key, tactFilePath);
		}

		public static void RegisterPatternSwappedFromJson(string key, string tactFileJson)
		{
			Connection.RegisterPatternSwappedFromJson(key, tactFileJson);
		}

		public static void RegisterPatternSwappedFromFile(string key, string tactFilePath)
		{
			Connection.RegisterPatternSwappedFromFile(key, tactFilePath);
		}

		public static void Play(string key, int durationMillis, PositionID position, int[] dotPoints)
		{
			Connection.Play<int[], PathPoint[]>(key, durationMillis, position, dotPoints, null);
		}

		public static void Play(string key, int durationMillis, PositionID position, List<int> dotPoints)
		{
			Connection.Play<List<int>, PathPoint[]>(key, durationMillis, position, dotPoints, null);
		}

		public static void Play(string key, int durationMillis, PositionID position, byte[] dotPoints)
		{
			Connection.Play<byte[], PathPoint[]>(key, durationMillis, position, dotPoints, null);
		}

		public static void Play(string key, int durationMillis, PositionID position, List<byte> dotPoints)
		{
			Connection.Play<List<byte>, PathPoint[]>(key, durationMillis, position, dotPoints, null);
		}

		public static void Play(string key, int durationMillis, PositionID position, DotPoint[] dotPoints)
		{
			Connection.Play<DotPoint[], PathPoint[]>(key, durationMillis, position, dotPoints, null);
		}

		public static void Play(string key, int durationMillis, PositionID position, List<DotPoint> dotPoints)
		{
			Connection.Play<List<DotPoint>, PathPoint[]>(key, durationMillis, position, dotPoints, null);
		}

		public static void Play<A>(string key, int durationMillis, PositionID position, A pathPoints) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play<DotPoint[], A>(key, durationMillis, position, null, pathPoints);
		}

		public static void Play<A>(string key, int durationMillis, PositionID position, int[] dotPoints, A pathPoints) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints);
		}

		public static void Play<A>(string key, int durationMillis, PositionID position, List<int> dotPoints, A pathPoints) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints);
		}

		public static void Play<A>(string key, int durationMillis, PositionID position, byte[] dotPoints, A pathPoints) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints);
		}

		public static void Play<A>(string key, int durationMillis, PositionID position, List<byte> dotPoints, A pathPoints) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints);
		}

		public static void Play<A>(string key, int durationMillis, PositionID position, DotPoint[] dotPoints, A pathPoints) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints);
		}

		public static void Play<A>(string key, int durationMillis, PositionID position, List<DotPoint> dotPoints, A pathPoints) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints);
		}

		public static void PlayMirrored(string key, int durationMillis, PositionID position, int[] dotPoints, MirrorDirection mirrorDirection)
		{
			Connection.Play<int[], PathPoint[]>(key, durationMillis, position, dotPoints, null, mirrorDirection);
		}

		public static void PlayMirrored(string key, int durationMillis, PositionID position, List<int> dotPoints, MirrorDirection mirrorDirection)
		{
			Connection.Play<List<int>, PathPoint[]>(key, durationMillis, position, dotPoints, null, mirrorDirection);
		}

		public static void PlayMirrored(string key, int durationMillis, PositionID position, byte[] dotPoints, MirrorDirection mirrorDirection)
		{
			Connection.Play<byte[], PathPoint[]>(key, durationMillis, position, dotPoints, null, mirrorDirection);
		}

		public static void PlayMirrored(string key, int durationMillis, PositionID position, List<byte> dotPoints, MirrorDirection mirrorDirection)
		{
			Connection.Play<List<byte>, PathPoint[]>(key, durationMillis, position, dotPoints, null, mirrorDirection);
		}

		public static void PlayMirrored(string key, int durationMillis, PositionID position, DotPoint[] dotPoints, MirrorDirection mirrorDirection)
		{
			Connection.Play<DotPoint[], PathPoint[]>(key, durationMillis, position, dotPoints, null, mirrorDirection);
		}

		public static void PlayMirrored(string key, int durationMillis, PositionID position, List<DotPoint> dotPoints, MirrorDirection mirrorDirection)
		{
			Connection.Play<List<DotPoint>, PathPoint[]>(key, durationMillis, position, dotPoints, null, mirrorDirection);
		}

		public static void PlayMirrored<A>(string key, int durationMillis, PositionID position, int[] dotPoints, A pathPoints, MirrorDirection dotMirrorDirection) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints, dotMirrorDirection);
		}

		public static void PlayMirrored<A>(string key, int durationMillis, PositionID position, List<int> dotPoints, A pathPoints, MirrorDirection dotMirrorDirection) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints, dotMirrorDirection);
		}

		public static void PlayMirrored<A>(string key, int durationMillis, PositionID position, byte[] dotPoints, A pathPoints, MirrorDirection dotMirrorDirection) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints, dotMirrorDirection);
		}

		public static void PlayMirrored<A>(string key, int durationMillis, PositionID position, List<byte> dotPoints, A pathPoints, MirrorDirection dotMirrorDirection) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints, dotMirrorDirection);
		}

		public static void PlayMirrored<A>(string key, int durationMillis, PositionID position, DotPoint[] dotPoints, A pathPoints, MirrorDirection dotMirrorDirection) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints, dotMirrorDirection);
		}

		public static void PlayMirrored<A>(string key, int durationMillis, PositionID position, List<DotPoint> dotPoints, A pathPoints, MirrorDirection dotMirrorDirection) where A : IList<PathPoint>, ICollection<PathPoint>
		{
			Connection.Play(key, durationMillis, position, dotPoints, pathPoints, dotMirrorDirection);
		}

		public static void PlayRegistered(string key)
		{
			Connection.PlayRegistered(key);
		}

		public static void PlayRegistered(string key, int startTimeMillis)
		{
			Connection.PlayRegisteredMillis(key, startTimeMillis);
		}

		public static void PlayRegistered(string key, ScaleOption option)
		{
			Connection.PlayRegistered(key, null, option);
		}

		public static void PlayRegistered(string key, RotationOption option)
		{
			Connection.PlayRegistered(key, null, null, option);
		}

		public static void PlayRegistered(string key, ScaleOption scaleOption, RotationOption rotationOption)
		{
			Connection.PlayRegistered(key, null, scaleOption, rotationOption);
		}

		public static void PlayRegistered(string key, string altKey)
		{
			Connection.PlayRegistered(key, altKey);
		}

		public static void PlayRegistered(string key, string altKey, ScaleOption option)
		{
			Connection.PlayRegistered(key, altKey, option);
		}

		public static void PlayRegistered(string key, string altKey, RotationOption option)
		{
			Connection.PlayRegistered(key, altKey, null, option);
		}

		public static void PlayRegistered(string key, string altKey, ScaleOption scaleOption, RotationOption rotationOption)
		{
			Connection.PlayRegistered(key, altKey, scaleOption, rotationOption);
		}
	}
	public enum bHapticsStatus
	{
		Disconnected,
		Connecting,
		Connected
	}
	public class DotPoint
	{
		internal JSONObject node = new JSONObject();

		public int Index
		{
			get
			{
				return node["index"].AsInt;
			}
			set
			{
				node["index"] = value.Clamp(0, 20);
			}
		}

		public int Intensity
		{
			get
			{
				return node["intensity"].AsInt;
			}
			set
			{
				node["intensity"] = value.Clamp(0, 500);
			}
		}

		public DotPoint(int index = 0, int intensity = 50)
		{
			Index = index;
			Intensity = intensity;
		}

		public override string ToString()
		{
			return string.Format("{0} ( {1}: {2}, {3}: {4} )", "DotPoint", "Index", Index, "Intensity", Intensity);
		}
	}
	public static class Extensions
	{
		private static string OscAddressHeader = "/bhaptics";

		public static string ToOscAddress(this PositionID value)
		{
			return value switch
			{
				PositionID.Head => OscAddressHeader + "/head", 
				PositionID.Vest => OscAddressHeader + "/vest", 
				PositionID.VestFront => OscAddressHeader + "/vest/front", 
				PositionID.VestBack => OscAddressHeader + "/vest/back", 
				PositionID.ArmLeft => OscAddressHeader + "/arm/left", 
				PositionID.ArmRight => OscAddressHeader + "/arm/right", 
				PositionID.HandLeft => OscAddressHeader + "/hand/left", 
				PositionID.HandRight => OscAddressHeader + "/hand/right", 
				PositionID.GloveLeft => OscAddressHeader + "/glove/left", 
				PositionID.GloveRight => OscAddressHeader + "/glove/right", 
				PositionID.FootLeft => OscAddressHeader + "/foot/left", 
				PositionID.FootRight => OscAddressHeader + "/foot/right", 
				_ => null, 
			};
		}

		internal static string ToPacketString(this PositionID value)
		{
			return value switch
			{
				PositionID.ArmLeft => "ForearmL", 
				PositionID.ArmRight => "ForearmR", 
				PositionID.HandLeft => "HandL", 
				PositionID.HandRight => "HandR", 
				PositionID.GloveLeft => "GloveL", 
				PositionID.GloveRight => "GloveR", 
				PositionID.FootLeft => "FootL", 
				PositionID.FootRight => "FootR", 
				_ => value.ToString(), 
			};
		}

		internal static T Clamp<T>(T value, T min, T max) where T : IComparable<T>
		{
			if (value.CompareTo(min) < 0)
			{
				return min;
			}
			if (value.CompareTo(max) > 0)
			{
				return max;
			}
			return value;
		}

		internal static short Clamp(this short value, short min, short max)
		{
			return Extensions.Clamp<short>(value, min, max);
		}

		internal static ushort Clamp(this ushort value, ushort min, ushort max)
		{
			return Extensions.Clamp<ushort>(value, min, max);
		}

		internal static int Clamp(this int value, int min, int max)
		{
			return Extensions.Clamp<int>(value, min, max);
		}

		internal static uint Clamp(this uint value, uint min, uint max)
		{
			return Extensions.Clamp<uint>(value, min, max);
		}

		internal static double Clamp(this double value, double min, double max)
		{
			return Extensions.Clamp<double>(value, min, max);
		}

		internal static float Clamp(this float value, float min, float max)
		{
			return Extensions.Clamp<float>(value, min, max);
		}

		internal static void AddRange<T, Z>(this T arr, List<Z> value) where T : JSONNode where Z : JSONNode
		{
			if (value == null || arr.IsNull)
			{
				return;
			}
			int count = value.Count;
			if (count <= 0)
			{
				return;
			}
			for (int i = 0; i < count; i++)
			{
				Z val = value[i];
				if (!((JSONNode)val == (object)null) && !val.IsNull)
				{
					arr.Add(value[i]);
				}
			}
		}

		internal static void AddRange<T, Z>(this T arr, Z[] value) where T : JSONNode where Z : JSONNode
		{
			if (value == null || arr.IsNull)
			{
				return;
			}
			int num = value.Length;
			if (num <= 0)
			{
				return;
			}
			for (int i = 0; i < num; i++)
			{
				Z val = value[i];
				if (!((JSONNode)val == (object)null) && !val.IsNull)
				{
					arr.Add(value[i]);
				}
			}
		}

		internal static bool ContainsValue<T, Z>(this T arr, Z value) where T : JSONNode where Z : JSONNode
		{
			if (arr.IsNull || (JSONNode)value == (object)null || value.IsNull)
			{
				return false;
			}
			int count = arr.Count;
			if (count <= 0)
			{
				return false;
			}
			for (int i = 0; i < count; i++)
			{
				JSONNode jSONNode = arr[i];
				if (!(jSONNode == null) && !jSONNode.IsNull)
				{
					if (value.IsObject && jSONNode.IsObject && jSONNode.AsObject == value)
					{
						return true;
					}
					if (value.IsArray && jSONNode.IsArray && jSONNode.AsArray == value)
					{
						return true;
					}
				}
			}
			return false;
		}

		internal static bool ContainsValue<T>(this T arr, bool value) where T : JSONNode
		{
			if (arr.IsNull)
			{
				return false;
			}
			int count = arr.Count;
			if (count <= 0)
			{
				return false;
			}
			for (int i = 0; i < count; i++)
			{
				JSONNode jSONNode = arr[i];
				if (!(jSONNode == null) && !jSONNode.IsNull && jSONNode.IsBoolean && jSONNode.AsBool == value)
				{
					return true;
				}
			}
			return false;
		}

		internal static bool ContainsValue<T>(this T arr, string value) where T : JSONNode
		{
			if (arr.IsNull || string.IsNullOrEmpty(value))
			{
				return false;
			}
			int count = arr.Count;
			if (count <= 0)
			{
				return false;
			}
			for (int i = 0; i < count; i++)
			{
				JSONNode jSONNode = arr[i];
				if (!(jSONNode == null) && !jSONNode.IsNull && jSONNode.IsString && !string.IsNullOrEmpty(jSONNode.Value) && jSONNode.Value.Equals(value))
				{
					return true;
				}
			}
			return false;
		}

		internal static bool ContainsValueMoreThan<T>(this T[] arr, T value) where T : IComparable<T>
		{
			int num = arr.Length;
			if (num <= 0)
			{
				return false;
			}
			for (int i = 0; i < num; i++)
			{
				if (arr[i].CompareTo(value) > 0)
				{
					return true;
				}
			}
			return false;
		}

		internal static void ReverseAll<A>(this A arr) where A : IList, ICollection
		{
			arr.Reverse(0, arr.Count);
		}

		internal static void Reverse<A>(this A arr, int index, int length) where A : IList, ICollection
		{
			int num = index;
			int num2 = index + length - 1;
			while (num < num2)
			{
				arr.Swap(num2, num);
				num++;
				num2--;
			}
		}

		internal static void ReverseAll(this JSONNode node)
		{
			node.Reverse(0, node.Count);
		}

		internal static void Reverse(this JSONNode node, int index, int length)
		{
			int num = index;
			int num2 = index + length - 1;
			while (num < num2)
			{
				JSONNode value = node[num2];
				JSONNode value2 = node[num];
				node[num2] = value2;
				node[num] = value;
				num++;
				num2--;
			}
		}

		internal static void Swap<A>(this A dotPoints, int indexA, int indexB) where A : IList, ICollection
		{
			int count = dotPoints.Count;
			if (count <= 1 || indexA < 0 || indexA > count - 1 || indexB < 0 || indexB > count - 1)
			{
				return;
			}
			object obj = dotPoints[indexA];
			object obj2 = dotPoints[indexB];
			if ((object)obj.GetType() == typeof(DotPoint))
			{
				if (obj != null)
				{
					(obj as DotPoint).Index = indexB;
				}
				if (obj2 != null)
				{
					(obj2 as DotPoint).Index = indexA;
				}
			}
			dotPoints[indexB] = obj;
			dotPoints[indexA] = obj2;
		}
	}
	public class HapticPattern
	{
		public string Key { get; private set; }

		public static HapticPattern LoadFromJson(string key, string tactFileJson)
		{
			bHapticsManager.RegisterPatternFromJson(key, tactFileJson);
			return new HapticPattern
			{
				Key = key
			};
		}

		public static HapticPattern LoadFromFile(string key, string tactFilePath)
		{
			bHapticsManager.RegisterPatternFromFile(key, tactFilePath);
			return new HapticPattern
			{
				Key = key
			};
		}

		public static HapticPattern LoadSwappedFromJson(string key, string tactFileJson)
		{
			bHapticsManager.RegisterPatternSwappedFromJson(key, tactFileJson);
			return new HapticPattern
			{
				Key = key
			};
		}

		public static HapticPattern LoadSwappedFromFile(string key, string tactFilePath)
		{
			bHapticsManager.RegisterPatternSwappedFromFile(key, tactFilePath);
			return new HapticPattern
			{
				Key = key
			};
		}

		public bool IsRegistered()
		{
			return bHapticsManager.IsPatternRegistered(Key);
		}

		public bool IsPlaying()
		{
			return bHapticsManager.IsPlaying(Key);
		}

		public void Stop()
		{
			bHapticsManager.StopPlaying(Key);
		}

		public void Play()
		{
			bHapticsManager.PlayRegistered(Key);
		}

		public void Play(ScaleOption option)
		{
			bHapticsManager.PlayRegistered(Key, option);
		}

		public void Play(RotationOption option)
		{
			bHapticsManager.PlayRegistered(Key, option);
		}

		public void Play(ScaleOption scaleOption, RotationOption rotationOption)
		{
			bHapticsManager.PlayRegistered(Key, scaleOption, rotationOption);
		}
	}
	public enum MirrorDirection
	{
		None,
		Horizontal,
		Vertical,
		Both
	}
	public class PathPoint
	{
		internal JSONObject node = new JSONObject();

		public float X
		{
			get
			{
				return node["x"].AsFloat;
			}
			set
			{
				node["x"] = value;
			}
		}

		public float Y
		{
			get
			{
				return node["y"].AsFloat;
			}
			set
			{
				node["y"] = value;
			}
		}

		public int Intensity
		{
			get
			{
				return node["intensity"].AsInt;
			}
			set
			{
				node["intensity"] = value.Clamp(0, 500);
			}
		}

		public int MotorCount
		{
			get
			{
				return node["motorCount"].AsInt;
			}
			set
			{
				node["motorCount"] = value.Clamp(0, 3);
			}
		}

		public PathPoint(float x = 0f, float y = 0f, int intensity = 50, int motorCount = 3)
		{
			X = x;
			Y = y;
			Intensity = intensity;
			MotorCount = motorCount;
		}

		public override string ToString()
		{
			return string.Format("{0} ( {1}: {2}, {3}: {4}, {5}: {6}, {7}: {8} )", "PathPoint", "X", X, "Y", Y, "MotorCount", MotorCount, "Intensity", Intensity);
		}
	}
	public enum PositionID
	{
		Vest = 3,
		Head = 4,
		HandLeft = 6,
		HandRight = 7,
		FootLeft = 8,
		FootRight = 9,
		ArmLeft = 10,
		ArmRight = 11,
		VestFront = 201,
		VestBack = 202,
		GloveLeft = 203,
		GloveRight = 204
	}
	public class RotationOption
	{
		internal JSONObject node = new JSONObject();

		public float OffsetAngleX
		{
			get
			{
				return node["offsetAngleX"].AsFloat;
			}
			set
			{
				node["offsetAngleX"] = value;
			}
		}

		public float OffsetY
		{
			get
			{
				return node["offsetY"].AsFloat;
			}
			set
			{
				node["offsetY"] = value;
			}
		}

		public RotationOption(float offsetAngleX = 0f, float offsetY = 0f)
		{
			OffsetAngleX = offsetAngleX;
			OffsetY = offsetY;
		}

		public override string ToString()
		{
			return string.Format("{0} ( {1}: {2}, {3}: {4} )", "RotationOption", "OffsetAngleX", OffsetAngleX, "OffsetY", OffsetY);
		}
	}
	public class ScaleOption
	{
		internal JSONObject node = new JSONObject();

		public float Intensity
		{
			get
			{
				return node["intensity"].AsFloat;
			}
			set
			{
				node["intensity"] = value;
			}
		}

		public float Duration
		{
			get
			{
				return node["duration"].AsFloat;
			}
			set
			{
				node["duration"] = value;
			}
		}

		public ScaleOption(float intensity = 1f, float duration = 1f)
		{
			Intensity = intensity;
			Duration = duration;
		}

		public override string ToString()
		{
			return string.Format("{0} ( {1}: {2}, {3}: {4} )", "ScaleOption", "Intensity", Intensity, "Duration", Duration);
		}
	}
}
namespace bHapticsLib.Properties
{
	internal static class BuildInfo
	{
		public const string Name = "bHapticsLib";

		public const string Author = "Herp Derpinstine";

		public const string Company = "Lava Gang";

		public const string Version = "1.0.6";

		public const string DownloadLink = "https://github.com/HerpDerpinstine/bHapticsLib";
	}
}
namespace bHapticsLib.Internal
{
	public abstract class ThreadedTask
	{
		private Thread thread;

		internal bool IsAlive()
		{
			return thread?.IsAlive ?? false;
		}

		public bool BeginInit()
		{
			if (!BeginInitInternal())
			{
				return false;
			}
			RunThread();
			return true;
		}

		internal abstract bool BeginInitInternal();

		public bool EndInit()
		{
			if (!EndInitInternal())
			{
				return false;
			}
			KillThread();
			return true;
		}

		internal abstract bool EndInitInternal();

		internal abstract void WithinThread();

		private void RunThread()
		{
			if (IsAlive())
			{
				KillThread();
			}
			thread = new Thread(WithinThread);
			thread.Start();
		}

		private void KillThread()
		{
			if (IsAlive())
			{
				thread.Abort();
				thread = null;
			}
		}
	}
	internal class ThreadSafeQueue<T> : IEnumerable<T>, IEnumerable, ICollection
	{
		private Queue<T> queue = new Queue<T>();

		public int Count => queue.Count;

		public object SyncRoot => ((ICollection)queue).SyncRoot;

		public bool IsSynchronized => true;

		public void Enqueue(T item)
		{
			lock (SyncRoot)
			{
				queue.Enqueue(item);
			}
		}

		public T Dequeue()
		{
			if (Count <= 0)
			{
				return default(T);
			}
			lock (SyncRoot)
			{
				return queue.Dequeue();
			}
		}

		public void Clear()
		{
			lock (SyncRoot)
			{
				queue.Clear();
			}
		}

		public void CopyTo(Array array, int index)
		{
			lock (SyncRoot)
			{
				((ICollection)queue).CopyTo(array, index);
			}
		}

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

		public IEnumerator<T> GetEnumerator()
		{
			lock (SyncRoot)
			{
				foreach (T item in queue)
				{
					yield return item;
				}
			}
		}
	}
	internal class WebSocketConnection : IDisposable
	{
		private bHapticsConnection Parent;

		internal bool FirstTry;

		private bool isConnected;

		private int RetryCount;

		private int RetryDelay = 3;

		private System.Timers.Timer RetryTimer;

		internal WebSocket Socket;

		internal PlayerResponse LastResponse;

		internal WebSocketConnection(bHapticsConnection parent)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			Parent = parent;
			string text = $"ws://{parent.IPAddress}:{bHapticsConnection.Port}/{bHapticsConnection.Endpoint}?app_id={parent.ID}&app_name={parent.Name}";
			WebSocketConfiguration val = default(WebSocketConfiguration);
			((WebSocketConfiguration)(ref val))..ctor();
			((WebSocketConfiguration)(ref val)).AutoConnect = false;
			((WebSocketConfiguration)(ref val)).UseAutomaticReceiveThread = true;
			Socket = new WebSocket(text, val);
			Socket.TextReceived += delegate(string txt)
			{
				try
				{
					if (LastResponse == null)
					{
						LastResponse = new PlayerResponse();
					}
					JSONNode jSONNode = JSON.Parse(txt);
					if (!(jSONNode == null) && !jSONNode.IsNull && jSONNode.IsObject)
					{
						LastResponse.m_Dict = jSONNode.AsObject.m_Dict;
					}
				}
				catch
				{
				}
			};
			Socket.Opened += delegate
			{
				isConnected = true;
				RetryCount = 0;
				Parent.QueueRegisterCache();
			};
			Socket.Closed += delegate
			{
				isConnected = false;
				LastResponse = null;
			};
			if (parent.TryToReconnect)
			{
				RetryTimer = new System.Timers.Timer(RetryDelay * 1000);
				RetryTimer.AutoReset = true;
				RetryTimer.Elapsed += delegate
				{
					RetryCheck();
				};
				RetryTimer.Start();
			}
			FirstTry = true;
		}

		public void Dispose()
		{
			try
			{
				Socket.SendClose((WebSocketCloseCode)1000, (string)null);
				isConnected = false;
				if (Parent.TryToReconnect)
				{
					RetryTimer.Stop();
					RetryTimer.Dispose();
				}
			}
			catch
			{
			}
		}

		internal void TryConnect()
		{
			try
			{
				Socket.Connect();
			}
			catch
			{
			}
		}

		private void RetryCheck()
		{
			//IL_001c: 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: Invalid comparison between Unknown and I4
			if (IsConnected() || !Parent.TryToReconnect || (int)Socket.State == 0 || (int)Socket.State == 2)
			{
				return;
			}
			if (Parent.MaxRetries > 0)
			{
				if (RetryCount >= Parent.MaxRetries)
				{
					Parent.EndInit();
					return;
				}
				RetryCount++;
			}
			TryConnect();
		}

		internal bool IsConnected()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (isConnected)
			{
				return (int)Socket.State == 1;
			}
			return false;
		}

		internal void Send(JSONObject jsonNode)
		{
			Send(jsonNode.ToString());
		}

		internal void Send(string msg)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			if (!IsConnected())
			{
				return;
			}
			try
			{
				Socket.Send((WebSocketMessage)new WebSocketTextMessage(msg));
			}
			catch
			{
			}
		}
	}
}
namespace bHapticsLib.Internal.SimpleJSON
{
	internal enum JSONNodeType
	{
		Array = 1,
		Object = 2,
		String = 3,
		Number = 4,
		NullValue = 5,
		Boolean = 6,
		None = 7,
		Custom = 255
	}
	internal enum JSONTextMode
	{
		Compact,
		Indent
	}
	internal abstract class JSONNode
	{
		internal struct Enumerator
		{
			private enum Type
			{
				None,
				Array,
				Object
			}

			private Type type;

			private Dictionary<string, JSONNode>.Enumerator m_Object;

			private List<JSONNode>.Enumerator m_Array;

			internal bool IsValid => type != Type.None;

			internal KeyValuePair<string, JSONNode> Current
			{
				get
				{
					if (type == Type.Array)
					{
						return new KeyValuePair<string, JSONNode>(string.Empty, m_Array.Current);
					}
					if (type == Type.Object)
					{
						return m_Object.Current;
					}
					return new KeyValuePair<string, JSONNode>(string.Empty, null);
				}
			}

			internal Enumerator(List<JSONNode>.Enumerator aArrayEnum)
			{
				type = Type.Array;
				m_Object = default(Dictionary<string, JSONNode>.Enumerator);
				m_Array = aArrayEnum;
			}

			internal Enumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum)
			{
				type = Type.Object;
				m_Object = aDictEnum;
				m_Array = default(List<JSONNode>.Enumerator);
			}

			internal bool MoveNext()
			{
				if (type == Type.Array)
				{
					return m_Array.MoveNext();
				}
				if (type == Type.Object)
				{
					return m_Object.MoveNext();
				}
				return false;
			}
		}

		internal struct ValueEnumerator
		{
			private Enumerator m_Enumerator;

			internal JSONNode Current => m_Enumerator.Current.Value;

			internal ValueEnumerator(List<JSONNode>.Enumerator aArrayEnum)
				: this(new Enumerator(aArrayEnum))
			{
			}

			internal ValueEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum)
				: this(new Enumerator(aDictEnum))
			{
			}

			internal ValueEnumerator(Enumerator aEnumerator)
			{
				m_Enumerator = aEnumerator;
			}

			internal bool MoveNext()
			{
				return m_Enumerator.MoveNext();
			}

			internal ValueEnumerator GetEnumerator()
			{
				return this;
			}
		}

		internal struct KeyEnumerator
		{
			private Enumerator m_Enumerator;

			internal string Current => m_Enumerator.Current.Key;

			internal KeyEnumerator(List<JSONNode>.Enumerator aArrayEnum)
				: this(new Enumerator(aArrayEnum))
			{
			}

			internal KeyEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum)
				: this(new Enumerator(aDictEnum))
			{
			}

			internal KeyEnumerator(Enumerator aEnumerator)
			{
				m_Enumerator = aEnumerator;
			}

			internal bool MoveNext()
			{
				return m_Enumerator.MoveNext();
			}

			internal KeyEnumerator GetEnumerator()
			{
				return this;
			}
		}

		public class LinqEnumerator : IEnumerator<KeyValuePair<string, JSONNode>>, IDisposable, IEnumerator, IEnumerable<KeyValuePair<string, JSONNode>>, IEnumerable
		{
			private JSONNode m_Node;

			private Enumerator m_Enumerator;

			public KeyValuePair<string, JSONNode> Current => m_Enumerator.Current;

			object IEnumerator.Current => m_Enumerator.Current;

			internal LinqEnumerator(JSONNode aNode)
			{
				m_Node = aNode;
				if (m_Node != null)
				{
					m_Enumerator = m_Node.GetEnumerator();
				}
			}

			public bool MoveNext()
			{
				return m_Enumerator.MoveNext();
			}

			public void Dispose()
			{
				m_Node = null;
				m_Enumerator = default(Enumerator);
			}

			public IEnumerator<KeyValuePair<string, JSONNode>> GetEnumerator()
			{
				return new LinqEnumerator(m_Node);
			}

			public void Reset()
			{
				if (m_Node != null)
				{
					m_Enumerator = m_Node.GetEnumerator();
				}
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return new LinqEnumerator(m_Node);
			}
		}

		internal static bool forceASCII = false;

		internal static bool longAsString = false;

		internal static bool allowLineComments = true;

		[ThreadStatic]
		private static StringBuilder m_EscapeBuilder;

		internal abstract JSONNodeType Tag { get; }

		internal virtual JSONNode this[int aIndex]
		{
			get
			{
				return null;
			}
			set
			{
			}
		}

		internal virtual JSONNode this[string aKey]
		{
			get
			{
				return null;
			}
			set
			{
			}
		}

		internal virtual string Value
		{
			get
			{
				return "";
			}
			set
			{
			}
		}

		internal virtual int Count => 0;

		internal virtual bool IsNumber => false;

		internal virtual bool IsString => false;

		internal virtual bool IsBoolean => false;

		internal virtual bool IsNull => false;

		internal virtual bool IsArray => false;

		internal virtual bool IsObject => false;

		internal virtual bool Inline
		{
			get
			{
				return false;
			}
			set
			{
			}
		}

		internal virtual IEnumerable<JSONNode> Children
		{
			get
			{
				yield break;
			}
		}

		internal IEnumerable<JSONNode> DeepChildren
		{
			get
			{
				foreach (JSONNode child in Children)
				{
					foreach (JSONNode deepChild in child.DeepChildren)
					{
						yield return deepChild;
					}
				}
			}
		}

		internal IEnumerable<KeyValuePair<string, JSONNode>> Linq => new LinqEnumerator(this);

		internal KeyEnumerator Keys => new KeyEnumerator(GetEnumerator());

		internal ValueEnumerator Values => new ValueEnumerator(GetEnumerator());

		internal virtual double AsDouble
		{
			get
			{
				double result = 0.0;
				if (double.TryParse(Value, NumberStyles.Float, CultureInfo.InvariantCulture, out result))
				{
					return result;
				}
				return 0.0;
			}
			set
			{
				Value = value.ToString(CultureInfo.InvariantCulture);
			}
		}

		internal virtual int AsInt
		{
			get
			{
				return (int)AsDouble;
			}
			set
			{
				AsDouble = value;
			}
		}

		internal virtual float AsFloat
		{
			get
			{
				return (float)AsDouble;
			}
			set
			{
				AsDouble = value;
			}
		}

		internal virtual bool AsBool
		{
			get
			{
				bool result = false;
				if (bool.TryParse(Value, out result))
				{
					return result;
				}
				return !string.IsNullOrEmpty(Value);
			}
			set
			{
				Value = (value ? "true" : "false");
			}
		}

		internal virtual long AsLong
		{
			get
			{
				long result = 0L;
				if (long.TryParse(Value, out result))
				{
					return result;
				}
				return 0L;
			}
			set
			{
				Value = value.ToString();
			}
		}

		internal virtual JSONArray AsArray => this as JSONArray;

		internal virtual JSONObject AsObject => this as JSONObject;

		internal static StringBuilder EscapeBuilder
		{
			get
			{
				if (m_EscapeBuilder == null)
				{
					m_EscapeBuilder = new StringBuilder();
				}
				return m_EscapeBuilder;
			}
		}

		internal virtual void Add(string aKey, JSONNode aItem)
		{
		}

		internal virtual void Add(JSONNode aItem)
		{
			Add("", aItem);
		}

		internal virtual JSONNode Remove(string aKey)
		{
			return null;
		}

		internal virtual JSONNode Remove(int aIndex)
		{
			return null;
		}

		internal virtual JSONNode Remove(JSONNode aNode)
		{
			return aNode;
		}

		internal virtual bool HasKey(string aKey)
		{
			return false;
		}

		internal virtual JSONNode GetValueOrDefault(string aKey, JSONNode aDefault)
		{
			return aDefault;
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			WriteToStringBuilder(stringBuilder, 0, 0, JSONTextMode.Compact);
			return stringBuilder.ToString();
		}

		internal virtual string ToString(int aIndent)
		{
			StringBuilder stringBuilder = new StringBuilder();
			WriteToStringBuilder(stringBuilder, 0, aIndent, JSONTextMode.Indent);
			return stringBuilder.ToString();
		}

		internal abstract void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode);

		internal abstract Enumerator GetEnumerator();

		public static implicit operator JSONNode(string s)
		{
			return new JSONString(s);
		}

		public static implicit operator string(JSONNode d)
		{
			if (!(d == null))
			{
				return d.Value;
			}
			return null;
		}

		public static implicit operator JSONNode(double n)
		{
			return new JSONNumber(n);
		}

		public static implicit operator double(JSONNode d)
		{
			if (!(d == null))
			{
				return d.AsDouble;
			}
			return 0.0;
		}

		public static implicit operator JSONNode(float n)
		{
			return new JSONNumber(n);
		}

		public static implicit operator float(JSONNode d)
		{
			if (!(d == null))
			{
				return d.AsFloat;
			}
			return 0f;
		}

		public static implicit operator JSONNode(int n)
		{
			return new JSONNumber(n);
		}

		public static implicit operator int(JSONNode d)
		{
			if (!(d == null))
			{
				return d.AsInt;
			}
			return 0;
		}

		public static implicit operator JSONNode(long n)
		{
			if (longAsString)
			{
				return new JSONString(n.ToString());
			}
			return new JSONNumber(n);
		}

		public static implicit operator long(JSONNode d)
		{
			if (!(d == null))
			{
				return d.AsLong;
			}
			return 0L;
		}

		public static implicit operator JSONNode(bool b)
		{
			return new JSONBool(b);
		}

		public static implicit operator bool(JSONNode d)
		{
			if (!(d == null))
			{
				return d.AsBool;
			}
			return false;
		}

		public static implicit operator JSONNode(KeyValuePair<string, JSONNode> aKeyValue)
		{
			return aKeyValue.Value;
		}

		public static bool operator ==(JSONNode a, object b)
		{
			if ((object)a == b)
			{
				return true;
			}
			bool flag = a is JSONNull || (object)a == null || a is JSONLazyCreator;
			bool flag2 = b is JSONNull || b == null || b is JSONLazyCreator;
			if (flag && flag2)
			{
				return true;
			}
			if (!flag)
			{
				return a.Equals(b);
			}
			return false;
		}

		public static bool operator !=(JSONNode a, object b)
		{
			return !(a == b);
		}

		public override bool Equals(object obj)
		{
			return (object)this == obj;
		}

		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		internal static string Escape(string aText)
		{
			StringBuilder escapeBuilder = EscapeBuilder;
			escapeBuilder.Length = 0;
			if (escapeBuilder.Capacity < aText.Length + aText.Length / 10)
			{
				escapeBuilder.Capacity = aText.Length + aText.Length / 10;
			}
			foreach (char c in aText)
			{
				switch (c)
				{
				case '\\':
					escapeBuilder.Append("\\\\");
					continue;
				case '"':
					escapeBuilder.Append("\\\"");
					continue;
				case '\n':
					escapeBuilder.Append("\\n");
					continue;
				case '\r':
					escapeBuilder.Append("\\r");
					continue;
				case '\t':
					escapeBuilder.Append("\\t");
					continue;
				case '\b':
					escapeBuilder.Append("\\b");
					continue;
				case '\f':
					escapeBuilder.Append("\\f");
					continue;
				}
				if (c < ' ' || (forceASCII && c > '\u007f'))
				{
					ushort num = c;
					escapeBuilder.Append("\\u").Append(num.ToString("X4"));
				}
				else
				{
					escapeBuilder.Append(c);
				}
			}
			string result = escapeBuilder.ToString();
			escapeBuilder.Length = 0;
			return result;
		}

		private static JSONNode ParseElement(string token, bool quoted)
		{
			if (quoted)
			{
				return token;
			}
			string text = token.ToLower();
			switch (text)
			{
			case "false":
			case "true":
				return text == "true";
			case "null":
				return JSONNull.CreateOrGet();
			default:
			{
				if (double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					return result;
				}
				return token;
			}
			}
		}

		internal static JSONNode Parse(string aJSON)
		{
			Stack<JSONNode> stack = new Stack<JSONNode>();
			JSONNode jSONNode = null;
			int i = 0;
			StringBuilder stringBuilder = new StringBuilder();
			string aKey = "";
			bool flag = false;
			bool flag2 = false;
			for (; i < aJSON.Length; i++)
			{
				switch (aJSON[i])
				{
				case '{':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
						break;
					}
					stack.Push(new JSONObject());
					if (jSONNode != null)
					{
						jSONNode.Add(aKey, stack.Peek());
					}
					aKey = "";
					stringBuilder.Length = 0;
					jSONNode = stack.Peek();
					break;
				case '[':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
						break;
					}
					stack.Push(new JSONArray());
					if (jSONNode != null)
					{
						jSONNode.Add(aKey, stack.Peek());
					}
					aKey = "";
					stringBuilder.Length = 0;
					jSONNode = stack.Peek();
					break;
				case ']':
				case '}':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
						break;
					}
					if (stack.Count == 0)
					{
						throw new Exception("JSON Parse: Too many closing brackets");
					}
					stack.Pop();
					if (stringBuilder.Length > 0 || flag2)
					{
						jSONNode.Add(aKey, ParseElement(stringBuilder.ToString(), flag2));
					}
					flag2 = false;
					aKey = "";
					stringBuilder.Length = 0;
					if (stack.Count > 0)
					{
						jSONNode = stack.Peek();
					}
					break;
				case ':':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
						break;
					}
					aKey = stringBuilder.ToString();
					stringBuilder.Length = 0;
					flag2 = false;
					break;
				case '"':
					flag = !flag;
					flag2 = flag2 || flag;
					break;
				case ',':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
						break;
					}
					if (stringBuilder.Length > 0 || flag2)
					{
						jSONNode.Add(aKey, ParseElement(stringBuilder.ToString(), flag2));
					}
					flag2 = false;
					aKey = "";
					stringBuilder.Length = 0;
					flag2 = false;
					break;
				case '\t':
				case ' ':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
					}
					break;
				case '\\':
					i++;
					if (flag)
					{
						char c = aJSON[i];
						switch (c)
						{
						case 't':
							stringBuilder.Append('\t');
							break;
						case 'r':
							stringBuilder.Append('\r');
							break;
						case 'n':
							stringBuilder.Append('\n');
							break;
						case 'b':
							stringBuilder.Append('\b');
							break;
						case 'f':
							stringBuilder.Append('\f');
							break;
						case 'u':
						{
							string s = aJSON.Substring(i + 1, 4);
							stringBuilder.Append((char)int.Parse(s, NumberStyles.AllowHexSpecifier));
							i += 4;
							break;
						}
						default:
							stringBuilder.Append(c);
							break;
						}
					}
					break;
				case '/':
					if (allowLineComments && !flag && i + 1 < aJSON.Length && aJSON[i + 1] == '/')
					{
						while (++i < aJSON.Length && aJSON[i] != '\n' && aJSON[i] != '\r')
						{
						}
					}
					else
					{
						stringBuilder.Append(aJSON[i]);
					}
					break;
				default:
					stringBuilder.Append(aJSON[i]);
					break;
				case '\n':
				case '\r':
				case '\ufeff':
					break;
				}
			}
			if (flag)
			{
				throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
			}
			if (jSONNode == null)
			{
				return ParseElement(stringBuilder.ToString(), flag2);
			}
			return jSONNode;
		}
	}
	internal class JSONArray : JSONNode
	{
		private List<JSONNode> m_List = new List<JSONNode>();

		private bool inline;

		internal override bool Inline
		{
			get
			{
				return inline;
			}
			set
			{
				inline = value;
			}
		}

		internal override JSONNodeType Tag => JSONNodeType.Array;

		internal override bool IsArray => true;

		internal override JSONNode this[int aIndex]
		{
			get
			{
				if (aIndex < 0 || aIndex >= m_List.Count)
				{
					return new JSONLazyCreator(this);
				}
				return m_List[aIndex];
			}
			set
			{
				if (value == null)
				{
					value = JSONNull.CreateOrGet();
				}
				if (aIndex < 0 || aIndex >= m_List.Count)
				{
					m_List.Add(value);
				}
				else
				{
					m_List[aIndex] = value;
				}
			}
		}

		internal override JSONNode this[string aKey]
		{
			get
			{
				return new JSONLazyCreator(this);
			}
			set
			{
				if (value == null)
				{
					value = JSONNull.CreateOrGet();
				}
				m_List.Add(value);
			}
		}

		internal override int Count => m_List.Count;

		internal override IEnumerable<JSONNode> Children
		{
			get
			{
				foreach (JSONNode item in m_List)
				{
					yield return item;
				}
			}
		}

		internal override Enumerator GetEnumerator()
		{
			return new Enumerator(m_List.GetEnumerator());
		}

		internal override void Add(string aKey, JSONNode aItem)
		{
			if (aItem == null)
			{
				aItem = JSONNull.CreateOrGet();
			}
			m_List.Add(aItem);
		}

		internal override JSONNode Remove(int aIndex)
		{
			if (aIndex < 0 || aIndex >= m_List.Count)
			{
				return null;
			}
			JSONNode result = m_List[aIndex];
			m_List.RemoveAt(aIndex);
			return result;
		}

		internal override JSONNode Remove(JSONNode aNode)
		{
			m_List.Remove(aNode);
			return aNode;
		}

		internal void Clear()
		{
			m_List.Clear();
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append('[');
			int count = m_List.Count;
			if (inline)
			{
				aMode = JSONTextMode.Compact;
			}
			for (int i = 0; i < count; i++)
			{
				if (i > 0)
				{
					aSB.Append(',');
				}
				if (aMode == JSONTextMode.Indent)
				{
					aSB.AppendLine();
				}
				if (aMode == JSONTextMode.Indent)
				{
					aSB.Append(' ', aIndent + aIndentInc);
				}
				m_List[i].WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
			}
			if (aMode == JSONTextMode.Indent)
			{
				aSB.AppendLine().Append(' ', aIndent);
			}
			aSB.Append(']');
		}
	}
	internal class JSONObject : JSONNode
	{
		internal Dictionary<string, JSONNode> m_Dict = new Dictionary<string, JSONNode>();

		private bool inline;

		internal override bool Inline
		{
			get
			{
				return inline;
			}
			set
			{
				inline = value;
			}
		}

		internal override JSONNodeType Tag => JSONNodeType.Object;

		internal override bool IsObject => true;

		internal override JSONNode this[string aKey]
		{
			get
			{
				if (m_Dict.ContainsKey(aKey))
				{
					return m_Dict[aKey];
				}
				return new JSONLazyCreator(this, aKey);
			}
			set
			{
				if (value == null)
				{
					value = JSONNull.CreateOrGet();
				}
				if (m_Dict.ContainsKey(aKey))
				{
					m_Dict[aKey] = value;
				}
				else
				{
					m_Dict.Add(aKey, value);
				}
			}
		}

		internal override JSONNode this[int aIndex]
		{
			get
			{
				if (aIndex < 0 || aIndex >= m_Dict.Count)
				{
					return null;
				}
				return m_Dict.ElementAt(aIndex).Value;
			}
			set
			{
				if (value == null)
				{
					value = JSONNull.CreateOrGet();
				}
				if (aIndex >= 0 && aIndex < m_Dict.Count)
				{
					string key = m_Dict.ElementAt(aIndex).Key;
					m_Dict[key] = value;
				}
			}
		}

		internal override int Count => m_Dict.Count;

		internal override IEnumerable<JSONNode> Children
		{
			get
			{
				foreach (KeyValuePair<string, JSONNode> item in m_Dict)
				{
					yield return item.Value;
				}
			}
		}

		internal override Enumerator GetEnumerator()
		{
			return new Enumerator(m_Dict.GetEnumerator());
		}

		internal override void Add(string aKey, JSONNode aItem)
		{
			if (aItem == null)
			{
				aItem = JSONNull.CreateOrGet();
			}
			if (aKey != null)
			{
				if (m_Dict.ContainsKey(aKey))
				{
					m_Dict[aKey] = aItem;
				}
				else
				{
					m_Dict.Add(aKey, aItem);
				}
			}
			else
			{
				m_Dict.Add(Guid.NewGuid().ToString(), aItem);
			}
		}

		internal override JSONNode Remove(string aKey)
		{
			if (!m_Dict.ContainsKey(aKey))
			{
				return null;
			}
			JSONNode result = m_Dict[aKey];
			m_Dict.Remove(aKey);
			return result;
		}

		internal override JSONNode Remove(int aIndex)
		{
			if (aIndex < 0 || aIndex >= m_Dict.Count)
			{
				return null;
			}
			KeyValuePair<string, JSONNode> keyValuePair = m_Dict.ElementAt(aIndex);
			m_Dict.Remove(keyValuePair.Key);
			return keyValuePair.Value;
		}

		internal override JSONNode Remove(JSONNode aNode)
		{
			try
			{
				KeyValuePair<string, JSONNode> keyValuePair = m_Dict.Where((KeyValuePair<string, JSONNode> k) => k.Value == aNode).First();
				m_Dict.Remove(keyValuePair.Key);
				return aNode;
			}
			catch
			{
				return null;
			}
		}

		internal override bool HasKey(string aKey)
		{
			return m_Dict.ContainsKey(aKey);
		}

		internal override JSONNode GetValueOrDefault(string aKey, JSONNode aDefault)
		{
			if (m_Dict.TryGetValue(aKey, out var value))
			{
				return value;
			}
			return aDefault;
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append('{');
			bool flag = true;
			if (inline)
			{
				aMode = JSONTextMode.Compact;
			}
			foreach (KeyValuePair<string, JSONNode> item in m_Dict)
			{
				if (!flag)
				{
					aSB.Append(',');
				}
				flag = false;
				if (aMode == JSONTextMode.Indent)
				{
					aSB.AppendLine();
				}
				if (aMode == JSONTextMode.Indent)
				{
					aSB.Append(' ', aIndent + aIndentInc);
				}
				aSB.Append('"').Append(JSONNode.Escape(item.Key)).Append('"');
				if (aMode == JSONTextMode.Compact)
				{
					aSB.Append(':');
				}
				else
				{
					aSB.Append(" : ");
				}
				item.Value.WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
			}
			if (aMode == JSONTextMode.Indent)
			{
				aSB.AppendLine().Append(' ', aIndent);
			}
			aSB.Append('}');
		}
	}
	internal class JSONString : JSONNode
	{
		private string m_Data;

		internal override JSONNodeType Tag => JSONNodeType.String;

		internal override bool IsString => true;

		internal override string Value
		{
			get
			{
				return m_Data;
			}
			set
			{
				m_Data = value;
			}
		}

		internal override Enumerator GetEnumerator()
		{
			return default(Enumerator);
		}

		internal JSONString(string aData)
		{
			m_Data = aData;
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append('"').Append(JSONNode.Escape(m_Data)).Append('"');
		}

		public override bool Equals(object obj)
		{
			if (base.Equals(obj))
			{
				return true;
			}
			if (obj is string text)
			{
				return m_Data == text;
			}
			JSONString jSONString = obj as JSONString;
			if (jSONString != null)
			{
				return m_Data == jSONString.m_Data;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return m_Data.GetHashCode();
		}
	}
	internal class JSONNumber : JSONNode
	{
		private double m_Data;

		internal override JSONNodeType Tag => JSONNodeType.Number;

		internal override bool IsNumber => true;

		internal override string Value
		{
			get
			{
				return m_Data.ToString(CultureInfo.InvariantCulture);
			}
			set
			{
				if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					m_Data = result;
				}
			}
		}

		internal override double AsDouble
		{
			get
			{
				return m_Data;
			}
			set
			{
				m_Data = value;
			}
		}

		internal override long AsLong
		{
			get
			{
				return (long)m_Data;
			}
			set
			{
				m_Data = value;
			}
		}

		internal override Enumerator GetEnumerator()
		{
			return default(Enumerator);
		}

		internal JSONNumber(double aData)
		{
			m_Data = aData;
		}

		internal JSONNumber(string aData)
		{
			Value = aData;
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append(Value);
		}

		private static bool IsNumeric(object value)
		{
			if (!(value is int) && !(value is uint) && !(value is float) && !(value is double) && !(value is decimal) && !(value is long) && !(value is ulong) && !(value is short) && !(value is ushort) && !(value is sbyte))
			{
				return value is byte;
			}
			return true;
		}

		public override bool Equals(object obj)
		{
			if (obj == null)
			{
				return false;
			}
			if (base.Equals(obj))
			{
				return true;
			}
			JSONNumber jSONNumber = obj as JSONNumber;
			if (jSONNumber != null)
			{
				return m_Data == jSONNumber.m_Data;
			}
			if (IsNumeric(obj))
			{
				return Convert.ToDouble(obj) == m_Data;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return m_Data.GetHashCode();
		}
	}
	internal class JSONBool : JSONNode
	{
		private bool m_Data;

		internal override JSONNodeType Tag => JSONNodeType.Boolean;

		internal override bool IsBoolean => true;

		internal override string Value
		{
			get
			{
				return m_Data.ToString();
			}
			set
			{
				if (bool.TryParse(value, out var result))
				{
					m_Data = result;
				}
			}
		}

		internal override bool AsBool
		{
			get
			{
				return m_Data;
			}
			set
			{
				m_Data = value;
			}
		}

		internal override Enumerator GetEnumerator()
		{
			return default(Enumerator);
		}

		internal JSONBool(bool aData)
		{
			m_Data = aData;
		}

		internal JSONBool(string aData)
		{
			Value = aData;
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append(m_Data ? "true" : "false");
		}

		public override bool Equals(object obj)
		{
			if (obj == null)
			{
				return false;
			}
			if (obj is bool)
			{
				return m_Data == (bool)obj;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return m_Data.GetHashCode();
		}
	}
	internal class JSONNull : JSONNode
	{
		private static JSONNull m_StaticInstance = new JSONNull();

		internal static bool reuseSameInstance = true;

		internal override JSONNodeType Tag => JSONNodeType.NullValue;

		internal override bool IsNull => true;

		internal override string Value
		{
			get
			{
				return "null";
			}
			set
			{
			}
		}

		internal override bool AsBool
		{
			get
			{
				return false;
			}
			set
			{
			}
		}

		internal static JSONNull CreateOrGet()
		{
			if (reuseSameInstance)
			{
				return m_StaticInstance;
			}
			return new JSONNull();
		}

		private JSONNull()
		{
		}

		internal override Enumerator GetEnumerator()
		{
			return default(Enumerator);
		}

		public override bool Equals(object obj)
		{
			if ((object)this == obj)
			{
				return true;
			}
			return obj is JSONNull;
		}

		public override int GetHashCode()
		{
			return 0;
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append("null");
		}
	}
	internal class JSONLazyCreator : JSONNode
	{
		private JSONNode m_Node;

		private string m_Key;

		internal override JSONNodeType Tag => JSONNodeType.None;

		internal override JSONNode this[int aIndex]
		{
			get
			{
				return new JSONLazyCreator(this);
			}
			set
			{
				Set(new JSONArray()).Add(value);
			}
		}

		internal override JSONNode this[string aKey]
		{
			get
			{
				return new JSONLazyCreator(this, aKey);
			}
			set
			{
				Set(new JSONObject()).Add(aKey, value);
			}
		}

		internal override int AsInt
		{
			get
			{
				Set(new JSONNumber(0.0));
				return 0;
			}
			set
			{
				Set(new JSONNumber(value));
			}
		}

		internal override float AsFloat
		{
			get
			{
				Set(new JSONNumber(0.0));
				return 0f;
			}
			set
			{
				Set(new JSONNumber(value));
			}
		}

		internal override double AsDouble
		{
			get
			{
				Set(new JSONNumber(0.0));
				return 0.0;
			}
			set
			{
				Set(new JSONNumber(value));
			}
		}

		internal override long AsLong
		{
			get
			{
				if (JSONNode.longAsString)
				{
					Set(new JSONString("0"));
				}
				else
				{
					Set(new JSONNumber(0.0));
				}
				return 0L;
			}
			set
			{
				if (JSONNode.longAsString)
				{
					Set(new JSONString(value.ToString()));
				}
				else
				{
					Set(new JSONNumber(value));
				}
			}
		}

		internal override bool AsBool
		{
			get
			{
				Set(new JSONBool(aData: false));
				return false;
			}
			set
			{
				Set(new JSONBool(value));
			}
		}

		internal override JSONArray AsArray => Set(new JSONArray());

		internal override JSONObject AsObject => Set(new JSONObject());

		internal override Enumerator GetEnumerator()
		{
			return default(Enumerator);
		}

		internal JSONLazyCreator(JSONNode aNode)
		{
			m_Node = aNode;
			m_Key = null;
		}

		internal JSONLazyCreator(JSONNode aNode, string aKey)
		{
			m_Node = aNode;
			m_Key = aKey;
		}

		private T Set<T>(T aVal) where T : JSONNode
		{
			if (m_Key == null)
			{
				m_Node.Add(aVal);
			}
			else
			{
				m_Node.Add(m_Key, aVal);
			}
			m_Node = null;
			return aVal;
		}

		internal override void Add(JSONNode aItem)
		{
			Set(new JSONArray()).Add(aItem);
		}

		internal override void Add(string aKey, JSONNode aItem)
		{
			Set(new JSONObject()).Add(aKey, aItem);
		}

		public static bool operator ==(JSONLazyCreator a, object b)
		{
			if (b == null)
			{
				return true;
			}
			return (object)a == b;
		}

		public static bool operator !=(JSONLazyCreator a, object b)
		{
			return !(a == b);
		}

		public override bool Equals(object obj)
		{
			if (obj == null)
			{
				return true;
			}
			return (object)this == obj;
		}

		public override int GetHashCode()
		{
			return 0;
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append("null");
		}
	}
	internal static class JSON
	{
		internal static JSONNode Parse(string aJSON)
		{
			return JSONNode.Parse(aJSON);
		}
	}
}
namespace bHapticsLib.Internal.Models.Connection
{
	internal class PlayerPacket : JSONObject
	{
		internal JSONArray Register
		{
			get
			{
				string aKey = "Register";
				if (this[aKey] == null)
				{
					this[aKey] = new JSONArray();
				}
				return this[aKey].AsArray;
			}
		}

		internal JSONArray Submit
		{
			get
			{
				string aKey = "Submit";
				if (this[aKey] == null)
				{
					this[aKey] = new JSONArray();
				}
				return this[aKey].AsArray;
			}
		}

		internal void Clear()
		{
			Register.Clear();
			Submit.Clear();
		}

		internal bool IsEmpty()
		{
			if (Register.Count <= 0)
			{
				return Submit.Count <= 0;
			}
			return false;
		}
	}
	internal class PlayerResponse : JSONObject
	{
		internal int ConnectedDeviceCount => this["ConnectedDeviceCount"].AsInt;

		internal JSONArray ActiveKeys
		{
			get
			{
				string aKey = "ActiveKeys";
				if (this[aKey] == null)
				{
					this[aKey] = new JSONArray();
				}
				return this[aKey].AsArray;
			}
		}

		internal JSONArray ConnectedPositions
		{
			get
			{
				string aKey = "ConnectedPositions";
				if (this[aKey] == null)
				{
					this[aKey] = new JSONArray();
				}
				return this[aKey].AsArray;
			}
		}

		internal JSONArray RegisteredKeys
		{
			get
			{
				string aKey = "RegisteredKeys";
				if (this[aKey] == null)
				{
					this[aKey] = new JSONArray();
				}
				return this[aKey].AsArray;
			}
		}

		internal JSONObject Status
		{
			get
			{
				string aKey = "Status";
				if (this[aKey] == null)
				{
					this[aKey] = new JSONObject();
				}
				return this[aKey].AsObject;
			}
		}
	}
	internal class RegisterRequest : JSONObject
	{
		internal string key
		{
			get
			{
				return this["key"];
			}
			set
			{
				this["key"] = value;
			}
		}

		internal JSONObject project
		{
			get
			{
				string aKey = "project";
				if (this[aKey] == null)
				{
					this[aKey] = new JSONObject();
				}
				return this[aKey].AsObject;
			}
			set
			{
				this["project"] = value;
			}
		}
	}
	internal class SubmitRequest : JSONObject
	{
		internal string type
		{
			get
			{
				return this["type"];
			}
			set
			{
				this["type"] = value;
			}
		}

		internal string key
		{
			get
			{
				return this["key"];
			}
			set
			{
				this["key"] = value;
			}
		}

		internal JSONObject Parameters
		{
			get
			{
				string aKey = "Parameters";
				if (this[aKey] == null)
				{
					this[aKey] = new JSONObject();
				}
				return this[aKey].AsObject;
			}
		}

		internal SubmitRequestFrame Frame
		{
			get
			{
				string aKey = "Frame";
				if (this[aKey] == null)
				{
					this[aKey] = new SubmitRequestFrame();
				}
				return this[aKey].AsObject as SubmitRequestFrame;
			}
		}
	}
	internal class SubmitRequestFrame : JSONObject
	{
		internal int durationMillis
		{
			get
			{
				return this["durationMillis"].AsInt;
			}
			set
			{
				this["durationMillis"] = value;
			}
		}

		internal string position
		{
			get
			{
				return this["position"];
			}
			set
			{
				this["position"] = value.ToString();
			}
		}

		internal JSONArray dotPoints
		{
			get
			{
				string aKey = "dotPoints";
				if (this[aKey] == null)
				{
					this[aKey] = new JSONArray();
				}
				return this[aKey].AsArray;
			}
		}

		internal JSONArray pathPoints
		{
			get
			{
				string aKey = "pathPoints";
				if (this[aKey] == null)
				{
					this[aKey] = new JSONArray();
				}
				return this[aKey].AsArray;
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/BepInEx.MelonLoader.Loader/MelonLoader.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using AssetRipper.VersionUtilities;
using AssetsTools.NET;
using AssetsTools.NET.Extra;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Harmony;
using HarmonyLib;
using HarmonyLib.Public.Patching;
using HarmonyLib.Tools;
using MelonLoader;
using MelonLoader.Assertions;
using MelonLoader.Fixes;
using MelonLoader.ICSharpCode.SharpZipLib.BZip2;
using MelonLoader.ICSharpCode.SharpZipLib.Checksum;
using MelonLoader.ICSharpCode.SharpZipLib.Core;
using MelonLoader.ICSharpCode.SharpZipLib.Encryption;
using MelonLoader.ICSharpCode.SharpZipLib.Zip;
using MelonLoader.ICSharpCode.SharpZipLib.Zip.Compression;
using MelonLoader.ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using MelonLoader.InternalUtils;
using MelonLoader.Lemons.Cryptography;
using MelonLoader.Modules;
using MelonLoader.MonoInternals;
using MelonLoader.MonoInternals.ResolveInternals;
using MelonLoader.Preferences;
using MelonLoader.Preferences.IO;
using MelonLoader.TinyJSON;
using Microsoft.Cci;
using Microsoft.CodeAnalysis;
using Microsoft.Win32;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Mdb;
using Mono.Cecil.Pdb;
using Mono.Cecil.Rocks;
using Mono.Collections.Generic;
using Mono.CompilerServices.SymbolWriter;
using MonoMod.Cil;
using MonoMod.ModInterop;
using MonoMod.RuntimeDetour;
using MonoMod.RuntimeDetour.HookGen;
using MonoMod.RuntimeDetour.Platforms;
using MonoMod.Utils;
using MonoMod.Utils.Cil;
using Semver;
using Tomlet;
using Tomlet.Attributes;
using Tomlet.Exceptions;
using Tomlet.Models;
using bHapticsLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("MelonLoader")]
[assembly: AssemblyDescription("MelonLoader")]
[assembly: AssemblyCompany("discord.gg/2Wn3N2P")]
[assembly: AssemblyProduct("MelonLoader")]
[assembly: AssemblyCopyright("Created by Lava Gang")]
[assembly: AssemblyTrademark("discord.gg/2Wn3N2P")]
[assembly: Guid("A662769A-B294-434F-83B5-176FC4795334")]
[assembly: AssemblyFileVersion("0.5.7")]
[assembly: PatchShield]
[assembly: InternalsVisibleTo("BepInEx.MelonLoader.Loader.UnityMono")]
[assembly: InternalsVisibleTo("BepInEx.MelonLoader.Loader.IL2CPP")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.5.7.0")]
[assembly: TypeForwardedTo(typeof(AccessTools))]
[assembly: TypeForwardedTo(typeof(ArgumentType))]
[assembly: TypeForwardedTo(typeof(CodeInstruction))]
[assembly: TypeForwardedTo(typeof(CodeInstructionExtensions))]
[assembly: TypeForwardedTo(typeof(CodeMatch))]
[assembly: TypeForwardedTo(typeof(CodeMatcher))]
[assembly: TypeForwardedTo(typeof(CollectionExtensions))]
[assembly: TypeForwardedTo(typeof(DelegateTypeFactory))]
[assembly: TypeForwardedTo(typeof(ExceptionBlock))]
[assembly: TypeForwardedTo(typeof(ExceptionBlockType))]
[assembly: TypeForwardedTo(typeof(FastAccess))]
[assembly: TypeForwardedTo(typeof(FastInvokeHandler))]
[assembly: TypeForwardedTo(typeof(FileLog))]
[assembly: TypeForwardedTo(typeof(GeneralExtensions))]
[assembly: TypeForwardedTo(typeof(GetterHandler<, >))]
[assembly: TypeForwardedTo(typeof(Harmony))]
[assembly: TypeForwardedTo(typeof(HarmonyAfter))]
[assembly: TypeForwardedTo(typeof(HarmonyArgument))]
[assembly: TypeForwardedTo(typeof(HarmonyAttribute))]
[assembly: TypeForwardedTo(typeof(HarmonyBefore))]
[assembly: TypeForwardedTo(typeof(HarmonyCleanup))]
[assembly: TypeForwardedTo(typeof(HarmonyDebug))]
[assembly: TypeForwardedTo(typeof(HarmonyDelegate))]
[assembly: TypeForwardedTo(typeof(HarmonyEmitIL))]
[assembly: TypeForwardedTo(typeof(HarmonyException))]
[assembly: TypeForwardedTo(typeof(HarmonyFinalizer))]
[assembly: TypeForwardedTo(typeof(HarmonyGlobalSettings))]
[assembly: TypeForwardedTo(typeof(HarmonyILManipulator))]
[assembly: TypeForwardedTo(typeof(HarmonyMethod))]
[assembly: TypeForwardedTo(typeof(HarmonyMethodExtensions))]
[assembly: TypeForwardedTo(typeof(HarmonyPatch))]
[assembly: TypeForwardedTo(typeof(HarmonyPatchAll))]
[assembly: TypeForwardedTo(typeof(HarmonyPatchType))]
[assembly: TypeForwardedTo(typeof(HarmonyPostfix))]
[assembly: TypeForwardedTo(typeof(HarmonyPrefix))]
[assembly: TypeForwardedTo(typeof(HarmonyPrepare))]
[assembly: TypeForwardedTo(typeof(HarmonyPriority))]
[assembly: TypeForwardedTo(typeof(HarmonyReversePatch))]
[assembly: TypeForwardedTo(typeof(HarmonyReversePatchType))]
[assembly: TypeForwardedTo(typeof(HarmonyTargetMethod))]
[assembly: TypeForwardedTo(typeof(HarmonyTargetMethods))]
[assembly: TypeForwardedTo(typeof(HarmonyTranspiler))]
[assembly: TypeForwardedTo(typeof(HarmonyWrapSafe))]
[assembly: TypeForwardedTo(typeof(InlineSignature))]
[assembly: TypeForwardedTo(typeof(InstantiationHandler<>))]
[assembly: TypeForwardedTo(typeof(InvalidHarmonyPatchArgumentException))]
[assembly: TypeForwardedTo(typeof(MemberNotFoundException))]
[assembly: TypeForwardedTo(typeof(MethodBaseExtensions))]
[assembly: TypeForwardedTo(typeof(MethodDispatchType))]
[assembly: TypeForwardedTo(typeof(MethodInvoker))]
[assembly: TypeForwardedTo(typeof(MethodType))]
[assembly: TypeForwardedTo(typeof(Patch))]
[assembly: TypeForwardedTo(typeof(PatchClassProcessor))]
[assembly: TypeForwardedTo(typeof(Patches))]
[assembly: TypeForwardedTo(typeof(PatchInfo))]
[assembly: TypeForwardedTo(typeof(PatchProcessor))]
[assembly: TypeForwardedTo(typeof(Priority))]
[assembly: TypeForwardedTo(typeof(HarmonyManipulator))]
[assembly: TypeForwardedTo(typeof(ManagedMethodPatcher))]
[assembly: TypeForwardedTo(typeof(MethodPatcher))]
[assembly: TypeForwardedTo(typeof(NativeDetourMethodPatcher))]
[assembly: TypeForwardedTo(typeof(PatchManager))]
[assembly: TypeForwardedTo(typeof(ReversePatcher))]
[assembly: TypeForwardedTo(typeof(SetterHandler<, >))]
[assembly: TypeForwardedTo(typeof(SymbolExtensions))]
[assembly: TypeForwardedTo(typeof(HarmonyFileLog))]
[assembly: TypeForwardedTo(typeof(Logger))]
[assembly: TypeForwardedTo(typeof(Transpilers))]
[assembly: TypeForwardedTo(typeof(Traverse))]
[assembly: TypeForwardedTo(typeof(Traverse<>))]
[assembly: TypeForwardedTo(typeof(ILocalScope))]
[assembly: TypeForwardedTo(typeof(IName))]
[assembly: TypeForwardedTo(typeof(INamespaceScope))]
[assembly: TypeForwardedTo(typeof(IUsedNamespace))]
[assembly: TypeForwardedTo(typeof(ArrayDimension))]
[assembly: TypeForwardedTo(typeof(ArrayMarshalInfo))]
[assembly: TypeForwardedTo(typeof(ArrayType))]
[assembly: TypeForwardedTo(typeof(AssemblyAttributes))]
[assembly: TypeForwardedTo(typeof(AssemblyDefinition))]
[assembly: TypeForwardedTo(typeof(AssemblyHashAlgorithm))]
[assembly: TypeForwardedTo(typeof(AssemblyLinkedResource))]
[assembly: TypeForwardedTo(typeof(AssemblyNameDefinition))]
[assembly: TypeForwardedTo(typeof(AssemblyNameReference))]
[assembly: TypeForwardedTo(typeof(AssemblyResolutionException))]
[assembly: TypeForwardedTo(typeof(AssemblyResolveEventArgs))]
[assembly: TypeForwardedTo(typeof(AssemblyResolveEventHandler))]
[assembly: TypeForwardedTo(typeof(BaseAssemblyResolver))]
[assembly: TypeForwardedTo(typeof(ByReferenceType))]
[assembly: TypeForwardedTo(typeof(CallSite))]
[assembly: TypeForwardedTo(typeof(AsyncMethodBodyDebugInformation))]
[assembly: TypeForwardedTo(typeof(BinaryCustomDebugInformation))]
[assembly: TypeForwardedTo(typeof(Code))]
[assembly: TypeForwardedTo(typeof(ConstantDebugInformation))]
[assembly: TypeForwardedTo(typeof(CustomDebugInformation))]
[assembly: TypeForwardedTo(typeof(CustomDebugInformationKind))]
[assembly: TypeForwardedTo(typeof(DebugInformation))]
[assembly: TypeForwardedTo(typeof(DefaultSymbolReaderProvider))]
[assembly: TypeForwardedTo(typeof(DefaultSymbolWriterProvider))]
[assembly: TypeForwardedTo(typeof(Document))]
[assembly: TypeForwardedTo(typeof(DocumentHashAlgorithm))]
[assembly: TypeForwardedTo(typeof(DocumentLanguage))]
[assembly: TypeForwardedTo(typeof(DocumentLanguageVendor))]
[assembly: TypeForwardedTo(typeof(DocumentType))]
[assembly: TypeForwardedTo(typeof(EmbeddedPortablePdbReader))]
[assembly: TypeForwardedTo(typeof(EmbeddedPortablePdbReaderProvider))]
[assembly: TypeForwardedTo(typeof(EmbeddedPortablePdbWriter))]
[assembly: TypeForwardedTo(typeof(EmbeddedPortablePdbWriterProvider))]
[assembly: TypeForwardedTo(typeof(EmbeddedSourceDebugInformation))]
[assembly: TypeForwardedTo(typeof(ExceptionHandler))]
[assembly: TypeForwardedTo(typeof(ExceptionHandlerType))]
[assembly: TypeForwardedTo(typeof(FlowControl))]
[assembly: TypeForwardedTo(typeof(ICustomDebugInformationProvider))]
[assembly: TypeForwardedTo(typeof(ILProcessor))]
[assembly: TypeForwardedTo(typeof(ImageDebugDirectory))]
[assembly: TypeForwardedTo(typeof(ImageDebugHeader))]
[assembly: TypeForwardedTo(typeof(ImageDebugHeaderEntry))]
[assembly: TypeForwardedTo(typeof(ImageDebugType))]
[assembly: TypeForwardedTo(typeof(ImportDebugInformation))]
[assembly: TypeForwardedTo(typeof(ImportTarget))]
[assembly: TypeForwardedTo(typeof(ImportTargetKind))]
[assembly: TypeForwardedTo(typeof(Instruction))]
[assembly: TypeForwardedTo(typeof(InstructionOffset))]
[assembly: TypeForwardedTo(typeof(ISymbolReader))]
[assembly: TypeForwardedTo(typeof(ISymbolReaderProvider))]
[assembly: TypeForwardedTo(typeof(ISymbolWriter))]
[assembly: TypeForwardedTo(typeof(ISymbolWriterProvider))]
[assembly: TypeForwardedTo(typeof(MethodBody))]
[assembly: TypeForwardedTo(typeof(MethodDebugInformation))]
[assembly: TypeForwardedTo(typeof(OpCode))]
[assembly: TypeForwardedTo(typeof(OpCodes))]
[assembly: TypeForwardedTo(typeof(OpCodeType))]
[assembly: TypeForwardedTo(typeof(OperandType))]
[assembly: TypeForwardedTo(typeof(PortablePdbReader))]
[assembly: TypeForwardedTo(typeof(PortablePdbReaderProvider))]
[assembly: TypeForwardedTo(typeof(PortablePdbWriter))]
[assembly: TypeForwardedTo(typeof(PortablePdbWriterProvider))]
[assembly: TypeForwardedTo(typeof(ScopeDebugInformation))]
[assembly: TypeForwardedTo(typeof(SequencePoint))]
[assembly: TypeForwardedTo(typeof(SourceLinkDebugInformation))]
[assembly: TypeForwardedTo(typeof(StackBehaviour))]
[assembly: TypeForwardedTo(typeof(StateMachineScope))]
[assembly: TypeForwardedTo(typeof(StateMachineScopeDebugInformation))]
[assembly: TypeForwardedTo(typeof(SymbolsNotFoundException))]
[assembly: TypeForwardedTo(typeof(SymbolsNotMatchingException))]
[assembly: TypeForwardedTo(typeof(VariableAttributes))]
[assembly: TypeForwardedTo(typeof(VariableDebugInformation))]
[assembly: TypeForwardedTo(typeof(VariableDefinition))]
[assembly: TypeForwardedTo(typeof(VariableIndex))]
[assembly: TypeForwardedTo(typeof(VariableReference))]
[assembly: TypeForwardedTo(typeof(CustomAttribute))]
[assembly: TypeForwardedTo(typeof(CustomAttributeArgument))]
[assembly: TypeForwardedTo(typeof(CustomAttributeNamedArgument))]
[assembly: TypeForwardedTo(typeof(CustomMarshalInfo))]
[assembly: TypeForwardedTo(typeof(DefaultAssemblyResolver))]
[assembly: TypeForwardedTo(typeof(DefaultMetadataImporter))]
[assembly: TypeForwardedTo(typeof(DefaultReflectionImporter))]
[assembly: TypeForwardedTo(typeof(EmbeddedResource))]
[assembly: TypeForwardedTo(typeof(EventAttributes))]
[assembly: TypeForwardedTo(typeof(EventDefinition))]
[assembly: TypeForwardedTo(typeof(EventReference))]
[assembly: TypeForwardedTo(typeof(ExportedType))]
[assembly: TypeForwardedTo(typeof(FieldAttributes))]
[assembly: TypeForwardedTo(typeof(FieldDefinition))]
[assembly: TypeForwardedTo(typeof(FieldReference))]
[assembly: TypeForwardedTo(typeof(FixedArrayMarshalInfo))]
[assembly: TypeForwardedTo(typeof(FixedSysStringMarshalInfo))]
[assembly: TypeForwardedTo(typeof(FunctionPointerType))]
[assembly: TypeForwardedTo(typeof(GenericInstanceMethod))]
[assembly: TypeForwardedTo(typeof(GenericInstanceType))]
[assembly: TypeForwardedTo(typeof(GenericParameter))]
[assembly: TypeForwardedTo(typeof(GenericParameterAttributes))]
[assembly: TypeForwardedTo(typeof(GenericParameterType))]
[assembly: TypeForwardedTo(typeof(IAssemblyResolver))]
[assembly: TypeForwardedTo(typeof(IConstantProvider))]
[assembly: TypeForwardedTo(typeof(ICustomAttribute))]
[assembly: TypeForwardedTo(typeof(ICustomAttributeProvider))]
[assembly: TypeForwardedTo(typeof(IGenericInstance))]
[assembly: TypeForwardedTo(typeof(IGenericParameterProvider))]
[assembly: TypeForwardedTo(typeof(IMarshalInfoProvider))]
[assembly: TypeForwardedTo(typeof(IMemberDefinition))]
[assembly: TypeForwardedTo(typeof(IMetadataImporter))]
[assembly: TypeForwardedTo(typeof(IMetadataImporterProvider))]
[assembly: TypeForwardedTo(typeof(IMetadataResolver))]
[assembly: TypeForwardedTo(typeof(IMetadataScope))]
[assembly: TypeForwardedTo(typeof(IMetadataTokenProvider))]
[assembly: TypeForwardedTo(typeof(IMethodSignature))]
[assembly: TypeForwardedTo(typeof(IModifierType))]
[assembly: TypeForwardedTo(typeof(InterfaceImplementation))]
[assembly: TypeForwardedTo(typeof(IReflectionImporter))]
[assembly: TypeForwardedTo(typeof(IReflectionImporterProvider))]
[assembly: TypeForwardedTo(typeof(ISecurityDeclarationProvider))]
[assembly: TypeForwardedTo(typeof(LinkedResource))]
[assembly: TypeForwardedTo(typeof(ManifestResourceAttributes))]
[assembly: TypeForwardedTo(typeof(MarshalInfo))]
[assembly: TypeForwardedTo(typeof(MdbReader))]
[assembly: TypeForwardedTo(typeof(MdbReaderProvider))]
[assembly: TypeForwardedTo(typeof(MdbWriter))]
[assembly: TypeForwardedTo(typeof(MdbWriterProvider))]
[assembly: TypeForwardedTo(typeof(MemberReference))]
[assembly: TypeForwardedTo(typeof(MetadataKind))]
[assembly: TypeForwardedTo(typeof(MetadataResolver))]
[assembly: TypeForwardedTo(typeof(MetadataScopeType))]
[assembly: TypeForwardedTo(typeof(MetadataToken))]
[assembly: TypeForwardedTo(typeof(MetadataType))]
[assembly: TypeForwardedTo(typeof(MethodAttributes))]
[assembly: TypeForwardedTo(typeof(MethodCallingConvention))]
[assembly: TypeForwardedTo(typeof(MethodDefinition))]
[assembly: TypeForwardedTo(typeof(MethodImplAttributes))]
[assembly: TypeForwardedTo(typeof(MethodReference))]
[assembly: TypeForwardedTo(typeof(MethodReturnType))]
[assembly: TypeForwardedTo(typeof(MethodSemanticsAttributes))]
[assembly: TypeForwardedTo(typeof(MethodSpecification))]
[assembly: TypeForwardedTo(typeof(ModuleAttributes))]
[assembly: TypeForwardedTo(typeof(ModuleCharacteristics))]
[assembly: TypeForwardedTo(typeof(ModuleDefinition))]
[assembly: TypeForwardedTo(typeof(ModuleKind))]
[assembly: TypeForwardedTo(typeof(ModuleParameters))]
[assembly: TypeForwardedTo(typeof(ModuleReference))]
[assembly: TypeForwardedTo(typeof(NativeType))]
[assembly: TypeForwardedTo(typeof(OptionalModifierType))]
[assembly: TypeForwardedTo(typeof(ParameterAttributes))]
[assembly: TypeForwardedTo(typeof(ParameterDefinition))]
[assembly: TypeForwardedTo(typeof(ParameterReference))]
[assembly: TypeForwardedTo(typeof(NativePdbReader))]
[assembly: TypeForwardedTo(typeof(NativePdbReaderProvider))]
[assembly: TypeForwardedTo(typeof(NativePdbWriter))]
[assembly: TypeForwardedTo(typeof(NativePdbWriterProvider))]
[assembly: TypeForwardedTo(typeof(PdbReaderProvider))]
[assembly: TypeForwardedTo(typeof(PdbWriterProvider))]
[assembly: TypeForwardedTo(typeof(PinnedType))]
[assembly: TypeForwardedTo(typeof(PInvokeAttributes))]
[assembly: TypeForwardedTo(typeof(PInvokeInfo))]
[assembly: TypeForwardedTo(typeof(PointerType))]
[assembly: TypeForwardedTo(typeof(PropertyAttributes))]
[assembly: TypeForwardedTo(typeof(PropertyDefinition))]
[assembly: TypeForwardedTo(typeof(PropertyReference))]
[assembly: TypeForwardedTo(typeof(ReaderParameters))]
[assembly: TypeForwardedTo(typeof(ReadingMode))]
[assembly: TypeForwardedTo(typeof(RequiredModifierType))]
[assembly: TypeForwardedTo(typeof(ResolutionException))]
[assembly: TypeForwardedTo(typeof(Resource))]
[assembly: TypeForwardedTo(typeof(ResourceType))]
[assembly: TypeForwardedTo(typeof(DocCommentId))]
[assembly: TypeForwardedTo(typeof(IILVisitor))]
[assembly: TypeForwardedTo(typeof(ILParser))]
[assembly: TypeForwardedTo(typeof(MethodBodyRocks))]
[assembly: TypeForwardedTo(typeof(MethodDefinitionRocks))]
[assembly: TypeForwardedTo(typeof(ModuleDefinitionRocks))]
[assembly: TypeForwardedTo(typeof(ParameterReferenceRocks))]
[assembly: TypeForwardedTo(typeof(SecurityDeclarationRocks))]
[assembly: TypeForwardedTo(typeof(TypeDefinitionRocks))]
[assembly: TypeForwardedTo(typeof(TypeReferenceRocks))]
[assembly: TypeForwardedTo(typeof(SafeArrayMarshalInfo))]
[assembly: TypeForwardedTo(typeof(SecurityAction))]
[assembly: TypeForwardedTo(typeof(SecurityAttribute))]
[assembly: TypeForwardedTo(typeof(SecurityDeclaration))]
[assembly: TypeForwardedTo(typeof(SentinelType))]
[assembly: TypeForwardedTo(typeof(TargetArchitecture))]
[assembly: TypeForwardedTo(typeof(TargetRuntime))]
[assembly: TypeForwardedTo(typeof(TokenType))]
[assembly: TypeForwardedTo(typeof(TypeAttributes))]
[assembly: TypeForwardedTo(typeof(TypeDefinition))]
[assembly: TypeForwardedTo(typeof(TypeReference))]
[assembly: TypeForwardedTo(typeof(TypeSpecification))]
[assembly: TypeForwardedTo(typeof(TypeSystem))]
[assembly: TypeForwardedTo(typeof(VariantType))]
[assembly: TypeForwardedTo(typeof(WriterParameters))]
[assembly: TypeForwardedTo(typeof(Collection<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlyCollection<>))]
[assembly: TypeForwardedTo(typeof(AnonymousScopeEntry))]
[assembly: TypeForwardedTo(typeof(CapturedScope))]
[assembly: TypeForwardedTo(typeof(CapturedVariable))]
[assembly: TypeForwardedTo(typeof(CodeBlockEntry))]
[assembly: TypeForwardedTo(typeof(CompileUnitEntry))]
[assembly: TypeForwardedTo(typeof(ICompileUnit))]
[assembly: TypeForwardedTo(typeof(IMethodDef))]
[assembly: TypeForwardedTo(typeof(ISourceFile))]
[assembly: TypeForwardedTo(typeof(LineNumberEntry))]
[assembly: TypeForwardedTo(typeof(LineNumberTable))]
[assembly: TypeForwardedTo(typeof(LocalVariableEntry))]
[assembly: TypeForwardedTo(typeof(MethodEntry))]
[assembly: TypeForwardedTo(typeof(MonoSymbolFile))]
[assembly: TypeForwardedTo(typeof(MonoSymbolFileException))]
[assembly: TypeForwardedTo(typeof(MonoSymbolWriter))]
[assembly: TypeForwardedTo(typeof(NamespaceEntry))]
[assembly: TypeForwardedTo(typeof(OffsetTable))]
[assembly: TypeForwardedTo(typeof(ScopeVariable))]
[assembly: TypeForwardedTo(typeof(SourceFileEntry))]
[assembly: TypeForwardedTo(typeof(SourceMethodBuilder))]
[assembly: TypeForwardedTo(typeof(SymbolWriterImpl))]
[assembly: TypeForwardedTo(typeof(IILReferenceBag))]
[assembly: TypeForwardedTo(typeof(ILContext))]
[assembly: TypeForwardedTo(typeof(ILCursor))]
[assembly: TypeForwardedTo(typeof(ILLabel))]
[assembly: TypeForwardedTo(typeof(ILPatternMatchingExt))]
[assembly: TypeForwardedTo(typeof(MoveType))]
[assembly: TypeForwardedTo(typeof(NopILReferenceBag))]
[assembly: TypeForwardedTo(typeof(RuntimeILReferenceBag))]
[assembly: TypeForwardedTo(typeof(SearchTarget))]
[assembly: TypeForwardedTo(typeof(ModExportNameAttribute))]
[assembly: TypeForwardedTo(typeof(ModImportNameAttribute))]
[assembly: TypeForwardedTo(typeof(ModInteropManager))]
[assembly: TypeForwardedTo(typeof(Detour))]
[assembly: TypeForwardedTo(typeof(Detour<>))]
[assembly: TypeForwardedTo(typeof(DetourConfig))]
[assembly: TypeForwardedTo(typeof(DetourContext))]
[assembly: TypeForwardedTo(typeof(DetourHelper))]
[assembly: TypeForwardedTo(typeof(DetourModManager))]
[assembly: TypeForwardedTo(typeof(HarmonyDetourBridge))]
[assembly: TypeForwardedTo(typeof(Hook))]
[assembly: TypeForwardedTo(typeof(Hook<>))]
[assembly: TypeForwardedTo(typeof(Hook<, >))]
[assembly: TypeForwardedTo(typeof(HookConfig))]
[assembly: TypeForwardedTo(typeof(HookEndpointManager))]
[assembly: TypeForwardedTo(typeof(IDetour))]
[assembly: TypeForwardedTo(typeof(IDetourNativePlatform))]
[assembly: TypeForwardedTo(typeof(IDetourRuntimePlatform))]
[assembly: TypeForwardedTo(typeof(ILHook))]
[assembly: TypeForwardedTo(typeof(ILHookConfig))]
[assembly: TypeForwardedTo(typeof(ISortableDetour))]
[assembly: TypeForwardedTo(typeof(NativeDetour))]
[assembly: TypeForwardedTo(typeof(NativeDetourConfig))]
[assembly: TypeForwardedTo(typeof(NativeDetourData))]
[assembly: TypeForwardedTo(typeof(OnMethodCompiledEvent))]
[assembly: TypeForwardedTo(typeof(DetourNativeARMPlatform))]
[assembly: TypeForwardedTo(typeof(DetourNativeLibcPlatform))]
[assembly: TypeForwardedTo(typeof(DetourNativeMonoPlatform))]
[assembly: TypeForwardedTo(typeof(DetourNativeMonoPosixPlatform))]
[assembly: TypeForwardedTo(typeof(DetourNativeWindowsPlatform))]
[assembly: TypeForwardedTo(typeof(DetourNativeX86Platform))]
[assembly: TypeForwardedTo(typeof(DetourRuntimeILPlatform))]
[assembly: TypeForwardedTo(typeof(DetourRuntimeMonoPlatform))]
[assembly: TypeForwardedTo(typeof(DetourRuntimeNET50Platform))]
[assembly: TypeForwardedTo(typeof(DetourRuntimeNET60Platform))]
[assembly: TypeForwardedTo(typeof(DetourRuntimeNETCore30Platform))]
[assembly: TypeForwardedTo(typeof(DetourRuntimeNETCorePlatform))]
[assembly: TypeForwardedTo(typeof(DetourRuntimeNETPlatform))]
[assembly: TypeForwardedTo(typeof(CecilILGenerator))]
[assembly: TypeForwardedTo(typeof(ILGeneratorShim))]
[assembly: TypeForwardedTo(typeof(ILGeneratorShimExt))]
[assembly: TypeForwardedTo(typeof(DMDCecilGenerator))]
[assembly: TypeForwardedTo(typeof(DMDEmitDynamicMethodGenerator))]
[assembly: TypeForwardedTo(typeof(DMDEmitMethodBuilderGenerator))]
[assembly: TypeForwardedTo(typeof(DMDGenerator<>))]
[assembly: TypeForwardedTo(typeof(DynamicMethodDefinition))]
[assembly: TypeForwardedTo(typeof(DynamicMethodHelper))]
[assembly: TypeForwardedTo(typeof(DynamicMethodReference))]
[assembly: TypeForwardedTo(typeof(DynData<>))]
[assembly: TypeForwardedTo(typeof(DynDll))]
[assembly: TypeForwardedTo(typeof(DynDllImportAttribute))]
[assembly: TypeForwardedTo(typeof(DynDllMapping))]
[assembly: TypeForwardedTo(typeof(Extensions))]
[assembly: TypeForwardedTo(typeof(FastReflectionDelegate))]
[assembly: TypeForwardedTo(typeof(FastReflectionHelper))]
[assembly: TypeForwardedTo(typeof(GCListener))]
[assembly: TypeForwardedTo(typeof(GenericMethodInstantiationComparer))]
[assembly: TypeForwardedTo(typeof(GenericTypeInstantiationComparer))]
[assembly: TypeForwardedTo(typeof(ICallSiteGenerator))]
[assembly: TypeForwardedTo(typeof(LazyDisposable))]
[assembly: TypeForwardedTo(typeof(LazyDisposable<>))]
[assembly: TypeForwardedTo(typeof(MMReflectionImporter))]
[assembly: TypeForwardedTo(typeof(Platform))]
[assembly: TypeForwardedTo(typeof(PlatformHelper))]
[assembly: TypeForwardedTo(typeof(ReflectionHelper))]
[assembly: TypeForwardedTo(typeof(Relinker))]
[assembly: TypeForwardedTo(typeof(RelinkFailedException))]
[assembly: TypeForwardedTo(typeof(RelinkTargetNotFoundException))]
[assembly: TypeForwardedTo(typeof(WeakReferenceComparer))]
[assembly: TypeForwardedTo(typeof(IgnoresAccessChecksToAttribute))]
[assembly: TypeForwardedTo(typeof(TomlDoNotInlineObjectAttribute))]
[assembly: TypeForwardedTo(typeof(TomlInlineCommentAttribute))]
[assembly: TypeForwardedTo(typeof(TomlPrecedingCommentAttribute))]
[assembly: TypeForwardedTo(typeof(TomlPropertyAttribute))]
[assembly: TypeForwardedTo(typeof(InvalidTomlDateTimeException))]
[assembly: TypeForwardedTo(typeof(InvalidTomlEscapeException))]
[assembly: TypeForwardedTo(typeof(InvalidTomlInlineTableException))]
[assembly: TypeForwardedTo(typeof(InvalidTomlKeyException))]
[assembly: TypeForwardedTo(typeof(InvalidTomlNumberException))]
[assembly: TypeForwardedTo(typeof(MissingIntermediateInTomlTableArraySpecException))]
[assembly: TypeForwardedTo(typeof(NewLineInTomlInlineTableException))]
[assembly: TypeForwardedTo(typeof(NoTomlKeyException))]
[assembly: TypeForwardedTo(typeof(TimeOffsetOnTomlDateOrTimeException))]
[assembly: TypeForwardedTo(typeof(TomlArraySyntaxException))]
[assembly: TypeForwardedTo(typeof(TomlContainsDottedKeyNonTableException))]
[assembly: TypeForwardedTo(typeof(TomlDateTimeMissingSeparatorException))]
[assembly: TypeForwardedTo(typeof(TomlDateTimeUnnecessarySeparatorException))]
[assembly: TypeForwardedTo(typeof(TomlDottedKeyException))]
[assembly: TypeForwardedTo(typeof(TomlDottedKeyParserException))]
[assembly: TypeForwardedTo(typeof(TomlDoubleDottedKeyException))]
[assembly: TypeForwardedTo(typeof(TomlEndOfFileException))]
[assembly: TypeForwardedTo(typeof(TomlEnumParseException))]
[assembly: TypeForwardedTo(typeof(TomlException))]
[assembly: TypeForwardedTo(typeof(TomlExceptionWithLine))]
[assembly: TypeForwardedTo(typeof(TomlFieldTypeMismatchException))]
[assembly: TypeForwardedTo(typeof(TomlInlineTableSeparatorException))]
[assembly: TypeForwardedTo(typeof(TomlInstantiationException))]
[assembly: TypeForwardedTo(typeof(TomlInternalException))]
[assembly: TypeForwardedTo(typeof(TomlInvalidValueException))]
[assembly: TypeForwardedTo(typeof(TomlKeyRedefinitionException))]
[assembly: TypeForwardedTo(typeof(TomlMissingEqualsException))]
[assembly: TypeForwardedTo(typeof(TomlMissingNewlineException))]
[assembly: TypeForwardedTo(typeof(TomlNewlineInInlineCommentException))]
[assembly: TypeForwardedTo(typeof(TomlNonTableArrayUsedAsTableArrayException))]
[assembly: TypeForwardedTo(typeof(TomlNoSuchValueException))]
[assembly: TypeForwardedTo(typeof(TomlPrimitiveToDocumentException))]
[assembly: TypeForwardedTo(typeof(TomlStringException))]
[assembly: TypeForwardedTo(typeof(TomlTableArrayAlreadyExistsAsNonArrayException))]
[assembly: TypeForwardedTo(typeof(TomlTableLockedException))]
[assembly: TypeForwardedTo(typeof(TomlTableRedefinitionException))]
[assembly: TypeForwardedTo(typeof(TomlTripleQuotedKeyException))]
[assembly: TypeForwardedTo(typeof(TomlTypeMismatchException))]
[assembly: TypeForwardedTo(typeof(TomlUnescapedUnicodeControlCharException))]
[assembly: TypeForwardedTo(typeof(TomlWhitespaceInKeyException))]
[assembly: TypeForwardedTo(typeof(TripleQuoteInTomlMultilineLiteralException))]
[assembly: TypeForwardedTo(typeof(TripleQuoteInTomlMultilineSimpleStringException))]
[assembly: TypeForwardedTo(typeof(UnterminatedTomlKeyException))]
[assembly: TypeForwardedTo(typeof(UnterminatedTomlStringException))]
[assembly: TypeForwardedTo(typeof(UnterminatedTomlTableArrayException))]
[assembly: TypeForwardedTo(typeof(UnterminatedTomlTableNameException))]
[assembly: TypeForwardedTo(typeof(ITomlValueWithDateTime))]
[assembly: TypeForwardedTo(typeof(TomlArray))]
[assembly: TypeForwardedTo(typeof(TomlBoolean))]
[assembly: TypeForwardedTo(typeof(TomlCommentData))]
[assembly: TypeForwardedTo(typeof(TomlDocument))]
[assembly: TypeForwardedTo(typeof(TomlDouble))]
[assembly: TypeForwardedTo(typeof(TomlLocalDate))]
[assembly: TypeForwardedTo(typeof(TomlLocalDateTime))]
[assembly: TypeForwardedTo(typeof(TomlLocalTime))]
[assembly: TypeForwardedTo(typeof(TomlLong))]
[assembly: TypeForwardedTo(typeof(TomlOffsetDateTime))]
[assembly: TypeForwardedTo(typeof(TomlString))]
[assembly: TypeForwardedTo(typeof(TomlTable))]
[assembly: TypeForwardedTo(typeof(TomlValue))]
[assembly: TypeForwardedTo(typeof(TomletMain))]
[assembly: TypeForwardedTo(typeof(TomletStringReader))]
[assembly: TypeForwardedTo(typeof(TomlNumberUtils))]
[assembly: TypeForwardedTo(typeof(TomlParser))]
[assembly: TypeForwardedTo(typeof(TomlSerializationMethods))]
[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 Semver
{
	internal static class IntExtensions
	{
		public static int Digits(this int n)
		{
			if (n < 10)
			{
				return 1;
			}
			if (n < 100)
			{
				return 2;
			}
			if (n < 1000)
			{
				return 3;
			}
			if (n < 10000)
			{
				return 4;
			}
			if (n < 100000)
			{
				return 5;
			}
			if (n < 1000000)
			{
				return 6;
			}
			if (n < 10000000)
			{
				return 7;
			}
			if (n < 100000000)
			{
				return 8;
			}
			if (n < 1000000000)
			{
				return 9;
			}
			return 10;
		}
	}
	[Serializable]
	public sealed class SemVersion : IComparable<SemVersion>, IComparable, ISerializable
	{
		private static readonly Regex ParseEx = new Regex("^(?<major>\\d+)(?>\\.(?<minor>\\d+))?(?>\\.(?<patch>\\d+))?(?>\\-(?<pre>[0-9A-Za-z\\-\\.]+))?(?>\\+(?<build>[0-9A-Za-z\\-\\.]+))?$", RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);

		public int Major { get; }

		public int Minor { get; }

		public int Patch { get; }

		public string Prerelease { get; }

		public string Build { get; }

		private SemVersion(SerializationInfo info, StreamingContext context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			SemVersion semVersion = Parse(info.GetString("SemVersion"));
			Major = semVersion.Major;
			Minor = semVersion.Minor;
			Patch = semVersion.Patch;
			Prerelease = semVersion.Prerelease;
			Build = semVersion.Build;
		}

		public SemVersion(int major, int minor = 0, int patch = 0, string prerelease = "", string build = "")
		{
			Major = major;
			Minor = minor;
			Patch = patch;
			Prerelease = prerelease ?? "";
			Build = build ?? "";
		}

		public SemVersion(Version version)
		{
			if (version == null)
			{
				throw new ArgumentNullException("version");
			}
			Major = version.Major;
			Minor = version.Minor;
			if (version.Revision >= 0)
			{
				Patch = version.Revision;
			}
			Prerelease = "";
			Build = ((version.Build > 0) ? version.Build.ToString(CultureInfo.InvariantCulture) : "");
		}

		public static SemVersion Parse(string version, bool strict = false)
		{
			Match match = ParseEx.Match(version);
			if (!match.Success)
			{
				throw new ArgumentException("Invalid version '" + version + "'.", "version");
			}
			int major = int.Parse(match.Groups["major"].Value, CultureInfo.InvariantCulture);
			Group group = match.Groups["minor"];
			int minor = 0;
			if (group.Success)
			{
				minor = int.Parse(group.Value, CultureInfo.InvariantCulture);
			}
			else if (strict)
			{
				throw new InvalidOperationException("Invalid version (no minor version given in strict mode)");
			}
			Group group2 = match.Groups["patch"];
			int patch = 0;
			if (group2.Success)
			{
				patch = int.Parse(group2.Value, CultureInfo.InvariantCulture);
			}
			else if (strict)
			{
				throw new InvalidOperationException("Invalid version (no patch version given in strict mode)");
			}
			string value = match.Groups["pre"].Value;
			string value2 = match.Groups["build"].Value;
			return new SemVersion(major, minor, patch, value, value2);
		}

		public static bool TryParse(string version, out SemVersion semver, bool strict = false)
		{
			semver = null;
			if (version == null)
			{
				return false;
			}
			Match match = ParseEx.Match(version);
			if (!match.Success)
			{
				return false;
			}
			if (!int.TryParse(match.Groups["major"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
			{
				return false;
			}
			Group group = match.Groups["minor"];
			int result2 = 0;
			if (group.Success)
			{
				if (!int.TryParse(group.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out result2))
				{
					return false;
				}
			}
			else if (strict)
			{
				return false;
			}
			Group group2 = match.Groups["patch"];
			int result3 = 0;
			if (group2.Success)
			{
				if (!int.TryParse(group2.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out result3))
				{
					return false;
				}
			}
			else if (strict)
			{
				return false;
			}
			string value = match.Groups["pre"].Value;
			string value2 = match.Groups["build"].Value;
			semver = new SemVersion(result, result2, result3, value, value2);
			return true;
		}

		public static bool Equals(SemVersion versionA, SemVersion versionB)
		{
			if ((object)versionA == versionB)
			{
				return true;
			}
			if ((object)versionA == null || (object)versionB == null)
			{
				return false;
			}
			return versionA.Equals(versionB);
		}

		public static int Compare(SemVersion versionA, SemVersion versionB)
		{
			if ((object)versionA == versionB)
			{
				return 0;
			}
			if ((object)versionA == null)
			{
				return -1;
			}
			if ((object)versionB == null)
			{
				return 1;
			}
			return versionA.CompareTo(versionB);
		}

		public SemVersion Change(int? major = null, int? minor = null, int? patch = null, string prerelease = null, string build = null)
		{
			return new SemVersion(major ?? Major, minor ?? Minor, patch ?? Patch, prerelease ?? Prerelease, build ?? Build);
		}

		public override string ToString()
		{
			int capacity = 4 + Major.Digits() + Minor.Digits() + Patch.Digits() + Prerelease.Length + Build.Length;
			StringBuilder stringBuilder = new StringBuilder(capacity);
			stringBuilder.Append(Major);
			stringBuilder.Append('.');
			stringBuilder.Append(Minor);
			stringBuilder.Append('.');
			stringBuilder.Append(Patch);
			if (Prerelease.Length > 0)
			{
				stringBuilder.Append('-');
				stringBuilder.Append(Prerelease);
			}
			if (Build.Length > 0)
			{
				stringBuilder.Append('+');
				stringBuilder.Append(Build);
			}
			return stringBuilder.ToString();
		}

		public int CompareTo(object obj)
		{
			return CompareTo((SemVersion)obj);
		}

		public int CompareTo(SemVersion other)
		{
			int num = CompareByPrecedence(other);
			if (num != 0)
			{
				return num;
			}
			return CompareComponent(Build, other.Build);
		}

		public bool PrecedenceMatches(SemVersion other)
		{
			return CompareByPrecedence(other) == 0;
		}

		public int CompareByPrecedence(SemVersion other)
		{
			if ((object)other == null)
			{
				return 1;
			}
			int num = Major.CompareTo(other.Major);
			if (num != 0)
			{
				return num;
			}
			num = Minor.CompareTo(other.Minor);
			if (num != 0)
			{
				return num;
			}
			num = Patch.CompareTo(other.Patch);
			if (num != 0)
			{
				return num;
			}
			return CompareComponent(Prerelease, other.Prerelease, nonemptyIsLower: true);
		}

		private static int CompareComponent(string a, string b, bool nonemptyIsLower = false)
		{
			bool flag = string.IsNullOrEmpty(a);
			bool flag2 = string.IsNullOrEmpty(b);
			if (flag && flag2)
			{
				return 0;
			}
			if (flag)
			{
				return nonemptyIsLower ? 1 : (-1);
			}
			if (flag2)
			{
				return (!nonemptyIsLower) ? 1 : (-1);
			}
			string[] array = a.Split(new char[1] { '.' });
			string[] array2 = b.Split(new char[1] { '.' });
			int num = Math.Min(array.Length, array2.Length);
			for (int i = 0; i < num; i++)
			{
				string text = array[i];
				string text2 = array2[i];
				int result;
				bool flag3 = int.TryParse(text, out result);
				int result2;
				bool flag4 = int.TryParse(text2, out result2);
				int num2;
				if (flag3 && flag4)
				{
					num2 = result.CompareTo(result2);
					if (num2 != 0)
					{
						return num2;
					}
					continue;
				}
				if (flag3)
				{
					return -1;
				}
				if (flag4)
				{
					return 1;
				}
				num2 = string.CompareOrdinal(text, text2);
				if (num2 != 0)
				{
					return num2;
				}
			}
			return array.Length.CompareTo(array2.Length);
		}

		public override bool Equals(object obj)
		{
			if (obj == null)
			{
				return false;
			}
			if (this == obj)
			{
				return true;
			}
			SemVersion semVersion = (SemVersion)obj;
			return Major == semVersion.Major && Minor == semVersion.Minor && Patch == semVersion.Patch && string.Equals(Prerelease, semVersion.Prerelease, StringComparison.Ordinal) && string.Equals(Build, semVersion.Build, StringComparison.Ordinal);
		}

		public override int GetHashCode()
		{
			int hashCode = Major.GetHashCode();
			hashCode = hashCode * 31 + Minor.GetHashCode();
			hashCode = hashCode * 31 + Patch.GetHashCode();
			hashCode = hashCode * 31 + Prerelease.GetHashCode();
			return hashCode * 31 + Build.GetHashCode();
		}

		[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
		public void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			info.AddValue("SemVersion", ToString());
		}

		public static implicit operator SemVersion(string version)
		{
			return Parse(version);
		}

		public static bool operator ==(SemVersion left, SemVersion right)
		{
			return Equals(left, right);
		}

		public static bool operator !=(SemVersion left, SemVersion right)
		{
			return !Equals(left, right);
		}

		public static bool operator >(SemVersion left, SemVersion right)
		{
			return Compare(left, right) > 0;
		}

		public static bool operator >=(SemVersion left, SemVersion right)
		{
			return Equals(left, right) || Compare(left, right) > 0;
		}

		public static bool operator <(SemVersion left, SemVersion right)
		{
			return Compare(left, right) < 0;
		}

		public static bool operator <=(SemVersion left, SemVersion right)
		{
			return Equals(left, right) || Compare(left, right) < 0;
		}
	}
}
namespace Harmony
{
	[Obsolete("Harmony.MethodType is Only Here for Compatibility Reasons. Please use HarmonyLib.MethodType instead.")]
	public enum MethodType
	{
		Normal,
		Getter,
		Setter,
		Constructor,
		StaticConstructor
	}
	[Obsolete("Harmony.PropertyMethod is Only Here for Compatibility Reasons. Please use HarmonyLib.MethodType instead.")]
	public enum PropertyMethod
	{
		Getter = 1,
		Setter
	}
	[Obsolete("Harmony.ArgumentType is Only Here for Compatibility Reasons. Please use HarmonyLib.ArgumentType instead.")]
	public enum ArgumentType
	{
		Normal,
		Ref,
		Out,
		Pointer
	}
	[Obsolete("Harmony.HarmonyPatchType is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatchType instead.")]
	public enum HarmonyPatchType
	{
		All,
		Prefix,
		Postfix,
		Transpiler
	}
	[Obsolete("Harmony.HarmonyAttribute is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyAttribute instead.")]
	public class HarmonyAttribute : HarmonyAttribute
	{
	}
	[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Delegate, AllowMultiple = true)]
	public class HarmonyPatch : HarmonyPatch
	{
		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch()
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(Type declaringType)
			: base(declaringType)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(Type declaringType, Type[] argumentTypes)
			: base(declaringType, argumentTypes)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(Type declaringType, string methodName)
			: base(declaringType, methodName)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes)
			: base(declaringType, methodName, argumentTypes)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(declaringType, methodName, argumentTypes, Array.ConvertAll(argumentVariations, (ArgumentType x) => (ArgumentType)x))
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(Type declaringType, MethodType methodType)
			: base(declaringType, (MethodType)methodType)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes)
			: base(declaringType, (MethodType)methodType, argumentTypes)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(declaringType, (MethodType)methodType, argumentTypes, Array.ConvertAll(argumentVariations, (ArgumentType x) => (ArgumentType)x))
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(Type declaringType, string propertyName, MethodType methodType)
			: base(declaringType, propertyName, (MethodType)methodType)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(string methodName)
			: base(methodName)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(string methodName, params Type[] argumentTypes)
			: base(methodName, argumentTypes)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(methodName, argumentTypes, Array.ConvertAll(argumentVariations, (ArgumentType x) => (ArgumentType)x))
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(string propertyName, MethodType methodType)
			: base(propertyName, (MethodType)methodType)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(MethodType methodType)
			: base((MethodType)methodType)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(MethodType methodType, params Type[] argumentTypes)
			: base((MethodType)methodType, argumentTypes)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base((MethodType)methodType, argumentTypes, Array.ConvertAll(argumentVariations, (ArgumentType x) => (ArgumentType)x))
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(Type[] argumentTypes)
			: base(argumentTypes)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(argumentTypes, Array.ConvertAll(argumentVariations, (ArgumentType x) => (ArgumentType)x))
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(string propertyName, PropertyMethod type)
			: base(propertyName, (MethodType)type)
		{
		}

		[Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead.")]
		public HarmonyPatch(string assemblyQualifiedDeclaringType, string methodName, MethodType methodType, Type[] argumentTypes = null, ArgumentType[] argumentVariations = null)
			: base(assemblyQualifiedDeclaringType, methodName, (MethodType)methodType, argumentTypes, Array.ConvertAll(argumentVariations, (ArgumentType x) => (ArgumentType)x))
		{
		}
	}
	[Obsolete("Harmony.HarmonyPatchAll is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatchAll instead.")]
	[AttributeUsage(AttributeTargets.Class)]
	public class HarmonyPatchAll : HarmonyPatchAll
	{
	}
	[Obsolete("Harmony.HarmonyPriority is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPriority instead.")]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyPriority : HarmonyPriority
	{
		[Obsolete("Harmony.HarmonyPriority is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPriority instead.")]
		public HarmonyPriority(int prioritiy)
			: base(prioritiy)
		{
		}
	}
	[Obsolete("Harmony.HarmonyBefore is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyBefore instead.")]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyBefore : HarmonyBefore
	{
		[Obsolete("Harmony.HarmonyBefore is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyBefore instead.")]
		public HarmonyBefore(params string[] before)
			: base(before)
		{
		}
	}
	[Obsolete("Harmony.HarmonyAfter is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyAfter instead.")]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyAfter : HarmonyAfter
	{
		[Obsolete("Harmony.HarmonyAfter is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyAfter instead.")]
		public HarmonyAfter(params string[] after)
			: base(after)
		{
		}
	}
	[Obsolete("Harmony.HarmonyPrepare is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPrepare instead.")]
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrepare : HarmonyPrepare
	{
	}
	[Obsolete("Harmony.HarmonyCleanup is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyCleanup instead.")]
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyCleanup : HarmonyCleanup
	{
	}
	[Obsolete("Harmony.HarmonyTargetMethod is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyTargetMethod instead.")]
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethod : HarmonyTargetMethod
	{
	}
	[Obsolete("Harmony.HarmonyTargetMethods is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyTargetMethods instead.")]
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethods : HarmonyTargetMethods
	{
	}
	[Obsolete("Harmony.HarmonyPrefix is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPrefix instead.")]
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrefix : HarmonyPrefix
	{
	}
	[Obsolete("Harmony.HarmonyPostfix is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPostfix instead.")]
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPostfix : HarmonyPostfix
	{
	}
	[Obsolete("Harmony.HarmonyTranspiler is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyTranspiler instead.")]
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTranspiler : HarmonyTranspiler
	{
	}
	[Obsolete("Harmony.HarmonyArgument is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyArgument instead.")]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)]
	public class HarmonyArgument : HarmonyArgument
	{
		[Obsolete("Harmony.HarmonyArgument is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyArgument instead.")]
		public HarmonyArgument(string originalName)
			: base(originalName, (string)null)
		{
		}

		[Obsolete("Harmony.HarmonyArgument is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyArgument instead.")]
		public HarmonyArgument(int index)
			: base(index, (string)null)
		{
		}

		[Obsolete("Harmony.HarmonyArgument is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyArgument instead.")]
		public HarmonyArgument(string originalName, string newName)
			: base(originalName, newName)
		{
		}

		[Obsolete("Harmony.HarmonyArgument is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyArgument instead.")]
		public HarmonyArgument(int index, string name)
			: base(index, name)
		{
		}
	}
	public class DelegateTypeFactory : DelegateTypeFactory
	{
	}
	public delegate object GetterHandler(object source);
	public delegate void SetterHandler(object source, object value);
	public delegate object InstantiationHandler();
	public class FastAccess
	{
		[Obsolete("Use AccessTools.MethodDelegate<Func<T, S>>(PropertyInfo.GetGetMethod(true))")]
		public static InstantiationHandler CreateInstantiationHandler(Type type)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
			if ((object)constructor == null)
			{
				throw new ApplicationException($"The type {type} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).");
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition("InstantiateObject_" + type.Name, type, (Type[])null);
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Newobj, constructor);
			iLGenerator.Emit(OpCodes.Ret);
			return (InstantiationHandler)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(InstantiationHandler));
		}

		[Obsolete("Use AccessTools.MethodDelegate<Func<T, S>>(PropertyInfo.GetGetMethod(true))")]
		public static GetterHandler CreateGetterHandler(PropertyInfo propertyInfo)
		{
			MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true);
			DynamicMethodDefinition val = CreateGetDynamicMethod(propertyInfo.DeclaringType);
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Call, getMethod);
			iLGenerator.Emit(OpCodes.Ret);
			return (GetterHandler)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(GetterHandler));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")]
		public static GetterHandler CreateGetterHandler(FieldInfo fieldInfo)
		{
			DynamicMethodDefinition val = CreateGetDynamicMethod(fieldInfo.DeclaringType);
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldfld, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return (GetterHandler)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(GetterHandler));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(name) for fields and AccessTools.MethodDelegate<Func<T, S>>(AccessTools.PropertyGetter(typeof(T), name)) for properties")]
		public static GetterHandler CreateFieldGetter(Type type, params string[] names)
		{
			foreach (string name in names)
			{
				FieldInfo field = type.GetField(name, AccessTools.all);
				if ((object)field != null)
				{
					return CreateGetterHandler(field);
				}
				PropertyInfo property = type.GetProperty(name, AccessTools.all);
				if ((object)property != null)
				{
					return CreateGetterHandler(property);
				}
			}
			return null;
		}

		[Obsolete("Use AccessTools.MethodDelegate<Action<T, S>>(PropertyInfo.GetSetMethod(true))")]
		public static SetterHandler CreateSetterHandler(PropertyInfo propertyInfo)
		{
			MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
			DynamicMethodDefinition val = CreateSetDynamicMethod(propertyInfo.DeclaringType);
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Call, setMethod);
			iLGenerator.Emit(OpCodes.Ret);
			return (SetterHandler)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(SetterHandler));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")]
		public static SetterHandler CreateSetterHandler(FieldInfo fieldInfo)
		{
			DynamicMethodDefinition val = CreateSetDynamicMethod(fieldInfo.DeclaringType);
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Stfld, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return (SetterHandler)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(SetterHandler));
		}

		private static DynamicMethodDefinition CreateGetDynamicMethod(Type type)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			return new DynamicMethodDefinition("DynamicGet_" + type.Name, typeof(object), new Type[1] { typeof(object) });
		}

		private static DynamicMethodDefinition CreateSetDynamicMethod(Type type)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			return new DynamicMethodDefinition("DynamicSet_" + type.Name, typeof(void), new Type[2]
			{
				typeof(object),
				typeof(object)
			});
		}
	}
	public delegate object FastInvokeHandler(object target, object[] paramters);
	public class MethodInvoker
	{
		public static FastInvokeHandler GetHandler(DynamicMethod methodInfo, Module module)
		{
			return ConvertFastInvokeHandler(MethodInvoker.GetHandler((MethodInfo)methodInfo, false));
		}

		public static FastInvokeHandler GetHandler(MethodInfo methodInfo)
		{
			return ConvertFastInvokeHandler(MethodInvoker.GetHandler(methodInfo, false));
		}

		private static FastInvokeHandler ConvertFastInvokeHandler(FastInvokeHandler sourceDelegate)
		{
			return (FastInvokeHandler)Delegate.CreateDelegate(typeof(FastInvokeHandler), ((Delegate)(object)sourceDelegate).Target, ((Delegate)(object)sourceDelegate).Method);
		}
	}
	public class HarmonyInstance : Harmony
	{
		[Obsolete("Harmony.HarmonyInstance is obsolete. Please use HarmonyLib.Harmony instead.")]
		public HarmonyInstance(string id)
			: base(id)
		{
		}

		[Obsolete("Harmony.HarmonyInstance.Create is obsolete. Please use the HarmonyLib.Harmony Constructor instead.")]
		public static HarmonyInstance Create(string id)
		{
			if (id == null)
			{
				throw new Exception("id cannot be null");
			}
			return new HarmonyInstance(id);
		}

		[Obsolete("Harmony.HarmonyInstance.Patch is obsolete. Please use HarmonyLib.Harmony.Patch instead.")]
		public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null)
		{
			((Harmony)this).Patch(original, (HarmonyMethod)(object)prefix, (HarmonyMethod)(object)postfix, (HarmonyMethod)(object)transpiler, (HarmonyMethod)null, (HarmonyMethod)null);
			return null;
		}

		public void Unpatch(MethodBase original, HarmonyPatchType type, string harmonyID = null)
		{
			((Harmony)this).Unpatch(original, (HarmonyPatchType)type, harmonyID);
		}
	}
	[Obsolete("Harmony.HarmonyMethod is obsolete. Please use HarmonyLib.HarmonyMethod instead.")]
	public class HarmonyMethod : HarmonyMethod
	{
		[Obsolete("Harmony.HarmonyMethod.prioritiy is obsolete. Please use HarmonyLib.HarmonyMethod.priority instead.")]
		public int prioritiy = -1;

		[Obsolete("Harmony.HarmonyMethod is obsolete. Please use HarmonyLib.HarmonyMethod instead.")]
		public HarmonyMethod()
		{
		}

		[Obsolete("Harmony.HarmonyMethod is obsolete. Please use HarmonyLib.HarmonyMethod instead.")]
		public HarmonyMethod(MethodInfo method)
			: base(method)
		{
		}

		[Obsolete("Harmony.HarmonyMethod is obsolete. Please use HarmonyLib.HarmonyMethod instead.")]
		public HarmonyMethod(Type type, string name, Type[] parameters = null)
			: base(type, name, parameters)
		{
		}

		[Obsolete("Harmony.HarmonyMethod.Merge is obsolete. Please use HarmonyLib.HarmonyMethod.Merge instead.")]
		public static HarmonyMethod Merge(List<HarmonyMethod> attributes)
		{
			return (HarmonyMethod)(object)HarmonyMethod.Merge(Array.ConvertAll(attributes.ToArray(), (HarmonyMethod x) => (HarmonyMethod)(object)x).ToList());
		}

		public override string ToString()
		{
			return ((HarmonyMethod)this).ToString();
		}
	}
	[Obsolete("Harmony.HarmonyMethodExtensions is obsolete. Please use HarmonyLib.HarmonyMethodExtensions instead.")]
	public static class HarmonyMethodExtensions
	{
		[Obsolete("Harmony.HarmonyMethodExtensions.CopyTo is obsolete. Please use HarmonyLib.HarmonyMethodExtensions.CopyTo instead.")]
		public static void CopyTo(this HarmonyMethod from, HarmonyMethod to)
		{
			HarmonyMethodExtensions.CopyTo((HarmonyMethod)(object)from, (HarmonyMethod)(object)to);
		}

		[Obsolete("Harmony.HarmonyMethodExtensions.Clone is obsolete. Please use HarmonyLib.HarmonyMethodExtensions.Clone instead.")]
		public static HarmonyMethod Clone(this HarmonyMethod original)
		{
			return (HarmonyMethod)(object)HarmonyMethodExtensions.Clone((HarmonyMethod)(object)original);
		}

		[Obsolete("Harmony.HarmonyMethodExtensions.Merge is obsolete. Please use HarmonyLib.HarmonyMethodExtensions.Merge instead.")]
		public static HarmonyMethod Merge(this HarmonyMethod master, HarmonyMethod detail)
		{
			return (HarmonyMethod)(object)HarmonyMethodExtensions.Merge((HarmonyMethod)(object)master, (HarmonyMethod)(object)detail);
		}

		[Obsolete("Harmony.HarmonyMethodExtensions.GetHarmonyMethods(Type) is obsolete. Please use HarmonyLib.HarmonyMethodExtensions.GetFromType instead.")]
		public static List<HarmonyMethod> GetHarmonyMethods(this Type type)
		{
			return Array.ConvertAll(HarmonyMethodExtensions.GetFromType(type).ToArray(), (HarmonyMethod x) => (HarmonyMethod)(object)x).ToList();
		}

		[Obsolete("Harmony.HarmonyMethodExtensions.GetHarmonyMethods(MethodBase) is obsolete. Please use HarmonyLib.HarmonyMethodExtensions.GetFromMethod instead.")]
		public static List<HarmonyMethod> GetHarmonyMethods(this MethodBase method)
		{
			return Array.ConvertAll(HarmonyMethodExtensions.GetFromMethod(method).ToArray(), (HarmonyMethod x) => (HarmonyMethod)(object)x).ToList();
		}
	}
	[Obsolete("Harmony.PatchInfoSerialization is Only Here for Compatibility Reasons. Please use HarmonyLib.PatchInfoSerialization instead.")]
	public static class PatchInfoSerialization
	{
		private delegate PatchInfo HarmonyLib_PatchInfoSerialization_Deserialize_Delegate(byte[] bytes);

		private delegate int HarmonyLib_PatchInfoSerialization_PriorityComparer_Delegate(object obj, int index, int priority);

		private static HarmonyLib_PatchInfoSerialization_Deserialize_Delegate HarmonyLib_PatchInfoSerialization_Deserialize = Extensions.CreateDelegate<HarmonyLib_PatchInfoSerialization_Deserialize_Delegate>((MethodBase)AccessTools.Method("HarmonyLib.PatchInfoSerialization:Deserialize", (Type[])null, (Type[])null));

		private static HarmonyLib_PatchInfoSerialization_PriorityComparer_Delegate HarmonyLib_PatchInfoSerialization_PriorityComparer = Extensions.CreateDelegate<HarmonyLib_PatchInfoSerialization_PriorityComparer_Delegate>((MethodBase)AccessTools.Method("HarmonyLib.PatchInfoSerialization:PriorityComparer", (Type[])null, (Type[])null));

		[Obsolete("Harmony.PatchInfoSerialization.Deserialize is Only Here for Compatibility Reasons. Please use HarmonyLib.PatchInfoSerialization.Deserialize instead.")]
		public static PatchInfo Deserialize(byte[] bytes)
		{
			return (PatchInfo)(object)HarmonyLib_PatchInfoSerialization_Deserialize(bytes);
		}

		[Obsolete("Harmony.PatchInfoSerialization.PriorityComparer is Only Here for Compatibility Reasons. Please use HarmonyLib.PatchInfoSerialization.PriorityComparer instead.")]
		public static int PriorityComparer(object obj, int index, int priority, string[] before, string[] after)
		{
			return HarmonyLib_PatchInfoSerialization_PriorityComparer(obj, index, priority);
		}
	}
	[Serializable]
	[Obsolete("Harmony.PatchInfo is Only Here for Compatibility Reasons. Please use HarmonyLib.PatchInfo instead.")]
	public class PatchInfo : PatchInfo
	{
	}
	[Serializable]
	[Obsolete("Harmony.Patch is Only Here for Compatibility Reasons. Please use HarmonyLib.Patch instead.")]
	public class Patch : IComparable
	{
		public readonly MethodInfo patch;

		private Patch patchWrapper;

		[Obsolete("Harmony.Patch is Only Here for Compatibility Reasons. Please use HarmonyLib.Patch instead.")]
		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			this.patch = patch;
			patchWrapper = new Patch(patch, index, owner, priority, before, after, false);
		}

		public MethodInfo GetMethod(MethodBase original)
		{
			return patchWrapper.GetMethod(original);
		}

		public override bool Equals(object obj)
		{
			return ((object)patchWrapper).Equals(obj);
		}

		public int CompareTo(object obj)
		{
			return patchWrapper.CompareTo(obj);
		}

		public override int GetHashCode()
		{
			return ((object)patchWrapper).GetHashCode();
		}
	}
	[Obsolete("Harmony.Priority is Only Here for Compatibility Reasons. Please use HarmonyLib.Priority instead.")]
	public static class Priority
	{
		[Obsolete("Harmony.Priority.Last is Only Here for Compatibility Reasons. Please use HarmonyLib.Priority.Last instead.")]
		public const int Last = 0;

		[Obsolete("Harmony.Priority.VeryLow is Only Here for Compatibility Reasons. Please use HarmonyLib.Priority.VeryLow instead.")]
		public const int VeryLow = 100;

		[Obsolete("Harmony.Priority.Low is Only Here for Compatibility Reasons. Please use HarmonyLib.Priority.Low instead.")]
		public const int Low = 200;

		[Obsolete("Harmony.Priority.LowerThanNormal is Only Here for Compatibility Reasons. Please use HarmonyLib.Priority.LowerThanNormal instead.")]
		public const int LowerThanNormal = 300;

		[Obsolete("Harmony.Priority.Normal is Only Here for Compatibility Reasons. Please use HarmonyLib.Priority.Normal instead.")]
		public const int Normal = 400;

		[Obsolete("Harmony.Priority.HigherThanNormal is Only Here for Compatibility Reasons. Please use HarmonyLib.Priority.HigherThanNormal instead.")]
		public const int HigherThanNormal = 500;

		[Obsolete("Harmony.Priority.High is Only Here for Compatibility Reasons. Please use HarmonyLib.Priority.High instead.")]
		public const int High = 600;

		[Obsolete("Harmony.Priority.VeryHigh is Only Here for Compatibility Reasons. Please use HarmonyLib.Priority.VeryHigh instead.")]
		public const int VeryHigh = 700;

		[Obsolete("Harmony.Priority.First is Only Here for Compatibility Reasons. Please use HarmonyLib.Priority.First instead.")]
		public const int First = 800;
	}
	[Obsolete("Harmony.AccessTools is Only Here for Compatibility Reasons. Please use HarmonyLib.AccessTools instead.")]
	public static class AccessTools
	{
		public delegate ref U FieldRef<T, U>(T obj);

		public static BindingFlags all = AccessTools.all;

		public static Type TypeByName(string name)
		{
			return AccessTools.TypeByName(name);
		}

		public static T FindIncludingBaseTypes<T>(Type type, Func<Type, T> action) where T : class
		{
			return AccessTools.FindIncludingBaseTypes<T>(type, action);
		}

		public static T FindIncludingInnerTypes<T>(Type type, Func<Type, T> action) where T : class
		{
			return AccessTools.FindIncludingInnerTypes<T>(type, action);
		}

		public static FieldInfo Field(Type type, string name)
		{
			return AccessTools.Field(type, name);
		}

		public static FieldInfo Field(Type type, int idx)
		{
			return AccessTools.DeclaredField(type, idx);
		}

		public static PropertyInfo DeclaredProperty(Type type, string name)
		{
			return AccessTools.DeclaredProperty(type, name);
		}

		public static PropertyInfo Property(Type type, string name)
		{
			return AccessTools.Property(type, name);
		}

		public static MethodInfo DeclaredMethod(Type type, string name, Type[] parameters = null, Type[] generics = null)
		{
			return AccessTools.DeclaredMethod(type, name, parameters, generics);
		}

		public static MethodInfo Method(Type type, string name, Type[] parameters = null, Type[] generics = null)
		{
			return AccessTools.Method(type, name, parameters, generics);
		}

		public static MethodInfo Method(string typeColonMethodname, Type[] parameters = null, Type[] generics = null)
		{
			return AccessTools.Method(typeColonMethodname, parameters, generics);
		}

		public static List<string> GetMethodNames(Type type)
		{
			return AccessTools.GetMethodNames(type);
		}

		public static List<string> GetMethodNames(object instance)
		{
			return AccessTools.GetMethodNames(instance);
		}

		public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters = null)
		{
			return AccessTools.DeclaredConstructor(type, parameters, false);
		}

		public static ConstructorInfo Constructor(Type type, Type[] parameters = null)
		{
			return AccessTools.Constructor(type, parameters, false);
		}

		public static List<ConstructorInfo> GetDeclaredConstructors(Type type)
		{
			return AccessTools.GetDeclaredConstructors(type, (bool?)null);
		}

		public static List<MethodInfo> GetDeclaredMethods(Type type)
		{
			return AccessTools.GetDeclaredMethods(type);
		}

		public static List<PropertyInfo> GetDeclaredProperties(Type type)
		{
			return AccessTools.GetDeclaredProperties(type);
		}

		public static List<FieldInfo> GetDeclaredFields(Type type)
		{
			return AccessTools.GetDeclaredFields(type);
		}

		public static Type GetReturnedType(MethodBase method)
		{
			return AccessTools.GetReturnedType(method);
		}

		public static Type Inner(Type type, string name)
		{
			return AccessTools.Inner(type, name);
		}

		public static Type FirstInner(Type type, Func<Type, bool> predicate)
		{
			return AccessTools.FirstInner(type, predicate);
		}

		public static MethodInfo FirstMethod(Type type, Func<MethodInfo, bool> predicate)
		{
			return AccessTools.FirstMethod(type, predicate);
		}

		public static ConstructorInfo FirstConstructor(Type type, Func<ConstructorInfo, bool> predicate)
		{
			return AccessTools.FirstConstructor(type, predicate);
		}

		public static PropertyInfo FirstProperty(Type type, Func<PropertyInfo, bool> predicate)
		{
			return AccessTools.FirstProperty(type, predicate);
		}

		public static Type[] GetTypes(object[] parameters)
		{
			return AccessTools.GetTypes(parameters);
		}

		public static List<string> GetFieldNames(Type type)
		{
			return AccessTools.GetFieldNames(type);
		}

		public static List<string> GetFieldNames(object instance)
		{
			return AccessTools.GetFieldNames(instance);
		}

		public static List<string> GetPropertyNames(Type type)
		{
			return AccessTools.GetPropertyNames(type);
		}

		public static List<string> GetPropertyNames(object instance)
		{
			return AccessTools.GetPropertyNames(instance);
		}

		public static FieldRef<T, U> FieldRefAccess<T, U>(string fieldName)
		{
			return ConvertFieldRef<T, U>(AccessTools.FieldRefAccess<T, U>(fieldName));
		}

		public static ref U FieldRefAccess<T, U>(T instance, string fieldName)
		{
			return ref FieldRefAccess<T, U>(fieldName)(instance);
		}

		private static FieldRef<T, U> ConvertFieldRef<T, U>(FieldRef<T, U> sourceDelegate)
		{
			return (FieldRef<T, U>)Delegate.CreateDelegate(typeof(FieldRef<T, U>), ((Delegate)(object)sourceDelegate).Target, ((Delegate)(object)sourceDelegate).Method);
		}

		public static void ThrowMissingMemberException(Type type, params string[] names)
		{
			AccessTools.ThrowMissingMemberException(type, names);
		}

		public static object GetDefaultValue(Type type)
		{
			return AccessTools.GetDefaultValue(type);
		}

		public static object CreateInstance(Type type)
		{
			return AccessTools.CreateInstance(type);
		}

		public static bool IsStruct(Type type)
		{
			return AccessTools.IsStruct(type);
		}

		public static bool IsClass(Type type)
		{
			return AccessTools.IsClass(type);
		}

		public static bool IsValue(Type type)
		{
			return AccessTools.IsValue(type);
		}

		public static bool IsVoid(Type type)
		{
			return AccessTools.IsVoid(type);
		}
	}
	[Obsolete("Harmony.GeneralExtensions is Only Here for Compatibility Reasons. Please use HarmonyLib.GeneralExtensions instead.")]
	public static class GeneralExtensions
	{
		[Obsolete("Harmony.GeneralExtensions.Join is Only Here for Compatibility Reasons. Please use HarmonyLib.GeneralExtensions.Join instead.")]
		public static string Join<T>(this IEnumerable<T> enumeration, Func<T, string> converter = null, string delimiter = ", ")
		{
			return GeneralExtensions.Join<T>(enumeration, converter, delimiter);
		}

		[Obsolete("Harmony.GeneralExtensions.Description is Only Here for Compatibility Reasons. Please use HarmonyLib.GeneralExtensions.Description instead.")]
		public static string Description(this Type[] parameters)
		{
			return GeneralExtensions.Description(parameters);
		}

		[Obsolete("Harmony.GeneralExtensions.FullDescription is Only Here for Compatibility Reasons. Please use HarmonyLib.GeneralExtensions.FullDescription instead.")]
		public static string FullDescription(this MethodBase method)
		{
			return GeneralExtensions.FullDescription(method);
		}

		[Obsolete("Harmony.GeneralExtensions.Types is Only Here for Compatibility Reasons. Please use HarmonyLib.GeneralExtensions.Types instead.")]
		public static Type[] Types(this ParameterInfo[] pinfo)
		{
			return GeneralExtensions.Types(pinfo);
		}

		[Obsolete("Harmony.GeneralExtensions.GetValueSafe is Only Here for Compatibility Reasons. Please use HarmonyLib.GeneralExtensions.GetValueSafe instead.")]
		public static T GetValueSafe<S, T>(this Dictionary<S, T> dictionary, S key)
		{
			return GeneralExtensions.GetValueSafe<S, T>(dictionary, key);
		}

		[Obsolete("Harmony.GeneralExtensions.GetTypedValue is Only Here for Compatibility Reasons. Please use HarmonyLib.GeneralExtensions.GetTypedValue instead.")]
		public static T GetTypedValue<T>(this Dictionary<string, object> dictionary, string key)
		{
			return GeneralExtensions.GetTypedValue<T>(dictionary, key);
		}
	}
	[Obsolete("Harmony.CollectionExtensions is Only Here for Compatibility Reasons. Please use HarmonyLib.CollectionExtensions instead.")]
	public static class CollectionExtensions
	{
		[Obsolete("Harmony.CollectionExtensions.Do is Only Here for Compatibility Reasons. Please use HarmonyLib.CollectionExtensions.Do instead.")]
		public static void Do<T>(this IEnumerable<T> sequence, Action<T> action)
		{
			CollectionExtensions.Do<T>(sequence, action);
		}

		[Obsolete("Harmony.CollectionExtensions.DoIf is Only Here for Compatibility Reasons. Please use HarmonyLib.CollectionExtensions.DoIf instead.")]
		public static void DoIf<T>(this IEnumerable<T> sequence, Func<T, bool> condition, Action<T> action)
		{
			CollectionExtensions.DoIf<T>(sequence, condition, action);
		}

		[Obsolete("Harmony.CollectionExtensions.Add is Only Here for Compatibility Reasons. Please use HarmonyLib.CollectionExtensions.Add instead.")]
		public static IEnumerable<T> Add<T>(this IEnumerable<T> sequence, T item)
		{
			return CollectionExtensions.AddItem<T>(sequence, item);
		}

		[Obsolete("Harmony.CollectionExtensions.AddRangeToArray is Only Here for Compatibility Reasons. Please use HarmonyLib.CollectionExtensions.AddRangeToArray instead.")]
		public static T[] AddRangeToArray<T>(this T[] sequence, T[] items)
		{
			return CollectionExtensions.AddRangeToArray<T>(sequence, items);
		}

		[Obsolete("Harmony.CollectionExtensions.AddToArray is Only Here for Compatibility Reasons. Please use HarmonyLib.CollectionExtensions.AddToArray instead.")]
		public static T[] AddToArray<T>(this T[] sequence, T item)
		{
			return CollectionExtensions.AddToArray<T>(sequence, item);
		}
	}
	[Obsolete("Harmony.SymbolExtensions is Only Here for Compatibility Reasons. Please use HarmonyLib.SymbolExtensions instead.")]
	public static class SymbolExtensions
	{
		[Obsolete("Harmony.SymbolExtensions.GetMethodInfo is Only Here for Compatibility Reasons. Please use HarmonyLib.SymbolExtensions.GetMethodInfo instead.")]
		public static MethodInfo GetMethodInfo(Expression<Action> expression)
		{
			return SymbolExtensions.GetMethodInfo(expression);
		}

		[Obsolete("Harmony.SymbolExtensions.GetMethodInfo is Only Here for Compatibility Reasons. Please use HarmonyLib.SymbolExtensions.GetMethodInfo instead.")]
		public static MethodInfo GetMethodInfo<T>(Expression<Action<T>> expression)
		{
			return GetMethodInfo((LambdaExpression)expression);
		}

		[Obsolete("Harmony.SymbolExtensions.GetMethodInfo is Only Here for Compatibility Reasons. Please use HarmonyLib.SymbolExtensions.GetMethodInfo instead.")]
		public static MethodInfo GetMethodInfo<T, TResult>(Expression<Func<T, TResult>> expression)
		{
			return GetMethodInfo((LambdaExpression)expression);
		}

		[Obsolete("Harmony.SymbolExtensions.GetMethodInfo is Only Here for Compatibility Reasons. Please use HarmonyLib.SymbolExtensions.GetMethodInfo instead.")]
		public static MethodInfo GetMethodInfo(LambdaExpression expression)
		{
			return SymbolExtensions.GetMethodInfo(expression);
		}
	}
	[Obsolete("Harmony.HarmonyShield is Only Here for Compatibility Reasons. Please use MelonLoader.PatchShield instead.")]
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method)]
	public class HarmonyShield : PatchShield
	{
	}
}
namespace MelonLoader
{
	[AttributeUsage(AttributeTargets.Assembly)]
	public class HarmonyDontPatchAllAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class MelonAdditionalDependenciesAttribute : Attribute
	{
		public string[] AssemblyNames { get; internal set; }

		public MelonAdditionalDependenciesAttribute(params string[] assemblyNames)
		{
			AssemblyNames = assemblyNames;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class MelonAuthorColorAttribute : Attribute
	{
		public ConsoleColor Color { get; internal set; }

		public MelonAuthorColorAttribute()
		{
			Color = MelonLogger.DefaultTextColor;
		}

		public MelonAuthorColorAttribute(ConsoleColor color)
		{
			Color = ((color == ConsoleColor.Black) ? MelonLogger.DefaultMelonColor : color);
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class MelonColorAttribute : Attribute
	{
		public ConsoleColor Color { get; internal set; }

		public MelonColorAttribute()
		{
			Color = MelonLogger.DefaultMelonColor;
		}

		public MelonColorAttribute(ConsoleColor color)
		{
			Color = ((color == ConsoleColor.Black) ? MelonLogger.DefaultMelonColor : color);
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	public class MelonGameAttribute : Attribute
	{
		public string Developer { get; internal set; }

		public string Name { get; internal set; }

		public bool Universal => string.IsNullOrEmpty(Developer) || Developer.Equals("UNKNOWN") || string.IsNullOrEmpty(Name) || Name.Equals("UNKNOWN");

		public MelonGameAttribute(string developer = null, string name = null)
		{
			Developer = developer;
			Name = name;
		}

		public bool IsCompatible(string developer, string gameName)
		{
			return Universal || (!string.IsNullOrEmpty(developer) && Developer.Equals(developer) && !string.IsNullOrEmpty(gameName) && Name.Equals(gameName));
		}

		public bool IsCompatible(MelonGameAttribute att)
		{
			return IsCompatibleBecauseUniversal(att) || (att.Developer.Equals(Developer) && att.Name.Equals(Name));
		}

		public bool IsCompatibleBecauseUniversal(MelonGameAttribute att)
		{
			return att == null || Universal || att.Universal;
		}

		[Obsolete("IsCompatible(MelonModGameAttribute) is obsolete. Please use IsCompatible(MelonGameAttribute) instead.")]
		public bool IsCompatible(MelonModGameAttribute att)
		{
			return att == null || IsCompatibleBecauseUniversal(att) || (att.Developer.Equals(Developer) && att.GameName.Equals(Name));
		}

		[Obsolete("IsCompatible(MelonPluginGameAttribute) is obsolete. Please use IsCompatible(MelonGameAttribute) instead.")]
		public bool IsCompatible(MelonPluginGameAttribute att)
		{
			return att == null || IsCompatibleBecauseUniversal(att) || (att.Developer.Equals(Developer) && att.GameName.Equals(Name));
		}

		[Obsolete("IsCompatibleBecauseUniversal(MelonModGameAttribute) is obsolete. Please use IsCompatible(MelonGameAttribute) instead.")]
		public bool IsCompatibleBecauseUniversal(MelonModGameAttribute att)
		{
			return att == null || Universal || string.IsNullOrEmpty(att.Developer) || string.IsNullOrEmpty(att.GameName);
		}

		[Obsolete("IsCompatibleBecauseUniversal(MelonPluginGameAttribute) is obsolete. Please use IsCompatible(MelonGameAttribute) instead.")]
		public bool IsCompatibleBecauseUniversal(MelonPluginGameAttribute att)
		{
			return att == null || Universal || string.IsNullOrEmpty(att.Developer) || string.IsNullOrEmpty(att.GameName);
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	public class MelonGameVersionAttribute : Attribute
	{
		public string Version { get; internal set; }

		public bool Universal => string.IsNullOrEmpty(Version);

		public MelonGameVersionAttribute(string version = null)
		{
			Version = version;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class MelonIDAttribute : Attribute
	{
		public string ID { get; internal set; }

		public MelonIDAttribute(string id)
		{
			ID = id;
		}

		public MelonIDAttribute(int id)
		{
			ID = id.ToString();
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class MelonIncompatibleAssembliesAttribute : Attribute
	{
		public string[] AssemblyNames { get; internal set; }

		public MelonIncompatibleAssembliesAttribute(params string[] assemblyNames)
		{
			AssemblyNames = assemblyNames;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class MelonInfoAttribute : Attribute
	{
		public Type SystemType { get; internal set; }

		public string Name { get; internal set; }

		public string Version { get; internal set; }

		public SemVersion SemanticVersion { get; internal set; }

		public string Author { get; internal set; }

		public string DownloadLink { get; internal set; }

		public MelonInfoAttribute(Type type, string name, string version, string author, string downloadLink = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			SystemType = type;
			Name = name ?? "UNKNOWN";
			Author = author ?? "UNKNOWN";
			DownloadLink = downloadLink;
			if (string.IsNullOrEmpty(version))
			{
				Version = "1.0.0";
			}
			else
			{
				Version = version;
			}
			if (SemVersion.TryParse(Version, out var semver))
			{
				SemanticVersion = semver;
			}
		}

		public MelonInfoAttribute(Type type, string name, int versionMajor, int versionMinor, int versionRevision, string versionIdentifier, string author, string downloadLink = null)
			: this(type, name, string.Format("{0}.{1}.{2}{3}", versionMajor, versionMinor, versionRevision, string.IsNullOrEmpty(versionIdentifier) ? "" : versionIdentifier), author, downloadLink)
		{
		}

		public MelonInfoAttribute(Type type, string name, int versionMajor, int versionMinor, int versionRevision, string author, string downloadLink = null)
			: this(type, name, versionMajor, versionMinor, versionRevision, null, author, downloadLink)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class MelonOptionalDependenciesAttribute : Attribute
	{
		public string[] AssemblyNames { get; internal set; }

		public MelonOptionalDependenciesAttribute(params string[] assemblyNames)
		{
			AssemblyNames = assemblyNames;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class MelonPlatformAttribute : Attribute
	{
		public enum CompatiblePlatforms
		{
			UNIVERSAL,
			WINDOWS_X86,
			WINDOWS_X64
		}

		public CompatiblePlatforms[] Platforms { get; internal set; }

		public MelonPlatformAttribute(params CompatiblePlatforms[] platforms)
		{
			Platforms = platforms;
		}

		public bool IsCompatible(CompatiblePlatforms platform)
		{
			return Platforms == null || Platforms.Length == 0 || Platforms.Contains(platform);
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class MelonPlatformDomainAttribute : Attribute
	{
		public enum CompatibleDomains
		{
			UNIVERSAL,
			MONO,
			IL2CPP
		}

		public CompatibleDomains Domain { get; internal set; }

		public MelonPlatformDomainAttribute(CompatibleDomains domain = CompatibleDomains.UNIVERSAL)
		{
			Domain = domain;
		}

		public bool IsCompatible(CompatibleDomains domain)
		{
			return Domain == CompatibleDomains.UNIVERSAL || domain == CompatibleDomains.UNIVERSAL || Domain == domain;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class MelonPriorityAttribute : Attribute
	{
		public int Priority;

		public MelonPriorityAttribute(int priority = 0)
		{
			Priority = priority;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	public class MelonProcessAttribute : Attribute
	{
		public string EXE_Name { get; internal set; }

		public bool Universal => string.IsNullOrEmpty(EXE_Name);

		public MelonProcessAttribute(string exe_name = null)
		{
			EXE_Name = RemoveExtension(exe_name);
		}

		public bool IsCompatible(string processName)
		{
			return Universal || string.IsNullOrEmpty(processName) || RemoveExtension(processName) == EXE_Name;
		}

		private string RemoveExtension(string name)
		{
			return (name == null) ? null : (name.EndsWith(".exe") ? name.Remove(name.Length - 4) : name);
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method)]
	public class PatchShield : Attribute
	{
		private static FieldRef<object, MethodBase> PatchProcessor_OriginalRef;

		private static void LogException(Exception ex)
		{
			MelonLogger.Warning($"Patch Shield Exception: {ex}");
		}

		private static bool MethodCheck(MethodBase method)
		{
			return (object)method != null && method.DeclaringType.Assembly.GetCustomAttributes(typeof(PatchShield), inherit: false).Length == 0 && method.DeclaringType.GetCustomAttributes(typeof(PatchShield), inherit: false).Length == 0 && method.GetCustomAttributes(typeof(PatchShield), inherit: false).Length == 0;
		}

		internal static void Install()
		{
			Type typeFromHandle = typeof(PatchProcessor);
			Type typeFromHandle2 = typeof(PatchShield);
			PatchProcessor_OriginalRef = AccessTools.FieldRefAccess<MethodBase>(typeFromHandle, "original");
			try
			{
				Core.HarmonyInstance.Patch((MethodBase)AccessTools.Method("HarmonyLib.PatchFunctions:ReversePatch", (Type[])null, (Type[])null), AccessTools.Method(typeFromHandle2, "PatchMethod_PatchFunctions_ReversePatch", (Type[])null, (Type[])null).ToNewHarmonyMethod(), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				LogException(ex);
			}
			try
			{
				HarmonyMethod val = AccessTools.Method(typeFromHandle2, "PatchMethod_PatchProcessor_Unpatch", (Type[])null, (Type[])null).ToNewHarmonyMethod();
				foreach (MethodInfo item in from x in typeFromHandle.GetMethods(BindingFlags.Instance | BindingFlags.Public)
					where x.Name.Equals("Unpatch")
					select x)
				{
					Core.HarmonyInstance.Patch((MethodBase)item, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception ex2)
			{
				LogException(ex2);
			}
			try
			{
				Core.HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeFromHandle, "Patch", (Type[])null, (Type[])null), AccessTools.Method(typeFromHandle2, "PatchMethod_PatchProcessor_Patch", (Type[])null, (Type[])null).ToNewHarmonyMethod(), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex3)
			{
				LogException(ex3);
			}
			Hook.OnDetour = (Func<Hook, MethodBase, MethodBase, object, bool>)Delegate.Combine(Hook.OnDetour, (Func<Hook, MethodBase, MethodBase, object, bool>)((Hook detour, MethodBase originalMethod, MethodBase patchMethod, object delegateTarget) => MethodCheck(originalMethod)));
			ILHook.OnDetour = (Func<ILHook, MethodBase, Manipulator, bool>)Delegate.Combine(ILHook.OnDetour, (Func<ILHook, MethodBase, Manipulator, bool>)((ILHook detour, MethodBase originalMethod, Manipulator ilmanipulator) => MethodCheck(originalMethod)));
			Detour.OnDetour = (Func<Detour, MethodBase, MethodBase, bool>)Delegate.Combine(Detour.OnDetour, (Func<Detour, MethodBase, MethodBase, bool>)((Detour detour, MethodBase originalMethod, MethodBase patchMethod) => MethodCheck(originalMethod)));
		}

		private static bool PatchMethod_PatchFunctions_ReversePatch(MethodBase __1)
		{
			return MethodCheck(__1);
		}

		private static bool PatchMethod_PatchProcessor_Patch(PatchProcessor __instance)
		{
			return MethodCheck(PatchProcessor_OriginalRef.Invoke((object)__instance));
		}

		private static bool PatchMethod_PatchProcessor_Unpatch(PatchProcessor __instance)
		{
			return MethodCheck(PatchProcessor_OriginalRef.Invoke((object)__instance));
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	public class RegisterTypeInIl2Cpp : Attribute
	{
		internal static List<Assembly> registrationQueue = new List<Assembly>();

		internal static bool ready;

		internal bool LogSuccess = true;

		public RegisterTypeInIl2Cpp()
		{
		}

		public RegisterTypeInIl2Cpp(bool logSuccess)
		{
			LogSuccess = logSuccess;
		}

		public static void RegisterAssembly(Assembly asm)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return;
			}
			if (!ready)
			{
				registrationQueue.Add(asm);
				return;
			}
			IEnumerable<Type> validTypes = asm.GetValidTypes();
			if (validTypes == null || validTypes.Count() <= 0)
			{
				return;
			}
			foreach (Type item in validTypes)
			{
				object[] customAttributes = item.GetCustomAttributes(typeof(RegisterTypeInIl2Cpp), inherit: false);
				if (customAttributes != null && customAttributes.Length != 0)
				{
					RegisterTypeInIl2Cpp registerTypeInIl2Cpp = (RegisterTypeInIl2Cpp)customAttributes[0];
					if (registerTypeInIl2Cpp != null)
					{
						UnhollowerSupport.RegisterTypeInIl2CppDomain(item, registerTypeInIl2Cpp.LogSuccess);
					}
				}
			}
		}

		internal static void SetReady()
		{
			ready = true;
			if (registrationQueue == null)
			{
				return;
			}
			foreach (Assembly item in registrationQueue)
			{
				RegisterAssembly(item);
			}
			registrationQueue = null;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class VerifyLoaderBuildAttribute : Attribute
	{
		public string HashCode { get; internal set; }

		public VerifyLoaderBuildAttribute(string hashcode)
		{
			HashCode = hashcode;
		}

		public bool IsCompatible(string hashCode)
		{
			return string.IsNullOrEmpty(HashCode) || string.IsNullOrEmpty(hashCode) || HashCode == hashCode;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class VerifyLoaderVersionAttribute : Attribute
	{
		public SemVersion SemVer { get; private set; }

		public int Major { get; }

		public int Minor { get; }

		public int Patch { get; }

		public bool IsMinimum { get; private set; }

		public VerifyLoaderVersionAttribute(int major, int minor, int patch)
			: this(new SemVersion(major, minor, patch), is_minimum: false)
		{
		}

		public VerifyLoaderVersionAttribute(int major, int minor, int patch, bool is_minimum)
			: this(new SemVersion(major, minor, patch), is_minimum)
		{
		}

		public VerifyLoaderVersionAttribute(string version)
			: this(version, is_minimum: false)
		{
		}

		public VerifyLoaderVersionAttribute(string version, bool is_minimum)
			: this(SemVersion.Parse(version), is_minimum)
		{
		}

		public VerifyLoaderVersionAttribute(SemVersion semver, bool is_minimum)
		{
			SemVer = semver;
			IsMinimum = is_minimum;
		}

		public bool IsCompatible(SemVersion version)
		{
			return SemVer == null || version == null || (IsMinimum ? (SemVer <= version) : (SemVer == version));
		}

		public bool IsCompatible(string version)
		{
			SemVersion semver;
			return !SemVersion.TryParse(version, out semver) || IsCompatible(semver);
		}
	}
	public static class bHaptics
	{
		[Obsolete("MelonLoader.bHaptics.DeviceType is Only Here for Compatibility Reasons.")]
		public enum DeviceType
		{
			None,
			Tactal,
			TactSuit,
			Tactosy_arms,
			Tactosy_hands,
			Tactosy_feet
		}

		[Obsolete("MelonLoader.bHaptics.PositionType is Only Here for Compatibility Reasons. Please use bHapticsLib.PositionID instead.")]
		public enum PositionType
		{
			All = 0,
			Left = 1,
			Right = 2,
			Vest = 3,
			Head = 4,
			Racket = 5,
			HandL = 6,
			HandR = 7,
			FootL = 8,
			FootR = 9,
			ForearmL = 10,
			ForearmR = 11,
			VestFront = 201,
			VestBack = 202,
			GloveLeft = 203,
			GloveRight = 204,
			Custom1 = 251,
			Custom2 = 252,
			Custom3 = 253,
			Custom4 = 254
		}

		[Obsolete("MelonLoader.bHaptics.RotationOption is Only Here for Compatibility Reasons. Please use bHapticsLib.RotationOption instead.")]
		public class RotationOption
		{
			public float OffsetX;

			public float OffsetY;

			public RotationOption(float offsetX, float offsetY)
			{
				OffsetX = offsetX;
				OffsetY = offsetY;
			}

			public override string ToString()
			{
				return "RotationOption { OffsetX=" + OffsetX + ", OffsetY=" + OffsetY + " }";
			}
		}

		[Obsolete("MelonLoader.bHaptics.ScaleOption is Only Here for Compatibility Reasons. Please use bHapticsLib.ScaleOption instead.")]
		public class ScaleOption
		{
			public float Intensity;

			public float Duration;

			public ScaleOption(float intensity = 1f, float duration = 1f)
			{
				Intensity = intensity;
				Duration = duration;
			}

			public override string ToString()
			{
				return "ScaleOption { Intensity=" + Intensity + ", Duration=" + Duration + " }";
			}
		}

		[Obsolete("MelonLoader.bHaptics.DotPoint is Only Here for Compatibility Reasons. Please use bHapticsLib.DotPoint instead.")]
		public class DotPoint
		{
			public int Index;

			public int Intensity;

			public DotPoint(int index, int intensity = 50)
			{
				if (index < 0 || index > 19)
				{
					throw new Exception("Invalid argument index : " + index);
				}
				Intensity = MelonUtils.Clamp(intensity, 0, 100);
				Index = index;
			}

			public override string ToString()
			{
				return "DotPoint { Index=" + Index + ", Intensity=" + Intensity + " }";
			}
		}

		[Obsolete("MelonLoader.bHaptics.PathPoint is Only Here for Compatibility Reasons. Please use bHapticsLib.PathPoint instead.")]
		public struct PathPoint
		{
			public float X;

			public float Y;

			public int Intensity;

			public int MotorCount;

			public PathPoint(float x, float y, int intensity = 50, int motorCount = 3)
			{
				X = MelonUtils.Clamp(x, 0f, 1f);
				Y = MelonUtils.Clamp(y, 0f, 1f);
				Intensity = MelonUtils.Clamp(intensity, 0, 100);
				MotorCount = MelonUtils.Clamp(motorCount, 0, 3);
			}

			public override string ToString()
			{
				return "PathPoint { X=" + X + ", Y=" + Y + ", MotorCount=" + MotorCount + ", Intensity=" + Intensity + " }";
			}
		}

		[Obsolete("MelonLoader.bHaptics.FeedbackStatus is Only Here for Compatibility Reasons.")]
		public struct FeedbackStatus
		{
			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
			public int[] values;
		}

		private static Converter<DotPoint, DotPoint> DotPointConverter = (DotPoint x) => new DotPoint(0, 50)
		{
			Index = x.Index,
			Intensity = x.Intensity
		};

		private static Converter<PathPoint, PathPoint> PathPointConverter = (PathPoint x) => new PathPoint(0f, 0f, 50, 3)
		{
			X = x.X,
			Y = x.Y,
			Intensity = x.Intensity,
			MotorCount = x.MotorCount
		};

		public static bool WasError => false;

		[Obsolete("MelonLoader.bHaptics.IsPlaying is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.IsPlayingAny instead.")]
		public static bool IsPlaying()
		{
			return bHapticsManager.IsPlayingAny();
		}

		[Obsolete("MelonLoader.bHaptics.IsPlaying(string) is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.IsPlaying instead.")]
		public static bool IsPlaying(string key)
		{
			return bHapticsManager.IsPlaying(key);
		}

		[Obsolete("MelonLoader.bHaptics.IsDeviceConnected(DeviceType, bool) is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.IsDeviceConnected instead.")]
		public static bool IsDeviceConnected(DeviceType type, bool isLeft = true)
		{
			return IsDeviceConnected(DeviceTypeToPositionType(type, isLeft));
		}

		[Obsolete("MelonLoader.bHaptics.IsDeviceConnected(PositionType) is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.IsDeviceConnected instead.")]
		public static bool IsDeviceConnected(PositionType type)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return bHapticsManager.IsDeviceConnected(PositionTypeToPositionID(type));
		}

		[Obsolete("MelonLoader.bHaptics.IsFeedbackRegistered is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.IsPatternRegistered instead.")]
		public static bool IsFeedbackRegistered(string key)
		{
			return bHapticsManager.IsPatternRegistered(key);
		}

		[Obsolete("MelonLoader.bHaptics.RegisterFeedback is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.RegisterPatternFromJson instead.")]
		public static void RegisterFeedback(string key, string tactFileStr)
		{
			ProxyArray proxyArray = new ProxyArray();
			proxyArray["project"] = MelonLoader.TinyJSON.Decoder.Decode(tactFileStr);
			bHapticsManager.RegisterPatternFromJson(key, MelonLoader.TinyJSON.Encoder.Encode(proxyArray));
		}

		[Obsolete("MelonLoader.bHaptics.RegisterFeedbackFromTactFile is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.RegisterPatternFromJson instead.")]
		public static void RegisterFeedbackFromTactFile(string key, string tactFileStr)
		{
			bHapticsManager.RegisterPatternFromJson(key, tactFileStr);
		}

		[Obsolete("MelonLoader.bHaptics.RegisterFeedbackFromTactFileReflected is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.RegisterPatternSwappedFromJson instead.")]
		public static void RegisterFeedbackFromTactFileReflected(string key, string tactFileStr)
		{
			bHapticsManager.RegisterPatternSwappedFromJson(key, tactFileStr);
		}

		[Obsolete("MelonLoader.bHaptics.SubmitRegistered is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.PlayRegistered instead.")]
		public static void SubmitRegistered(string key)
		{
			bHapticsManager.PlayRegistered(key);
		}

		[Obsolete("MelonLoader.bHaptics.SubmitRegistered is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.PlayRegistered instead.")]
		public static void SubmitRegistered(string key, int startTimeMillis)
		{
			bHapticsManager.PlayRegistered(key, startTimeMillis);
		}

		[Obsolete("MelonLoader.bHaptics.SubmitRegistered is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.PlayRegistered instead.")]
		public static void SubmitRegistered(string key, string altKey, ScaleOption option)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			bHapticsManager.PlayRegistered(key, altKey, new ScaleOption(1f, 1f)
			{
				Duration = option.Duration,
				Intensity = option.Intensity
			});
		}

		[Obsolete("MelonLoader.bHaptics.SubmitRegistered is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.PlayRegistered instead.")]
		public static void SubmitRegistered(string key, string altKey, ScaleOption sOption, RotationOption rOption)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: 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_003a: 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_0059: Expected O, but got Unknown
			//IL_0059: Expected O, but got Unknown
			bHapticsManager.PlayRegistered(key, altKey, new ScaleOption(1f, 1f)
			{
				Duration = sOption.Duration,
				Intensity = sOption.Intensity
			}, new RotationOption(0f, 0f)
			{
				OffsetAngleX = rOption.OffsetX,
				OffsetY = rOption.OffsetY
			});
		}

		[Obsolete("MelonLoader.bHaptics.TurnOff is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.StopPlayingAll instead.")]
		public static void TurnOff()
		{
			bHapticsManager.StopPlayingAll();
		}

		[Obsolete("MelonLoader.bHaptics.TurnOff(string) is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.StopPlaying instead.")]
		public static void TurnOff(string key)
		{
			bHapticsManager.StopPlaying(key);
		}

		[Obsolete("MelonLoader.bHaptics.Submit is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.Play instead.")]
		public static void Submit(string key, DeviceType type, bool isLeft, byte[] bytes, int durationMillis)
		{
			Submit(key, DeviceTypeToPositionType(type, isLeft), bytes, durationMillis);
		}

		[Obsolete("MelonLoader.bHaptics.Submit is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.Play instead.")]
		public static void Submit(string key, PositionType position, byte[] bytes, int durationMillis)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			bHapticsManager.Play(key, durationMillis, PositionTypeToPositionID(position), bytes);
		}

		[Obsolete("MelonLoader.bHaptics.Submit is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.Play instead.")]
		public static void Submit(string key, DeviceType type, bool isLeft, List<DotPoint> points, int durationMillis)
		{
			Submit(key, DeviceTypeToPositionType(type, isLeft), points, durationMillis);
		}

		[Obsolete("MelonLoader.bHaptics.Submit is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.Play instead.")]
		public static void Submit(string key, PositionType position, List<DotPoint> points, int durationMillis)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			bHapticsManager.Play(key, durationMillis, PositionTypeToPositionID(position), points.ConvertAll(DotPointConverter));
		}

		[Obsolete("MelonLoader.bHaptics.Submit is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.Play instead.")]
		public static void Submit(string key, DeviceType type, bool isLeft, List<PathPoint> points, int durationMillis)
		{
			Submit(key, DeviceTypeToPositionType(type, isLeft), points, durationMillis);
		}

		[Obsolete("MelonLoader.bHaptics.Submit is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.Play instead.")]
		public static void Submit(string key, PositionType position, List<PathPoint> points, int durationMillis)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			bHapticsManager.Play<List<PathPoint>>(key, durationMillis, PositionTypeToPositionID(position), (DotPoint[])null, points.ConvertAll(PathPointConverter));
		}

		[Obsolete("MelonLoader.bHaptics.GetCurrentFeedbackStatus is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.GetDeviceStatus instead.")]
		public static FeedbackStatus GetCurrentFeedbackStatus(DeviceType type, bool isLeft = true)
		{
			return GetCurrentFeedbackStatus(DeviceTypeToPositionType(type, isLeft));
		}

		[Obsolete("MelonLoader.bHaptics.GetCurrentFeedbackStatus is Only Here for Compatibility Reasons. Please use bHapticsLib.bHapticsManager.GetDeviceStatus instead.")]
		public static FeedbackStatus GetCurrentFeedbackStatus(PositionType pos)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			FeedbackStatus result = default(FeedbackStatus);
			result.values = bHapticsManager.GetDeviceStatus(PositionTypeToPositionID(pos));
			return result;
		}

		[Obsolete("MelonLoader.bHaptics.DeviceTypeToPositionType is Only Here for Compatibility Reasons.")]
		public static PositionType DeviceTypeToPositionType(DeviceType pos, bool isLeft = true)
		{
			if (1 == 0)
			{
			}
			PositionType result = pos switch
			{
				DeviceType.Tactal => PositionType.Head, 
				DeviceType.TactSuit => PositionType.Vest, 
				DeviceType.Tactosy_arms => isLeft ? PositionType.ForearmL : PositionType.ForearmR, 
				DeviceType.Tactosy_feet => isLeft ? PositionType.FootL : PositionType.FootR, 
				DeviceType.Tactosy_hands => isLeft ? PositionType.HandL : PositionType.HandR, 
				_ => PositionType.Head, 
			};
			if (1 == 0)
			{
			}
			return result;
		}

		private static PositionID PositionTypeToPositionID(PositionType pos)
		{
			//IL_0051: 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_0094: 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_005d: 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_0066: Unknown result type (might be due to inval

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/BepInEx.MelonLoader.Loader/Tomlet.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Microsoft.CodeAnalysis;
using Tomlet.Attributes;
using Tomlet.Exceptions;
using Tomlet.Models;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("N/A")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("\n            Tomlet allows consumption and creation of TOML files (often used as configuration files) in .NET applications.\n            It supports serialization and deserialization of objects to and from TOML, and is compliant with version 1.0.0 of the TOML specification.\n        ")]
[assembly: AssemblyFileVersion("5.0.0.0")]
[assembly: AssemblyInformationalVersion("5.0.0+6c956664aa89c34c3d8ec0c0342ccd675646589d")]
[assembly: AssemblyProduct("Tomlet")]
[assembly: AssemblyTitle("Tomlet")]
[assembly: AssemblyVersion("5.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Tomlet
{
	internal static class Extensions
	{
		private static readonly HashSet<int> IllegalChars = new HashSet<int>
		{
			0, 1, 2, 3, 4, 5, 6, 7, 8, 11,
			14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
			24, 25, 26, 27, 28, 29, 30, 31, 127
		};

		internal static bool IsWhitespace(this int val)
		{
			if (!val.IsNewline())
			{
				return char.IsWhiteSpace((char)val);
			}
			return false;
		}

		internal static bool IsEquals(this int val)
		{
			return val == 61;
		}

		internal static bool IsSingleQuote(this int val)
		{
			return val == 39;
		}

		internal static bool IsDoubleQuote(this int val)
		{
			return val == 34;
		}

		internal static bool IsHashSign(this int val)
		{
			return val == 35;
		}

		internal static bool IsNewline(this int val)
		{
			if (val != 13)
			{
				return val == 10;
			}
			return true;
		}

		internal static bool IsDigit(this int val)
		{
			return char.IsDigit((char)val);
		}

		internal static bool IsComma(this int val)
		{
			return val == 44;
		}

		internal static bool IsPeriod(this int val)
		{
			return val == 46;
		}

		internal static bool IsEndOfArrayChar(this int val)
		{
			return val == 93;
		}

		internal static bool IsEndOfInlineObjectChar(this int val)
		{
			return val == 125;
		}

		internal static bool IsHexDigit(this char c)
		{
			if (IsDigit(c))
			{
				return true;
			}
			char c2 = char.ToUpperInvariant(c);
			if (c2 >= 'A')
			{
				return c2 <= 'F';
			}
			return false;
		}

		internal static bool TryPeek(this TomletStringReader reader, out int nextChar)
		{
			nextChar = reader.Peek();
			return nextChar != -1;
		}

		internal static int SkipWhitespace(this TomletStringReader reader)
		{
			return reader.ReadWhile((int c) => c.IsWhitespace()).Length;
		}

		internal static void SkipPotentialCarriageReturn(this TomletStringReader reader)
		{
			if (reader.TryPeek(out var nextChar) && nextChar == 13)
			{
				reader.Read();
			}
		}

		internal static void SkipAnyComment(this TomletStringReader reader)
		{
			if (reader.TryPeek(out var nextChar) && nextChar.IsHashSign())
			{
				reader.ReadWhile((int commentChar) => !commentChar.IsNewline());
			}
		}

		internal static int SkipAnyNewlineOrWhitespace(this TomletStringReader reader)
		{
			return reader.ReadWhile((int c) => c.IsNewline() || c.IsWhitespace()).Count((char c) => c == '\n');
		}

		internal static int SkipAnyCommentNewlineWhitespaceEtc(this TomletStringReader reader)
		{
			int num = 0;
			int nextChar;
			while (reader.TryPeek(out nextChar) && (nextChar.IsHashSign() || nextChar.IsNewline() || nextChar.IsWhitespace()))
			{
				if (nextChar.IsHashSign())
				{
					reader.SkipAnyComment();
				}
				num += reader.SkipAnyNewlineOrWhitespace();
			}
			return num;
		}

		internal static int SkipAnyNewline(this TomletStringReader reader)
		{
			return reader.ReadWhile((int c) => c.IsNewline()).Count((char c) => c == '\n');
		}

		internal static char[] ReadChars(this TomletStringReader reader, int count)
		{
			char[] array = new char[count];
			reader.ReadBlock(array, 0, count);
			return array;
		}

		internal static string ReadWhile(this TomletStringReader reader, Predicate<int> predicate)
		{
			StringBuilder stringBuilder = new StringBuilder();
			int nextChar;
			while (reader.TryPeek(out nextChar) && predicate(nextChar))
			{
				stringBuilder.Append((char)reader.Read());
			}
			return stringBuilder.ToString();
		}

		internal static bool ExpectAndConsume(this TomletStringReader reader, char expectWhat)
		{
			if (!reader.TryPeek(out var nextChar))
			{
				return false;
			}
			if (nextChar == expectWhat)
			{
				reader.Read();
				return true;
			}
			return false;
		}

		public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> pair, out TKey one, out TValue two)
		{
			one = pair.Key;
			two = pair.Value;
		}

		public static bool IsNullOrWhiteSpace(this string s)
		{
			if (!string.IsNullOrEmpty(s))
			{
				return string.IsNullOrEmpty(s.Trim());
			}
			return true;
		}

		internal static T? GetCustomAttribute<T>(this MemberInfo info) where T : Attribute
		{
			return (from a in info.GetCustomAttributes(inherit: false)
				where a is T
				select a).Cast<T>().FirstOrDefault();
		}

		internal static void EnsureLegalChar(this int c, int currentLineNum)
		{
			if (IllegalChars.Contains(c))
			{
				throw new TomlUnescapedUnicodeControlCharException(currentLineNum, c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool RuntimeCorrectContains(this string original, char c)
		{
			return original.Contains(c.ToString());
		}
	}
	internal static class TomlCompositeDeserializer
	{
		public static TomlSerializationMethods.Deserialize<object> For(Type type)
		{
			Type type2 = type;
			TomlSerializationMethods.Deserialize<object> deserialize;
			if (type2.IsEnum)
			{
				TomlSerializationMethods.Deserialize<object> stringDeserializer = TomlSerializationMethods.GetDeserializer(typeof(string));
				deserialize = delegate(TomlValue value)
				{
					string text = (string)stringDeserializer(value);
					try
					{
						return Enum.Parse(type2, text, ignoreCase: true);
					}
					catch (Exception)
					{
						throw new TomlEnumParseException(text, type2);
					}
				};
			}
			else
			{
				FieldInfo[] fields = type2.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				fields = fields.Where((FieldInfo f) => !f.IsNotSerialized && f.GetCustomAttribute<CompilerGeneratedAttribute>() == null).ToArray();
				PropertyInfo[] properties = type2.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				Dictionary<PropertyInfo, TomlPropertyAttribute> propsDict = (from p in properties
					where (object)p.GetSetMethod(nonPublic: true) != null
					select new KeyValuePair<PropertyInfo, TomlPropertyAttribute>(p, p.GetCustomAttribute<TomlPropertyAttribute>())).ToDictionary((KeyValuePair<PropertyInfo, TomlPropertyAttribute> tuple) => tuple.Key, (KeyValuePair<PropertyInfo, TomlPropertyAttribute> tuple) => tuple.Value);
				if (fields.Length + propsDict.Count == 0)
				{
					return delegate
					{
						try
						{
							return Activator.CreateInstance(type2);
						}
						catch (MissingMethodException)
						{
							throw new TomlInstantiationException(type2);
						}
					};
				}
				deserialize = delegate(TomlValue value)
				{
					if (!(value is TomlTable tomlTable))
					{
						throw new TomlTypeMismatchException(typeof(TomlTable), value.GetType(), type2);
					}
					object obj;
					try
					{
						obj = Activator.CreateInstance(type2);
					}
					catch (MissingMethodException)
					{
						throw new TomlInstantiationException(type2);
					}
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						if (tomlTable.TryGetValue(fieldInfo.Name, out TomlValue value2))
						{
							object value3;
							try
							{
								value3 = TomlSerializationMethods.GetDeserializer(fieldInfo.FieldType)(value2);
							}
							catch (TomlTypeMismatchException cause)
							{
								throw new TomlFieldTypeMismatchException(type2, fieldInfo, cause);
							}
							fieldInfo.SetValue(obj, value3);
						}
					}
					foreach (KeyValuePair<PropertyInfo, TomlPropertyAttribute> item in propsDict)
					{
						Extensions.Deconstruct(item, out var one, out var two);
						PropertyInfo propertyInfo = one;
						string key = two?.GetMappedString() ?? propertyInfo.Name;
						if (tomlTable.TryGetValue(key, out TomlValue value4))
						{
							object value5;
							try
							{
								value5 = TomlSerializationMethods.GetDeserializer(propertyInfo.PropertyType)(value4);
							}
							catch (TomlTypeMismatchException cause2)
							{
								throw new TomlPropertyTypeMismatchException(type2, propertyInfo, cause2);
							}
							propertyInfo.SetValue(obj, value5, null);
						}
					}
					return obj;
				};
			}
			TomlSerializationMethods.Register(type2, null, deserialize);
			return deserialize;
		}
	}
	internal static class TomlCompositeSerializer
	{
		public static TomlSerializationMethods.Serialize<object> For(Type type)
		{
			Type type2 = type;
			TomlSerializationMethods.Serialize<object> serialize;
			if (type2.IsEnum)
			{
				TomlSerializationMethods.Serialize<object> stringSerializer = TomlSerializationMethods.GetSerializer(typeof(string));
				serialize = (object? o) => stringSerializer(Enum.GetName(type2, o) ?? throw new ArgumentException($"Tomlet: Cannot serialize {o} as an enum of type {type2} because the enum type does not declare a name for that value"));
			}
			else
			{
				FieldInfo[] fields = type2.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				var fieldAttribs = fields.ToDictionary((FieldInfo f) => f, (FieldInfo f) => new
				{
					inline = f.GetCustomAttribute<TomlInlineCommentAttribute>(),
					preceding = f.GetCustomAttribute<TomlPrecedingCommentAttribute>()
				});
				PropertyInfo[] props = type2.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToArray();
				var propAttribs = props.ToDictionary((PropertyInfo p) => p, (PropertyInfo p) => new
				{
					inline = p.GetCustomAttribute<TomlInlineCommentAttribute>(),
					preceding = p.GetCustomAttribute<TomlPrecedingCommentAttribute>(),
					prop = p.GetCustomAttribute<TomlPropertyAttribute>()
				});
				bool isForcedNoInline = type2.GetCustomAttribute<TomlDoNotInlineObjectAttribute>() != null;
				fields = fields.Where((FieldInfo f) => !f.IsNotSerialized && f.GetCustomAttribute<CompilerGeneratedAttribute>() == null && !Enumerable.Contains(f.Name, '<')).ToArray();
				if (fields.Length + props.Length == 0)
				{
					return (object? _) => new TomlTable();
				}
				serialize = delegate(object? instance)
				{
					if (instance == null)
					{
						throw new ArgumentNullException("instance", "Object being serialized is null. TOML does not support null values.");
					}
					TomlTable tomlTable = new TomlTable
					{
						ForceNoInline = isForcedNoInline
					};
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						object value = fieldInfo.GetValue(instance);
						if (value != null)
						{
							TomlValue tomlValue = TomlSerializationMethods.GetSerializer(fieldInfo.FieldType)(value);
							if (tomlValue != null)
							{
								var anon = fieldAttribs[fieldInfo];
								if (!tomlTable.ContainsKey(fieldInfo.Name))
								{
									tomlValue.Comments.InlineComment = anon.inline?.Comment;
									tomlValue.Comments.PrecedingComment = anon.preceding?.Comment;
									tomlTable.PutValue(fieldInfo.Name, tomlValue);
								}
							}
						}
					}
					PropertyInfo[] array2 = props;
					foreach (PropertyInfo propertyInfo in array2)
					{
						if ((object)propertyInfo.GetGetMethod(nonPublic: true) != null && !(propertyInfo.Name == "EqualityContract"))
						{
							object value2 = propertyInfo.GetValue(instance, null);
							if (value2 != null)
							{
								TomlValue tomlValue2 = TomlSerializationMethods.GetSerializer(propertyInfo.PropertyType)(value2);
								if (tomlValue2 != null)
								{
									var anon2 = propAttribs[propertyInfo];
									tomlValue2.Comments.InlineComment = anon2.inline?.Comment;
									tomlValue2.Comments.PrecedingComment = anon2.preceding?.Comment;
									tomlTable.PutValue(anon2.prop?.GetMappedString() ?? propertyInfo.Name, tomlValue2);
								}
							}
						}
					}
					return tomlTable;
				};
			}
			TomlSerializationMethods.Register(type2, serialize, null);
			return serialize;
		}
	}
	internal static class TomlDateTimeUtils
	{
		private static readonly Regex DateTimeRegex = new Regex("^(?:(\\d+)-(0[1-9]|1[012])-(0[1-9]|[12]\\d|3[01]))?([\\sTt])?(?:([01]\\d|2[0-3]):([0-5]\\d):([0-5]\\d|60)(\\.\\d+)?((?:[Zz])|(?:[\\+|\\-](?:[01]\\d|2[0-3])(?::[0-6][0-9])?(?::[0-6][0-9])?))?)?$", RegexOptions.Compiled);

		internal static TomlValue? ParseDateString(string input, int lineNumber)
		{
			Match match = DateTimeRegex.Match(input);
			bool flag = !match.Groups[1].Value.IsNullOrWhiteSpace();
			bool flag2 = !string.IsNullOrEmpty(match.Groups[4].Value);
			bool flag3 = !match.Groups[5].Value.IsNullOrWhiteSpace();
			bool flag4 = !match.Groups[9].Value.IsNullOrWhiteSpace();
			if (flag && flag3 && !flag2)
			{
				throw new TomlDateTimeMissingSeparatorException(lineNumber);
			}
			if (flag2 && (!flag3 || !flag))
			{
				throw new TomlDateTimeUnnecessarySeparatorException(lineNumber);
			}
			if (flag4 && (!flag3 || !flag))
			{
				throw new TimeOffsetOnTomlDateOrTimeException(lineNumber, match.Groups[9].Value);
			}
			if (!flag)
			{
				return TomlLocalTime.Parse(input);
			}
			if (!flag3)
			{
				return TomlLocalDate.Parse(input);
			}
			if (!flag4)
			{
				return TomlLocalDateTime.Parse(input);
			}
			return TomlOffsetDateTime.Parse(input);
		}
	}
	public static class TomletMain
	{
		[NoCoverage]
		public static void RegisterMapper<T>(TomlSerializationMethods.Serialize<T>? serializer, TomlSerializationMethods.Deserialize<T>? deserializer)
		{
			TomlSerializationMethods.Register(serializer, deserializer);
		}

		public static T To<T>(string tomlString)
		{
			return To<T>(new TomlParser().Parse(tomlString));
		}

		public static T To<T>(TomlValue value)
		{
			return (T)To(typeof(T), value);
		}

		public static object To(Type what, TomlValue value)
		{
			return TomlSerializationMethods.GetDeserializer(what)(value);
		}

		public static TomlValue? ValueFrom<T>(T t)
		{
			if (t == null)
			{
				throw new ArgumentNullException("t");
			}
			return ValueFrom(t.GetType(), t);
		}

		public static TomlValue? ValueFrom(Type type, object t)
		{
			return TomlSerializationMethods.GetSerializer(type)(t);
		}

		public static TomlDocument DocumentFrom<T>(T t)
		{
			if (t == null)
			{
				throw new ArgumentNullException("t");
			}
			return DocumentFrom(t.GetType(), t);
		}

		public static TomlDocument DocumentFrom(Type type, object t)
		{
			TomlValue tomlValue = ValueFrom(type, t);
			if (!(tomlValue is TomlDocument result))
			{
				if (tomlValue is TomlTable from)
				{
					return new TomlDocument(from);
				}
				throw new TomlPrimitiveToDocumentException(type);
			}
			return result;
		}

		public static string TomlStringFrom<T>(T t)
		{
			return DocumentFrom(t).SerializedValue;
		}

		public static string TomlStringFrom(Type type, object t)
		{
			return DocumentFrom(type, t).SerializedValue;
		}
	}
	public class TomletStringReader : IDisposable
	{
		private string? _s;

		private int _pos;

		private int _length;

		public TomletStringReader(string s)
		{
			_s = s;
			_length = s.Length;
		}

		public void Backtrack(int amount)
		{
			if (_pos < amount)
			{
				throw new Exception("Cannot backtrack past the beginning of the string");
			}
			_pos -= amount;
		}

		public void Dispose()
		{
			_s = null;
			_pos = 0;
			_length = 0;
		}

		public int Peek()
		{
			if (_pos != _length)
			{
				return _s[_pos];
			}
			return -1;
		}

		public int Read()
		{
			if (_pos != _length)
			{
				return _s[_pos++];
			}
			return -1;
		}

		public int Read(char[] buffer, int index, int count)
		{
			int num = _length - _pos;
			if (num <= 0)
			{
				return num;
			}
			if (num > count)
			{
				num = count;
			}
			_s.CopyTo(_pos, buffer, index, num);
			_pos += num;
			return num;
		}

		public int ReadBlock(char[] buffer, int index, int count)
		{
			int num = 0;
			int num2;
			do
			{
				num += (num2 = Read(buffer, index + num, count - num));
			}
			while (num2 > 0 && num < count);
			return num;
		}
	}
	internal static class TomlKeyUtils
	{
		internal static void GetTopLevelAndSubKeys(string key, out string ourKeyName, out string restOfKey)
		{
			bool flag = (key.StartsWith("\"") && key.EndsWith("\"")) || (key.StartsWith("'") && key.EndsWith("'"));
			bool flag2 = !flag && (key.StartsWith("\"") || key.StartsWith("'"));
			if (!key.Contains(".") || flag)
			{
				ourKeyName = key;
				restOfKey = "";
				return;
			}
			if (!flag2)
			{
				string[] array = key.Split(new char[1] { '.' });
				ourKeyName = array[0];
			}
			else
			{
				ourKeyName = key;
				string text = ourKeyName.Substring(1);
				if (ourKeyName.Contains("\""))
				{
					ourKeyName = ourKeyName.Substring(0, 2 + text.IndexOf("\"", StringComparison.Ordinal));
				}
				else
				{
					ourKeyName = ourKeyName.Substring(0, 2 + text.IndexOf("'", StringComparison.Ordinal));
				}
			}
			restOfKey = key.Substring(ourKeyName.Length + 1);
			ourKeyName = ourKeyName.Trim();
		}
	}
	internal static class TomlNumberStyle
	{
		internal static NumberStyles FloatingPoint = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent;

		internal static NumberStyles Integer = NumberStyles.AllowLeadingSign | NumberStyles.AllowThousands;
	}
	public static class TomlNumberUtils
	{
		public static long? GetLongValue(string input)
		{
			bool flag = input.StartsWith("0o");
			bool flag2 = input.StartsWith("0x");
			bool flag3 = input.StartsWith("0b");
			if (flag3 || flag2 || flag)
			{
				input = input.Substring(2);
			}
			if (input.Contains("__") || input.Any((char c) => c != '_' && c != '-' && c != '+' && !char.IsDigit(c) && (c < 'a' || c > 'f')))
			{
				return null;
			}
			if (input.First() == '_')
			{
				return null;
			}
			if (input.Last() == '_')
			{
				return null;
			}
			input = input.Replace("_", "");
			try
			{
				if (flag3)
				{
					return Convert.ToInt64(input, 2);
				}
				if (flag)
				{
					return Convert.ToInt64(input, 8);
				}
				if (flag2)
				{
					return Convert.ToInt64(input, 16);
				}
				return Convert.ToInt64(input, 10);
			}
			catch (Exception)
			{
				return null;
			}
		}

		public static double? GetDoubleValue(string input)
		{
			string text = input.Substring(1);
			if (input == "nan" || input == "inf" || text == "nan" || text == "inf")
			{
				if (input == "nan" || text == "nan")
				{
					return double.NaN;
				}
				if (input == "inf")
				{
					return double.PositiveInfinity;
				}
				if (text == "inf")
				{
					return input.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity;
				}
			}
			if (input.Contains("__") || input.Any((char c) => c != '_' && c != '-' && c != '+' && c != 'e' && c != '.' && !char.IsDigit(c)))
			{
				return null;
			}
			if (input.First() == '_')
			{
				return null;
			}
			if (input.Last() == '_')
			{
				return null;
			}
			input = input.Replace("_", "");
			if (input.Contains("e"))
			{
				string[] array = input.Split(new char[1] { 'e' });
				if (array.Length != 2)
				{
					return null;
				}
				if (array[0].EndsWith("."))
				{
					return null;
				}
			}
			if (double.TryParse(input, TomlNumberStyle.FloatingPoint, CultureInfo.InvariantCulture, out var result))
			{
				return result;
			}
			return null;
		}
	}
	public class TomlParser
	{
		private static readonly char[] TrueChars = new char[4] { 't', 'r', 'u', 'e' };

		private static readonly char[] FalseChars = new char[5] { 'f', 'a', 'l', 's', 'e' };

		private int _lineNumber = 1;

		private string[] _tableNames = new string[0];

		private TomlTable? _currentTable;

		[NoCoverage]
		public static TomlDocument ParseFile(string filePath)
		{
			string input = File.ReadAllText(filePath);
			return new TomlParser().Parse(input);
		}

		public TomlDocument Parse(string input)
		{
			try
			{
				TomlDocument tomlDocument = new TomlDocument();
				using TomletStringReader tomletStringReader = new TomletStringReader(input);
				string text = null;
				int nextChar;
				while (tomletStringReader.TryPeek(out nextChar))
				{
					_lineNumber += tomletStringReader.SkipAnyNewlineOrWhitespace();
					text = ReadAnyPotentialMultilineComment(tomletStringReader);
					if (!tomletStringReader.TryPeek(out var nextChar2))
					{
						break;
					}
					if (nextChar2 == 91)
					{
						tomletStringReader.Read();
						if (!tomletStringReader.TryPeek(out var nextChar3))
						{
							throw new TomlEndOfFileException(_lineNumber);
						}
						TomlValue tomlValue = ((nextChar3 == 91) ? ((TomlValue)ReadTableArrayStatement(tomletStringReader, tomlDocument)) : ((TomlValue)ReadTableStatement(tomletStringReader, tomlDocument)));
						tomlValue.Comments.PrecedingComment = text;
						continue;
					}
					ReadKeyValuePair(tomletStringReader, out string key, out TomlValue value);
					value.Comments.PrecedingComment = text;
					text = null;
					if (_currentTable != null)
					{
						_currentTable.ParserPutValue(key, value, _lineNumber);
					}
					else
					{
						tomlDocument.ParserPutValue(key, value, _lineNumber);
					}
					tomletStringReader.SkipWhitespace();
					tomletStringReader.SkipPotentialCarriageReturn();
					if (!tomletStringReader.ExpectAndConsume('\n') && tomletStringReader.TryPeek(out var nextChar4))
					{
						throw new TomlMissingNewlineException(_lineNumber, (char)nextChar4);
					}
					_lineNumber++;
				}
				tomlDocument.TrailingComment = text;
				return tomlDocument;
			}
			catch (Exception ex) when (!(ex is TomlException))
			{
				throw new TomlInternalException(_lineNumber, ex);
			}
		}

		private void ReadKeyValuePair(TomletStringReader reader, out string key, out TomlValue value)
		{
			key = ReadKey(reader);
			reader.SkipWhitespace();
			if (!reader.ExpectAndConsume('='))
			{
				if (reader.TryPeek(out var nextChar))
				{
					throw new TomlMissingEqualsException(_lineNumber, (char)nextChar);
				}
				throw new TomlEndOfFileException(_lineNumber);
			}
			reader.SkipWhitespace();
			value = ReadValue(reader);
		}

		private string ReadKey(TomletStringReader reader)
		{
			reader.SkipWhitespace();
			if (!reader.TryPeek(out var nextChar))
			{
				return "";
			}
			if (nextChar.IsEquals())
			{
				throw new NoTomlKeyException(_lineNumber);
			}
			reader.SkipWhitespace();
			string text;
			if (nextChar.IsDoubleQuote())
			{
				reader.Read();
				if (reader.TryPeek(out var nextChar2) && nextChar2.IsDoubleQuote())
				{
					reader.Read();
					if (reader.TryPeek(out var nextChar3) && nextChar3.IsDoubleQuote())
					{
						throw new TomlTripleQuotedKeyException(_lineNumber);
					}
					return string.Empty;
				}
				text = "\"" + ReadSingleLineBasicString(reader, consumeClosingQuote: false).StringValue + "\"";
				if (!reader.ExpectAndConsume('"'))
				{
					throw new UnterminatedTomlKeyException(_lineNumber);
				}
			}
			else if (nextChar.IsSingleQuote())
			{
				reader.Read();
				text = "'" + ReadSingleLineLiteralString(reader, consumeClosingQuote: false).StringValue + "'";
				if (!reader.ExpectAndConsume('\''))
				{
					throw new UnterminatedTomlKeyException(_lineNumber);
				}
			}
			else
			{
				text = ReadKeyInternal(reader, (int keyChar) => keyChar.IsEquals() || keyChar.IsHashSign());
			}
			return text.Replace("\\n", "\n").Replace("\\t", "\t");
		}

		private string ReadKeyInternal(TomletStringReader reader, Func<int, bool> charSignalsEndOfKey)
		{
			List<string> list = new List<string>();
			int nextChar;
			while (reader.TryPeek(out nextChar))
			{
				if (charSignalsEndOfKey(nextChar))
				{
					return string.Join(".", list.ToArray());
				}
				if (nextChar.IsPeriod())
				{
					throw new TomlDoubleDottedKeyException(_lineNumber);
				}
				StringBuilder stringBuilder = new StringBuilder();
				while (reader.TryPeek(out nextChar))
				{
					nextChar.EnsureLegalChar(_lineNumber);
					int num = reader.SkipWhitespace();
					reader.TryPeek(out var nextChar2);
					if (nextChar2.IsPeriod())
					{
						list.Add(stringBuilder.ToString());
						reader.ExpectAndConsume('.');
						reader.SkipWhitespace();
						break;
					}
					if (num > 0 && charSignalsEndOfKey(nextChar2))
					{
						list.Add(stringBuilder.ToString());
						break;
					}
					reader.Backtrack(num);
					if (charSignalsEndOfKey(nextChar))
					{
						list.Add(stringBuilder.ToString());
						break;
					}
					if (num > 0)
					{
						throw new TomlWhitespaceInKeyException(_lineNumber);
					}
					stringBuilder.Append((char)reader.Read());
				}
			}
			throw new TomlEndOfFileException(_lineNumber);
		}

		private TomlValue ReadValue(TomletStringReader reader)
		{
			if (!reader.TryPeek(out var nextChar))
			{
				throw new TomlEndOfFileException(_lineNumber);
			}
			TomlValue tomlValue;
			switch (nextChar)
			{
			case 91:
				tomlValue = ReadArray(reader);
				break;
			case 123:
				tomlValue = ReadInlineTable(reader);
				break;
			case 34:
			case 39:
			{
				int num = reader.Read();
				if (reader.Peek() != num)
				{
					tomlValue = (num.IsSingleQuote() ? ReadSingleLineLiteralString(reader) : ReadSingleLineBasicString(reader));
					break;
				}
				reader.Read();
				int num2 = reader.Peek();
				if (num2 == num)
				{
					reader.Read();
					tomlValue = (num.IsSingleQuote() ? ReadMultiLineLiteralString(reader) : ReadMultiLineBasicString(reader));
					break;
				}
				if (num2.IsWhitespace() || num2.IsNewline() || num2.IsHashSign() || num2.IsComma() || num2.IsEndOfArrayChar() || num2 == -1)
				{
					tomlValue = TomlString.Empty;
					break;
				}
				throw new TomlStringException(_lineNumber);
			}
			case 43:
			case 45:
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
			case 105:
			case 110:
			{
				string text = reader.ReadWhile((int valueChar) => !valueChar.IsEquals() && !valueChar.IsNewline() && !valueChar.IsHashSign() && !valueChar.IsComma() && !valueChar.IsEndOfArrayChar() && !valueChar.IsEndOfInlineObjectChar()).ToLowerInvariant().Trim();
				tomlValue = ((!Enumerable.Contains(text, ':') && !Enumerable.Contains(text, 't') && !Enumerable.Contains(text, ' ') && !Enumerable.Contains(text, 'z')) ? ((!Enumerable.Contains(text, '.') && (!Enumerable.Contains(text, 'e') || text.StartsWith("0x")) && !Enumerable.Contains(text, 'n') && !Enumerable.Contains(text, 'i')) ? (TomlLong.Parse(text) ?? TomlDateTimeUtils.ParseDateString(text, _lineNumber) ?? throw new InvalidTomlNumberException(_lineNumber, text)) : (TomlDouble.Parse(text) ?? TomlDateTimeUtils.ParseDateString(text, _lineNumber) ?? throw new InvalidTomlNumberException(_lineNumber, text))) : (TomlDateTimeUtils.ParseDateString(text, _lineNumber) ?? throw new InvalidTomlDateTimeException(_lineNumber, text)));
				break;
			}
			case 116:
			{
				char[] second2 = reader.ReadChars(4);
				if (!TrueChars.SequenceEqual(second2))
				{
					throw new TomlInvalidValueException(_lineNumber, (char)nextChar);
				}
				tomlValue = TomlBoolean.True;
				break;
			}
			case 102:
			{
				char[] second = reader.ReadChars(5);
				if (!FalseChars.SequenceEqual(second))
				{
					throw new TomlInvalidValueException(_lineNumber, (char)nextChar);
				}
				tomlValue = TomlBoolean.False;
				break;
			}
			default:
				throw new TomlInvalidValueException(_lineNumber, (char)nextChar);
			}
			reader.SkipWhitespace();
			tomlValue.Comments.InlineComment = ReadAnyPotentialInlineComment(reader);
			return tomlValue;
		}

		private TomlValue ReadSingleLineBasicString(TomletStringReader reader, bool consumeClosingQuote = true)
		{
			StringBuilder stringBuilder = new StringBuilder();
			bool flag = false;
			bool fourDigitUnicodeMode = false;
			bool eightDigitUnicodeMode = false;
			StringBuilder stringBuilder2 = new StringBuilder();
			int nextChar;
			while (reader.TryPeek(out nextChar))
			{
				nextChar.EnsureLegalChar(_lineNumber);
				if (nextChar == 34 && !flag)
				{
					break;
				}
				reader.Read();
				if (nextChar == 92 && !flag)
				{
					flag = true;
				}
				else if (flag)
				{
					flag = false;
					char? c = HandleEscapedChar(nextChar, out fourDigitUnicodeMode, out eightDigitUnicodeMode);
					if (c.HasValue)
					{
						stringBuilder.Append(c.Value);
					}
				}
				else if (fourDigitUnicodeMode || eightDigitUnicodeMode)
				{
					stringBuilder2.Append((char)nextChar);
					if ((fourDigitUnicodeMode && stringBuilder2.Length == 4) || (eightDigitUnicodeMode && stringBuilder2.Length == 8))
					{
						string unicodeString = stringBuilder2.ToString();
						stringBuilder.Append(DecipherUnicodeEscapeSequence(unicodeString, fourDigitUnicodeMode));
						fourDigitUnicodeMode = false;
						eightDigitUnicodeMode = false;
						stringBuilder2 = new StringBuilder();
					}
				}
				else
				{
					if (nextChar.IsNewline())
					{
						throw new UnterminatedTomlStringException(_lineNumber);
					}
					stringBuilder.Append((char)nextChar);
				}
			}
			if (consumeClosingQuote && !reader.ExpectAndConsume('"'))
			{
				throw new UnterminatedTomlStringException(_lineNumber);
			}
			return new TomlString(stringBuilder.ToString());
		}

		private string DecipherUnicodeEscapeSequence(string unicodeString, bool fourDigitMode)
		{
			if (unicodeString.Any((char c) => !c.IsHexDigit()))
			{
				throw new InvalidTomlEscapeException(_lineNumber, $"\\{(fourDigitMode ? 'u' : 'U')}{unicodeString}");
			}
			if (fourDigitMode)
			{
				return ((char)short.Parse(unicodeString, NumberStyles.HexNumber)).ToString();
			}
			return char.ConvertFromUtf32(int.Parse(unicodeString, NumberStyles.HexNumber));
		}

		private char? HandleEscapedChar(int escapedChar, out bool fourDigitUnicodeMode, out bool eightDigitUnicodeMode, bool allowNewline = false)
		{
			eightDigitUnicodeMode = false;
			fourDigitUnicodeMode = false;
			char value;
			switch (escapedChar)
			{
			case 98:
				value = '\b';
				break;
			case 116:
				value = '\t';
				break;
			case 110:
				value = '\n';
				break;
			case 102:
				value = '\f';
				break;
			case 114:
				value = '\r';
				break;
			case 34:
				value = '"';
				break;
			case 92:
				value = '\\';
				break;
			case 117:
				fourDigitUnicodeMode = true;
				return null;
			case 85:
				eightDigitUnicodeMode = true;
				return null;
			default:
				if (allowNewline && escapedChar.IsNewline())
				{
					return null;
				}
				throw new InvalidTomlEscapeException(_lineNumber, $"\\{escapedChar}");
			}
			return value;
		}

		private TomlValue ReadSingleLineLiteralString(TomletStringReader reader, bool consumeClosingQuote = true)
		{
			string text = reader.ReadWhile((int valueChar) => !valueChar.IsSingleQuote() && !valueChar.IsNewline());
			foreach (int item in ((IEnumerable<char>)text).Select((Func<char, int>)((char c) => c)))
			{
				item.EnsureLegalChar(_lineNumber);
			}
			if (!reader.TryPeek(out var nextChar))
			{
				throw new TomlEndOfFileException(_lineNumber);
			}
			if (!nextChar.IsSingleQuote())
			{
				throw new UnterminatedTomlStringException(_lineNumber);
			}
			if (consumeClosingQuote)
			{
				reader.Read();
			}
			return new TomlString(text);
		}

		private TomlValue ReadMultiLineLiteralString(TomletStringReader reader)
		{
			StringBuilder stringBuilder = new StringBuilder();
			_lineNumber += reader.SkipAnyNewline();
			int nextChar;
			while (reader.TryPeek(out nextChar))
			{
				int num = reader.Read();
				num.EnsureLegalChar(_lineNumber);
				if (!num.IsSingleQuote())
				{
					stringBuilder.Append((char)num);
					if (num == 10)
					{
						_lineNumber++;
					}
					continue;
				}
				if (!reader.TryPeek(out var nextChar2) || !nextChar2.IsSingleQuote())
				{
					stringBuilder.Append('\'');
					continue;
				}
				reader.Read();
				if (!reader.TryPeek(out var nextChar3) || !nextChar3.IsSingleQuote())
				{
					stringBuilder.Append('\'');
					stringBuilder.Append('\'');
					continue;
				}
				reader.Read();
				if (!reader.TryPeek(out var nextChar4) || !nextChar4.IsSingleQuote())
				{
					break;
				}
				reader.Read();
				stringBuilder.Append('\'');
				if (!reader.TryPeek(out var nextChar5) || !nextChar5.IsSingleQuote())
				{
					break;
				}
				reader.Read();
				stringBuilder.Append('\'');
				if (!reader.TryPeek(out var nextChar6) || !nextChar6.IsSingleQuote())
				{
					break;
				}
				throw new TripleQuoteInTomlMultilineLiteralException(_lineNumber);
			}
			return new TomlString(stringBuilder.ToString());
		}

		private TomlValue ReadMultiLineBasicString(TomletStringReader reader)
		{
			StringBuilder stringBuilder = new StringBuilder();
			bool flag = false;
			bool fourDigitUnicodeMode = false;
			bool eightDigitUnicodeMode = false;
			StringBuilder stringBuilder2 = new StringBuilder();
			_lineNumber += reader.SkipAnyNewline();
			int nextChar;
			while (reader.TryPeek(out nextChar))
			{
				int num = reader.Read();
				num.EnsureLegalChar(_lineNumber);
				if (num == 92 && !flag)
				{
					flag = true;
					continue;
				}
				if (flag)
				{
					flag = false;
					char? c = HandleEscapedChar(num, out fourDigitUnicodeMode, out eightDigitUnicodeMode, allowNewline: true);
					if (c.HasValue)
					{
						stringBuilder.Append(c.Value);
					}
					else if (num.IsNewline())
					{
						if (num == 13 && !reader.ExpectAndConsume('\n'))
						{
							throw new Exception($"Found a CR without an LF on line {_lineNumber}");
						}
						_lineNumber++;
						reader.SkipAnyNewlineOrWhitespace();
					}
					continue;
				}
				if (fourDigitUnicodeMode || eightDigitUnicodeMode)
				{
					stringBuilder2.Append((char)num);
					if ((fourDigitUnicodeMode && stringBuilder2.Length == 4) || (eightDigitUnicodeMode && stringBuilder2.Length == 8))
					{
						string unicodeString = stringBuilder2.ToString();
						stringBuilder.Append(DecipherUnicodeEscapeSequence(unicodeString, fourDigitUnicodeMode));
						fourDigitUnicodeMode = false;
						eightDigitUnicodeMode = false;
						stringBuilder2 = new StringBuilder();
					}
					continue;
				}
				if (!num.IsDoubleQuote())
				{
					if (num == 10)
					{
						_lineNumber++;
					}
					stringBuilder.Append((char)num);
					continue;
				}
				if (!reader.TryPeek(out var nextChar2) || !nextChar2.IsDoubleQuote())
				{
					stringBuilder.Append('"');
					continue;
				}
				reader.Read();
				if (!reader.TryPeek(out var nextChar3) || !nextChar3.IsDoubleQuote())
				{
					stringBuilder.Append('"');
					stringBuilder.Append('"');
					continue;
				}
				reader.Read();
				if (!reader.TryPeek(out var nextChar4) || !nextChar4.IsDoubleQuote())
				{
					break;
				}
				reader.Read();
				stringBuilder.Append('"');
				if (!reader.TryPeek(out var nextChar5) || !nextChar5.IsDoubleQuote())
				{
					break;
				}
				reader.Read();
				stringBuilder.Append('"');
				if (!reader.TryPeek(out var nextChar6) || !nextChar6.IsDoubleQuote())
				{
					break;
				}
				throw new TripleQuoteInTomlMultilineSimpleStringException(_lineNumber);
			}
			return new TomlString(stringBuilder.ToString());
		}

		private TomlArray ReadArray(TomletStringReader reader)
		{
			if (!reader.ExpectAndConsume('['))
			{
				throw new ArgumentException("Internal Tomlet Bug: ReadArray called and first char is not a [");
			}
			_lineNumber += reader.SkipAnyCommentNewlineWhitespaceEtc();
			TomlArray tomlArray = new TomlArray();
			int nextChar;
			while (reader.TryPeek(out nextChar))
			{
				_lineNumber += reader.SkipAnyCommentNewlineWhitespaceEtc();
				if (!reader.TryPeek(out var nextChar2))
				{
					throw new TomlEndOfFileException(_lineNumber);
				}
				if (nextChar2.IsEndOfArrayChar())
				{
					break;
				}
				tomlArray.ArrayValues.Add(ReadValue(reader));
				_lineNumber += reader.SkipAnyNewlineOrWhitespace();
				if (!reader.TryPeek(out var nextChar3))
				{
					throw new TomlEndOfFileException(_lineNumber);
				}
				if (nextChar3.IsEndOfArrayChar())
				{
					break;
				}
				if (!nextChar3.IsComma())
				{
					throw new TomlArraySyntaxException(_lineNumber, (char)nextChar3);
				}
				reader.ExpectAndConsume(',');
			}
			reader.ExpectAndConsume(']');
			return tomlArray;
		}

		private TomlTable ReadInlineTable(TomletStringReader reader)
		{
			if (!reader.ExpectAndConsume('{'))
			{
				throw new ArgumentException("Internal Tomlet Bug: ReadInlineTable called and first char is not a {");
			}
			_lineNumber += reader.SkipAnyCommentNewlineWhitespaceEtc();
			TomlTable tomlTable = new TomlTable
			{
				Defined = true
			};
			int nextChar;
			while (reader.TryPeek(out nextChar))
			{
				reader.SkipWhitespace();
				if (!reader.TryPeek(out var nextChar2))
				{
					throw new TomlEndOfFileException(_lineNumber);
				}
				if (nextChar2.IsEndOfInlineObjectChar())
				{
					break;
				}
				if (nextChar2.IsNewline())
				{
					throw new NewLineInTomlInlineTableException(_lineNumber);
				}
				try
				{
					ReadKeyValuePair(reader, out string key, out TomlValue value);
					tomlTable.ParserPutValue(key, value, _lineNumber);
				}
				catch (TomlException ex) when (ex is TomlMissingEqualsException || ex is NoTomlKeyException || ex is TomlWhitespaceInKeyException)
				{
					throw new InvalidTomlInlineTableException(_lineNumber, ex);
				}
				if (!reader.TryPeek(out var nextChar3))
				{
					throw new TomlEndOfFileException(_lineNumber);
				}
				if (!reader.ExpectAndConsume(','))
				{
					reader.SkipWhitespace();
					if (!reader.TryPeek(out nextChar3))
					{
						throw new TomlEndOfFileException(_lineNumber);
					}
					if (nextChar3.IsEndOfInlineObjectChar())
					{
						break;
					}
					throw new TomlInlineTableSeparatorException(_lineNumber, (char)nextChar3);
				}
			}
			reader.ExpectAndConsume('}');
			tomlTable.Locked = true;
			return tomlTable;
		}

		private TomlTable ReadTableStatement(TomletStringReader reader, TomlDocument document)
		{
			string text = reader.ReadWhile((int c) => !c.IsEndOfArrayChar() && !c.IsNewline());
			TomlTable parent = document;
			string relativeName = text;
			FindParentAndRelativeKey(ref parent, ref relativeName);
			TomlTable tomlTable;
			try
			{
				if (parent.ContainsKey(relativeName))
				{
					try
					{
						tomlTable = (TomlTable)parent.GetValue(relativeName);
						if (tomlTable.Defined)
						{
							throw new TomlTableRedefinitionException(_lineNumber, text);
						}
					}
					catch (InvalidCastException)
					{
						throw new TomlKeyRedefinitionException(_lineNumber, text);
					}
				}
				else
				{
					tomlTable = new TomlTable
					{
						Defined = true
					};
					parent.ParserPutValue(relativeName, tomlTable, _lineNumber);
				}
			}
			catch (TomlContainsDottedKeyNonTableException ex2)
			{
				throw new TomlDottedKeyParserException(_lineNumber, ex2.Key);
			}
			if (!reader.TryPeek(out var _))
			{
				throw new TomlEndOfFileException(_lineNumber);
			}
			if (!reader.ExpectAndConsume(']'))
			{
				throw new UnterminatedTomlTableNameException(_lineNumber);
			}
			reader.SkipWhitespace();
			tomlTable.Comments.InlineComment = ReadAnyPotentialInlineComment(reader);
			reader.SkipPotentialCarriageReturn();
			if (!reader.TryPeek(out var nextChar2))
			{
				throw new TomlEndOfFileException(_lineNumber);
			}
			if (!nextChar2.IsNewline())
			{
				throw new TomlMissingNewlineException(_lineNumber, (char)nextChar2);
			}
			_currentTable = tomlTable;
			_tableNames = text.Split(new char[1] { '.' });
			return tomlTable;
		}

		private TomlArray ReadTableArrayStatement(TomletStringReader reader, TomlDocument document)
		{
			if (!reader.ExpectAndConsume('['))
			{
				throw new ArgumentException("Internal Tomlet Bug: ReadTableArrayStatement called and first char is not a [");
			}
			string text = reader.ReadWhile((int c) => !c.IsEndOfArrayChar() && !c.IsNewline());
			if (!reader.ExpectAndConsume(']') || !reader.ExpectAndConsume(']'))
			{
				throw new UnterminatedTomlTableArrayException(_lineNumber);
			}
			TomlTable parent = document;
			string relativeName = text;
			FindParentAndRelativeKey(ref parent, ref relativeName);
			if (parent == document && Enumerable.Contains(relativeName, '.'))
			{
				throw new MissingIntermediateInTomlTableArraySpecException(_lineNumber, relativeName);
			}
			TomlArray tomlArray2;
			if (parent.ContainsKey(relativeName))
			{
				if (!(parent.GetValue(relativeName) is TomlArray tomlArray))
				{
					throw new TomlTableArrayAlreadyExistsAsNonArrayException(_lineNumber, text);
				}
				tomlArray2 = tomlArray;
				if (!tomlArray2.IsLockedToBeTableArray)
				{
					throw new TomlNonTableArrayUsedAsTableArrayException(_lineNumber, text);
				}
			}
			else
			{
				tomlArray2 = new TomlArray
				{
					IsLockedToBeTableArray = true
				};
				parent.ParserPutValue(relativeName, tomlArray2, _lineNumber);
			}
			_currentTable = new TomlTable
			{
				Defined = true
			};
			tomlArray2.ArrayValues.Add(_currentTable);
			_tableNames = text.Split(new char[1] { '.' });
			return tomlArray2;
		}

		private void FindParentAndRelativeKey(ref TomlTable parent, ref string relativeName)
		{
			for (int i = 0; i < _tableNames.Length; i++)
			{
				string text = _tableNames[i];
				if (!relativeName.StartsWith(text + "."))
				{
					break;
				}
				TomlValue value = parent.GetValue(text);
				if (value is TomlTable tomlTable)
				{
					parent = tomlTable;
				}
				else
				{
					if (!(value is TomlArray source))
					{
						throw new TomlTypeMismatchException(typeof(TomlArray), value.GetType(), typeof(TomlArray));
					}
					parent = (TomlTable)source.Last();
				}
				relativeName = relativeName.Substring(text.Length + 1);
			}
		}

		private string? ReadAnyPotentialInlineComment(TomletStringReader reader)
		{
			if (!reader.ExpectAndConsume('#'))
			{
				return null;
			}
			string text = reader.ReadWhile((int c) => !c.IsNewline()).Trim();
			if (text.Length < 1)
			{
				return null;
			}
			if (text[0] == ' ')
			{
				text = text.Substring(1);
			}
			foreach (int item in ((IEnumerable<char>)text).Select((Func<char, int>)((char c) => c)))
			{
				item.EnsureLegalChar(_lineNumber);
			}
			return text;
		}

		private string? ReadAnyPotentialMultilineComment(TomletStringReader reader)
		{
			StringBuilder stringBuilder = new StringBuilder();
			while (reader.ExpectAndConsume('#'))
			{
				string text = reader.ReadWhile((int c) => !c.IsNewline());
				if (text[0] == ' ')
				{
					text = text.Substring(1);
				}
				foreach (int item in ((IEnumerable<char>)text).Select((Func<char, int>)((char c) => c)))
				{
					item.EnsureLegalChar(_lineNumber);
				}
				stringBuilder.Append(text);
				_lineNumber += reader.SkipAnyNewlineOrWhitespace();
			}
			if (stringBuilder.Length == 0)
			{
				return null;
			}
			return stringBuilder.ToString();
		}
	}
	public static class TomlSerializationMethods
	{
		public delegate T Deserialize<out T>(TomlValue value);

		public delegate TomlValue? Serialize<in T>(T? t);

		private static MethodInfo _stringKeyedDictionaryMethod;

		private static MethodInfo _genericDictionarySerializerMethod;

		private static MethodInfo _genericNullableSerializerMethod;

		private static readonly Dictionary<Type, Delegate> Deserializers;

		private static readonly Dictionary<Type, Delegate> Serializers;

		[NoCoverage]
		static TomlSerializationMethods()
		{
			_stringKeyedDictionaryMethod = typeof(TomlSerializationMethods).GetMethod("StringKeyedDictionaryDeserializerFor", BindingFlags.Static | BindingFlags.NonPublic);
			_genericDictionarySerializerMethod = typeof(TomlSerializationMethods).GetMethod("GenericDictionarySerializer", BindingFlags.Static | BindingFlags.NonPublic);
			_genericNullableSerializerMethod = typeof(TomlSerializationMethods).GetMethod("GenericNullableSerializer", BindingFlags.Static | BindingFlags.NonPublic);
			Deserializers = new Dictionary<Type, Delegate>();
			Serializers = new Dictionary<Type, Delegate>();
			Register((string? s) => new TomlString(s), (TomlValue value) => (value as TomlString)?.Value ?? value.StringValue);
			Register(TomlBoolean.ValueOf, (TomlValue value) => ((value as TomlBoolean) ?? throw new TomlTypeMismatchException(typeof(TomlBoolean), value.GetType(), typeof(bool))).Value);
			Register((byte i) => new TomlLong(i), (TomlValue value) => (byte)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(byte))).Value);
			Register((sbyte i) => new TomlLong(i), (TomlValue value) => (sbyte)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(sbyte))).Value);
			Register((ushort i) => new TomlLong(i), (TomlValue value) => (ushort)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(ushort))).Value);
			Register((short i) => new TomlLong(i), (TomlValue value) => (short)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(short))).Value);
			Register((uint i) => new TomlLong(i), (TomlValue value) => (uint)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(uint))).Value);
			Register((int i) => new TomlLong(i), (TomlValue value) => (int)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(int))).Value);
			Register((ulong l) => new TomlLong((long)l), (TomlValue value) => (ulong)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(ulong))).Value);
			Register((long l) => new TomlLong(l), (TomlValue value) => ((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(long))).Value);
			Register((double d) => new TomlDouble(d), (TomlValue value) => (value as TomlDouble)?.Value ?? ((double)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlDouble), value.GetType(), typeof(double))).Value));
			Register((float f) => new TomlDouble(f), (TomlValue value) => (float)((value as TomlDouble)?.Value ?? ((double)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlDouble), value.GetType(), typeof(float))).Value)));
			Register((DateTime dt) => (!(dt.TimeOfDay == TimeSpan.Zero)) ? ((TomlValue?)new TomlLocalDateTime(dt)) : ((TomlValue?)new TomlLocalDate(dt)), (TomlValue value) => ((value as ITomlValueWithDateTime) ?? throw new TomlTypeMismatchException(typeof(ITomlValueWithDateTime), value.GetType(), typeof(DateTime))).Value);
			Register((DateTimeOffset odt) => new TomlOffsetDateTime(odt), (TomlValue value) => ((value as TomlOffsetDateTime) ?? throw new TomlTypeMismatchException(typeof(TomlOffsetDateTime), value.GetType(), typeof(DateTimeOffset))).Value);
			Register((TimeSpan lt) => new TomlLocalTime(lt), (TomlValue value) => ((value as TomlLocalTime) ?? throw new TomlTypeMismatchException(typeof(TomlLocalTime), value.GetType(), typeof(TimeSpan))).Value);
		}

		internal static Serialize<object> GetSerializer(Type t)
		{
			if (Serializers.TryGetValue(t, out Delegate value))
			{
				return (Serialize<object>)value;
			}
			if (t.IsArray || (t.Namespace == "System.Collections.Generic" && t.Name == "List`1"))
			{
				Serialize<object> serialize = GenericEnumerableSerializer();
				Serializers[t] = serialize;
				return serialize;
			}
			if (t.IsGenericType)
			{
				Type[] genericArguments = t.GetGenericArguments();
				if (genericArguments != null)
				{
					if ((object)t.GetGenericTypeDefinition() == typeof(Dictionary<, >))
					{
						MethodInfo method = _genericDictionarySerializerMethod.MakeGenericMethod(genericArguments);
						Delegate del2 = Delegate.CreateDelegate(typeof(Serialize<>).MakeGenericType(t), method);
						Serialize<object> serialize2 = (object? dict) => (TomlValue)del2.DynamicInvoke(dict);
						Serializers[t] = serialize2;
						return serialize2;
					}
					if ((object)t.GetGenericTypeDefinition() == typeof(Nullable<>))
					{
						MethodInfo method2 = _genericNullableSerializerMethod.MakeGenericMethod(genericArguments);
						Delegate del = Delegate.CreateDelegate(typeof(Serialize<>).MakeGenericType(t), method2);
						Serialize<object> serialize3 = (object? dict) => (TomlValue)del.DynamicInvoke(dict);
						Serializers[t] = serialize3;
						return serialize3;
					}
				}
			}
			return TomlCompositeSerializer.For(t);
		}

		internal static Deserialize<object> GetDeserializer(Type t)
		{
			if (Deserializers.TryGetValue(t, out Delegate value))
			{
				return (Deserialize<object>)value;
			}
			if (t.IsArray)
			{
				Deserialize<object> deserialize = ArrayDeserializerFor(t.GetElementType());
				Deserializers[t] = deserialize;
				return deserialize;
			}
			if (t.Namespace == "System.Collections.Generic" && t.Name == "List`1")
			{
				Deserialize<object> deserialize2 = ListDeserializerFor(t.GetGenericArguments()[0]);
				Deserializers[t] = deserialize2;
				return deserialize2;
			}
			if (t.IsGenericType && (object)t.GetGenericTypeDefinition() == typeof(Nullable<>))
			{
				Type[] genericArguments = t.GetGenericArguments();
				if (genericArguments != null && genericArguments.Length == 1)
				{
					Deserialize<object> deserialize3 = NullableDeserializerFor(t);
					Deserializers[t] = deserialize3;
					return deserialize3;
				}
			}
			if (t.IsGenericType && (object)t.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				Type[] genericArguments2 = t.GetGenericArguments();
				if (genericArguments2 != null && genericArguments2.Length == 2 && (object)genericArguments2[0] == typeof(string))
				{
					return (Deserialize<object>)_stringKeyedDictionaryMethod.MakeGenericMethod(genericArguments2[1]).Invoke(null, new object[0]);
				}
			}
			return TomlCompositeDeserializer.For(t);
		}

		private static Serialize<object?> GenericEnumerableSerializer()
		{
			return delegate(object? o)
			{
				IEnumerable obj = (o as IEnumerable) ?? throw new Exception("How did ArraySerializer end up getting a non-array?");
				TomlArray tomlArray = new TomlArray();
				foreach (object item in obj)
				{
					tomlArray.Add(item);
				}
				return tomlArray;
			};
		}

		private static Deserialize<object> ArrayDeserializerFor(Type elementType)
		{
			Type elementType2 = elementType;
			return delegate(TomlValue value)
			{
				if (!(value is TomlArray tomlArray))
				{
					throw new TomlTypeMismatchException(typeof(TomlArray), value.GetType(), elementType2.MakeArrayType());
				}
				Array array = Array.CreateInstance(elementType2, tomlArray.Count);
				Deserialize<object> deserializer = GetDeserializer(elementType2);
				for (int i = 0; i < tomlArray.ArrayValues.Count; i++)
				{
					TomlValue value2 = tomlArray.ArrayValues[i];
					array.SetValue(deserializer(value2), i);
				}
				return array;
			};
		}

		private static Deserialize<object> ListDeserializerFor(Type elementType)
		{
			Type elementType2 = elementType;
			Type listType = typeof(List<>).MakeGenericType(elementType2);
			MethodInfo relevantAddMethod = listType.GetMethod("Add");
			return delegate(TomlValue value)
			{
				TomlArray obj = (value as TomlArray) ?? throw new TomlTypeMismatchException(typeof(TomlArray), value.GetType(), listType);
				object obj2 = Activator.CreateInstance(listType);
				Deserialize<object> deserializer = GetDeserializer(elementType2);
				foreach (TomlValue arrayValue in obj.ArrayValues)
				{
					relevantAddMethod.Invoke(obj2, new object[1] { deserializer(arrayValue) });
				}
				return obj2;
			};
		}

		private static Deserialize<object> NullableDeserializerFor(Type nullableType)
		{
			Type nullableType2 = nullableType;
			Type t = nullableType2.GetGenericArguments()[0];
			Deserialize<object> elementDeserializer = GetDeserializer(t);
			return delegate(TomlValue value)
			{
				object obj = elementDeserializer(value);
				return Activator.CreateInstance(nullableType2, obj);
			};
		}

		private static Deserialize<Dictionary<string, T>> StringKeyedDictionaryDeserializerFor<T>()
		{
			Deserialize<object> deserializer = GetDeserializer(typeof(T));
			return (TomlValue value) => ((value as TomlTable) ?? throw new TomlTypeMismatchException(typeof(TomlTable), value.GetType(), typeof(Dictionary<string, T>))).Entries.ToDictionary<KeyValuePair<string, TomlValue>, string, T>((KeyValuePair<string, TomlValue> entry) => entry.Key, (KeyValuePair<string, TomlValue> entry) => (T)deserializer(entry.Value));
		}

		private static TomlValue? GenericNullableSerializer<T>(T? nullable) where T : struct
		{
			Serialize<object> serializer = GetSerializer(typeof(T));
			if (nullable.HasValue)
			{
				return serializer(nullable.Value);
			}
			return null;
		}

		private static TomlValue GenericDictionarySerializer<TKey, TValue>(Dictionary<TKey, TValue> dict) where TKey : notnull
		{
			Serialize<object> serializer = GetSerializer(typeof(TValue));
			TomlTable tomlTable = new TomlTable();
			foreach (KeyValuePair<TKey, TValue> item in dict)
			{
				TKey key = item.Key;
				string text = ((key != null) ? key.ToString() : null);
				if (text != null)
				{
					tomlTable.PutValue(text, serializer(item.Value), quote: true);
				}
			}
			return tomlTable;
		}

		internal static void Register<T>(Serialize<T>? serializer, Deserialize<T>? deserializer)
		{
			if (serializer != null)
			{
				RegisterSerializer(serializer);
				RegisterDictionarySerializer(serializer);
			}
			if (deserializer != null)
			{
				RegisterDeserializer(deserializer);
				RegisterDictionaryDeserializer(deserializer);
			}
		}

		internal static void Register(Type t, Serialize<object>? serializer, Deserialize<object>? deserializer)
		{
			if (serializer != null)
			{
				RegisterSerializer(serializer);
			}
			if (deserializer != null)
			{
				RegisterDeserializer(deserializer);
			}
		}

		private static void RegisterDeserializer<T>(Deserialize<T> deserializer)
		{
			Deserialize<T> deserializer2 = deserializer;
			Deserializers[typeof(T)] = new Deserialize<object>(BoxedDeserializer);
			object BoxedDeserializer(TomlValue value)
			{
				T val = deserializer2(value);
				if (val == null)
				{
					throw new Exception("TOML Deserializer returned null for type T");
				}
				return val;
			}
		}

		private static void RegisterSerializer<T>(Serialize<T> serializer)
		{
			Serialize<T> serializer2 = serializer;
			Serializers[typeof(T)] = new Serialize<object>(ObjectAcceptingSerializer);
			TomlValue? ObjectAcceptingSerializer(object value)
			{
				return serializer2((T)value);
			}
		}

		private static void RegisterDictionarySerializer<T>(Serialize<T> serializer)
		{
			Serialize<T> serializer2 = serializer;
			RegisterSerializer(delegate(Dictionary<string, T>? dict)
			{
				TomlTable tomlTable = new TomlTable();
				if (dict == null)
				{
					return tomlTable;
				}
				List<string> list = dict.Keys.ToList();
				List<TomlValue> list2 = dict.Values.Select(serializer2.Invoke).ToList();
				for (int i = 0; i < list.Count; i++)
				{
					tomlTable.PutValue(list[i], list2[i], quote: true);
				}
				return tomlTable;
			});
		}

		private static void RegisterDictionaryDeserializer<T>(Deserialize<T> deserializer)
		{
			Deserialize<T> deserializer2 = deserializer;
			RegisterDeserializer((TomlValue value) => ((value as TomlTable) ?? throw new TomlTypeMismatchException(typeof(TomlTable), value.GetType(), typeof(Dictionary<string, T>))).Entries.Select<KeyValuePair<string, TomlValue>, KeyValuePair<string, T>>((KeyValuePair<string, TomlValue> kvp) => new KeyValuePair<string, T>(kvp.Key, deserializer2(kvp.Value))).ToDictionary((KeyValuePair<string, T> kvp) => kvp.Key, (KeyValuePair<string, T> kvp) => kvp.Value));
		}
	}
	internal static class TomlUtils
	{
		public static string EscapeStringValue(string key)
		{
			return key.Replace("\\", "\\\\").Replace("\n", "\\n").Replace("\r", "");
		}

		public static string AddCorrectQuotes(string key)
		{
			if (key.Contains("'") && key.Contains("\""))
			{
				throw new InvalidTomlKeyException(key);
			}
			if (key.Contains("\""))
			{
				return "'" + key + "'";
			}
			return "\"" + key + "\"";
		}
	}
}
namespace Tomlet.Models
{
	public class TomlArray : TomlValue, IEnumerable<TomlValue>, IEnumerable
	{
		public readonly List<TomlValue> ArrayValues = new List<TomlValue>();

		internal bool IsLockedToBeTableArray;

		public override string StringValue => $"Toml Array ({ArrayValues.Count} values)";

		public bool IsTableArray
		{
			get
			{
				if (!IsLockedToBeTableArray)
				{
					return ArrayValues.All((TomlValue t) => t is TomlTable);
				}
				return true;
			}
		}

		public bool CanBeSerializedInline
		{
			get
			{
				if (IsTableArray)
				{
					if (ArrayValues.All((TomlValue o) => o is TomlTable tomlTable && tomlTable.ShouldBeSerializedInline))
					{
						return ArrayValues.Count <= 5;
					}
					return false;
				}
				return true;
			}
		}

		public bool IsSimpleArray
		{
			get
			{
				if (!IsLockedToBeTableArray)
				{
					return !ArrayValues.Any((TomlValue o) => o is TomlArray || o is TomlTable || !o.Comments.ThereAreNoComments);
				}
				return false;
			}
		}

		public TomlValue this[int index] => ArrayValues[index];

		public int Count => ArrayValues.Count;

		public override string SerializedValue => SerializeInline(!IsSimpleArray);

		public void Add<T>(T t) where T : new()
		{
			TomlValue tomlValue2 = (((object)t is TomlValue tomlValue) ? tomlValue : TomletMain.ValueFrom(t));
			if (tomlValue2 != null)
			{
				ArrayValues.Add(tomlValue2);
			}
		}

		public string SerializeInline(bool multiline)
		{
			if (!CanBeSerializedInline)
			{
				throw new Exception("Complex Toml Tables cannot be serialized into a TomlArray if the TomlArray is not a Table Array. This means that the TOML array cannot contain anything other than tables. If you are manually accessing SerializedValue on the TomlArray, you should probably be calling SerializeTableArray here. (Check the CanBeSerializedInline property and call that method if it is false)");
			}
			StringBuilder stringBuilder = new StringBuilder("[");
			char value = (multiline ? '\n' : ' ');
			using (IEnumerator<TomlValue> enumerator = GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					TomlValue current = enumerator.Current;
					stringBuilder.Append(value);
					if (current.Comments.PrecedingComment != null)
					{
						stringBuilder.Append(current.Comments.FormatPrecedingComment(1)).Append('\n');
					}
					if (multiline)
					{
						stringBuilder.Append('\t');
					}
					stringBuilder.Append(current.SerializedValue);
					stringBuilder.Append(',');
					if (current.Comments.InlineComment != null)
					{
						stringBuilder.Append(" # ").Append(current.Comments.InlineComment);
					}
				}
			}
			stringBuilder.Append(value);
			stringBuilder.Append(']');
			return stringBuilder.ToString();
		}

		public string SerializeTableArray(string key)
		{
			if (!IsTableArray)
			{
				throw new Exception("Cannot serialize normal arrays using this method. Use the normal TomlValue.SerializedValue property.");
			}
			StringBuilder stringBuilder = new StringBuilder();
			if (base.Comments.InlineComment != null)
			{
				throw new Exception("Sorry, but inline comments aren't supported on table-arrays themselves. See https://github.com/SamboyCoding/Tomlet/blob/master/Docs/InlineCommentsOnTableArrays.md for my rationale on this.");
			}
			bool flag = true;
			using (IEnumerator<TomlValue> enumerator = GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					TomlValue current = enumerator.Current;
					if (!(current is TomlTable tomlTable))
					{
						throw new Exception($"Toml Table-Array contains non-table entry? Value is {current}");
					}
					if (current.Comments.PrecedingComment != null)
					{
						if (flag && base.Comments.PrecedingComment != null)
						{
							stringBuilder.Append('\n');
						}
						stringBuilder.Append(current.Comments.FormatPrecedingComment()).Append('\n');
					}
					flag = false;
					stringBuilder.Append("[[").Append(key).Append("]]");
					if (current.Comments.InlineComment != null)
					{
						stringBuilder.Append(" # ").Append(current.Comments.InlineComment);
					}
					stringBuilder.Append('\n');
					stringBuilder.Append(tomlTable.SerializeNonInlineTable(key, includeHeader: false)).Append('\n');
				}
			}
			return stringBuilder.ToString();
		}

		public IEnumerator<TomlValue> GetEnumerator()
		{
			return ArrayValues.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return ArrayValues.GetEnumerator();
		}
	}
	public class TomlBoolean : TomlValue
	{
		private bool _value;

		public static TomlBoolean True => new TomlBoolean(value: true);

		public static TomlBoolean False => new TomlBoolean(value: false);

		public bool Value => _value;

		public override string StringValue
		{
			get
			{
				if (!Value)
				{
					return bool.FalseString.ToLowerInvariant();
				}
				return bool.TrueString.ToLowerInvariant();
			}
		}

		public override string SerializedValue => StringValue;

		private TomlBoolean(bool value)
		{
			_value = value;
		}

		public static TomlBoolean ValueOf(bool b)
		{
			if (!b)
			{
				return False;
			}
			return True;
		}
	}
	public class TomlCommentData
	{
		private string? _inlineComment;

		public string? PrecedingComment { get; set; }

		public string? InlineComment
		{
			get
			{
				return _inlineComment;
			}
			set
			{
				if (value == null)
				{
					_inlineComment = null;
					return;
				}
				if (value.Contains("\n") || value.Contains("\r"))
				{
					throw new TomlNewlineInInlineCommentException();
				}
				_inlineComment = value;
			}
		}

		public bool ThereAreNoComments
		{
			get
			{
				if (InlineComment == null)
				{
					return PrecedingComment == null;
				}
				return false;
			}
		}

		internal string FormatPrecedingComment(int indentCount = 0)
		{
			if (PrecedingComment == null)
			{
				throw new Exception("Preceding comment is null");
			}
			StringBuilder stringBuilder = new StringBuilder();
			string[] array = PrecedingComment.Split(new char[1] { '\n' });
			bool flag = true;
			string[] array2 = array;
			foreach (string value in array2)
			{
				if (!flag)
				{
					stringBuilder.Append('\n');
				}
				flag = false;
				string value2 = new string('\t', indentCount);
				stringBuilder.Append(value2).Append("# ").Append(value);
			}
			return stringBuilder.ToString();
		}
	}
	public class TomlDocument : TomlTable
	{
		public string? TrailingComment { get; set; }

		public override string SerializedValue => SerializeDocument();

		public override string StringValue => $"Toml root document ({Entries.Count} entries)";

		public static TomlDocument CreateEmpty()
		{
			return new TomlDocument();
		}

		internal TomlDocument()
		{
		}

		internal TomlDocument(TomlTable from)
		{
			foreach (string key in from.Keys)
			{
				PutValue(key, from.GetValue(key));
			}
		}

		private string SerializeDocument()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(SerializeNonInlineTable(null, includeHeader: false));
			if (TrailingComment != null)
			{
				TomlCommentData tomlCommentData = new TomlCommentData
				{
					PrecedingComment = TrailingComment
				};
				stringBuilder.Append('\n');
				stringBuilder.Append(tomlCommentData.FormatPrecedingComment());
			}
			return stringBuilder.ToString();
		}
	}
	public class TomlDouble : TomlValue
	{
		private double _value;

		public bool HasDecimal => Value != (double)(int)Value;

		public double Value => _value;

		public bool IsNaN => double.IsNaN(Value);

		public bool IsInfinity => double.IsInfinity(Value);

		public override string StringValue
		{
			get
			{
				if (this != null)
				{
					if (IsInfinity)
					{
						return double.IsPositiveInfinity(Value) ? "inf" : "-inf";
					}
					if (IsNaN)
					{
						return "nan";
					}
					if (HasDecimal)
					{
						return Value.ToString(CultureInfo.InvariantCulture);
					}
				}
				return $"{Value:F1}";
			}
		}

		public override string SerializedValue => StringValue;

		public TomlDouble(double value)
		{
			_value = value;
		}

		internal static TomlDouble? Parse(string valueInToml)
		{
			double? doubleValue = TomlNumberUtils.GetDoubleValue(valueInToml);
			if (!doubleValue.HasValue)
			{
				return null;
			}
			return new TomlDouble(doubleValue.Value);
		}
	}
	public class TomlLocalDate : TomlValue, ITomlValueWithDateTime
	{
		private readonly DateTime _value;

		public DateTime Value => _value;

		public override string StringValue => XmlConvert.ToString(Value, XmlDateTimeSerializationMode.Unspecified);

		public override string SerializedValue => StringValue;

		public TomlLocalDate(DateTime value)
		{
			_value = value;
		}

		public static TomlLocalDate? Parse(string input)
		{
			if (!DateTime.TryParse(input, out var result))
			{
				return null;
			}
			return new TomlLocalDate(result);
		}
	}
	public class TomlLocalDateTime : TomlValue, ITomlValueWithDateTime
	{
		private readonly DateTime _value;

		public DateTime Value => _value;

		public override string StringValue => XmlConvert.ToString(Value, XmlDateTimeSerializationMode.Unspecified);

		public override string SerializedValue => StringValue;

		public TomlLocalDateTime(DateTime value)
		{
			_value = value;
		}

		public static TomlLocalDateTime? Parse(string input)
		{
			if (!DateTime.TryParse(input, out var result))
			{
				return null;
			}
			return new TomlLocalDateTime(result);
		}
	}
	public class TomlLocalTime : TomlValue
	{
		private readonly TimeSpan _value;

		public TimeSpan Value => _value;

		public override string StringValue => Value.ToString();

		public override string SerializedValue => StringValue;

		public TomlLocalTime(TimeSpan value)
		{
			_value = value;
		}

		public static TomlLocalTime? Parse(string input)
		{
			if (!TimeSpan.TryParse(input, out var result))
			{
				return null;
			}
			return new TomlLocalTime(result);
		}
	}
	public class TomlLong : TomlValue
	{
		private long _value;

		public long Value => _value;

		public override string StringValue => Value.ToString();

		public override string SerializedValue => StringValue;

		public TomlLong(long value)
		{
			_value = value;
		}

		internal static TomlLong? Parse(string valueInToml)
		{
			long? longValue = TomlNumberUtils.GetLongValue(valueInToml);
			if (!longValue.HasValue)
			{
				return null;
			}
			return new TomlLong(longValue.Value);
		}
	}
	public class TomlOffsetDateTime : TomlValue
	{
		private readonly DateTimeOffset _value;

		public DateTimeOffset Value => _value;

		public override string StringValue => Value.ToString("O");

		public override string SerializedValue => StringValue;

		public TomlOffsetDateTime(DateTimeOffset value)
		{
			_value = value;
		}

		public static TomlOffsetDateTime? Parse(string input)
		{
			if (!DateTimeOffset.TryParse(input, out var result))
			{
				return null;
			}
			return new TomlOffsetDateTime(result);
		}
	}
	public class TomlString : TomlValue
	{
		private readonly string _value;

		public static TomlString Empty => new TomlString("");

		public string Value => _value;

		public override string StringValue => Value;

		public override string SerializedValue
		{
			get
			{
				if (!Value.RuntimeCorrectContains('\'') && Value.RuntimeCorrectContains('\\'))
				{
					if (!Value.RuntimeCorrectContains('\n'))
					{
						return LiteralStringSerializedForm;
					}
					return MultiLineLiteralStringSerializedForm;
				}
				if (Value.RuntimeCorrectContains('\'') && !Value.RuntimeCorrectContains('"'))
				{
					return StandardStringSerializedForm;
				}
				if (Value.RuntimeCorrectContains('"') && !Value.RuntimeCorrectContains('\'') && !Value.RuntimeCorrectContains('\n'))
				{
					return LiteralStringSerializedForm;
				}
				if (Value.RuntimeCorrectContains('"') && !Value.RuntimeCorrectContains('\''))
				{
					return MultiLineLiteralStringSerializedForm;
				}
				return StandardStringSerializedForm;
			}
		}

		internal string StandardStringSerializedForm => "\"" + TomlUtils.EscapeStringValue(Value) + "\"";

		internal string LiteralStringSerializedForm => "'" + Value + "'";

		internal string MultiLineLiteralStringSerializedForm => "'''\n" + Value + "'''";

		public TomlString(string? value)
		{
			_value = value ?? throw new ArgumentNullException("value", "TomlString's value cannot be null");
		}
	}
	public class TomlTable : TomlValue
	{
		public readonly Dictionary<string, TomlValue> Entries = new Dictionary<string, TomlValue>();

		internal bool Locked;

		internal bool Defined;

		public bool ForceNoInline { get; set; }

		public override string StringValue => $"Table ({Entries.Count} entries)";

		public HashSet<string> Keys => new HashSet<string>(Entries.Keys);

		public bool ShouldBeSerializedInline
		{
			get
			{
				if (!ForceNoInline && Entries.Count < 4)
				{
					return Entries.All<KeyValuePair<string, TomlValue>>((KeyValuePair<string, TomlValue> e) => !e.Key.Contains(" ") && e.Value.Comments.ThereAreNoComments && ((!(e.Value is TomlArray tomlArray)) ? (!(e.Value is TomlTable)) : tomlArray.IsSimpleArray));
				}
				return false;
			}
		}

		public override string SerializedValue
		{
			get
			{
				if (!ShouldBeSerializedInline)
				{
					throw new Exception("Cannot use SerializeValue to serialize non-inline tables. Use SerializeNonInlineTable(keyName).");
				}
				StringBuilder stringBuilder = new StringBuilder("{ ");
				stringBuilder.Append(string.Join(", ", Entries.Select<KeyValuePair<string, TomlValue>, string>((KeyValuePair<string, TomlValue> o) => o.Key + " = " + o.Value.SerializedValue).ToArray()));
				stringBuilder.Append(" }");
				return stringBuilder.ToString();
			}
		}

		public string SerializeNonInlineTable(string? keyName, bool includeHeader = true)
		{
			StringBuilder stringBuilder = new StringBuilder();
			if (includeHeader)
			{
				stringBuilder.Append('[').Append(keyName).Append("]");
				if (base.Comments.InlineComment != null)
				{
					stringBuilder.Append(" # ").Append(base.Comments.InlineComment);
				}
				stringBuilder.Append('\n');
			}
			string one;
			TomlValue two;
			foreach (KeyValuePair<string, TomlValue> entry in Entries)
			{
				Extensions.Deconstruct(entry, out one, out two);
				string subKey = one;
				TomlValue tomlValue = two;
				if (tomlValue is TomlTable tomlTable)
				{
					if (!tomlTable.ShouldBeSerializedInline)
					{
						goto IL_00a4;
					}
				}
				else if (tomlValue is TomlArray tomlArray && !tomlArray.CanBeSerializedInline)
				{
					goto IL_00a4;
				}
				bool flag = false;
				goto IL_00ac;
				IL_00a4:
				flag = true;
				goto IL_00ac;
				IL_00ac:
				if (!flag)
				{
					WriteValueToStringBuilder(keyName, subKey, stringBuilder);
				}
			}
			foreach (KeyValuePair<string, TomlValue> entry2 in Entries)
			{
				Extensions.Deconstruct(entry2, out one, out two);
				string subKey2 = one;
				if (two is TomlTable tomlTable2 && !tomlTable2.ShouldBeSerializedInline)
				{
					WriteValueToStringBuilder(keyName, subKey2, stringBuilder);
				}
			}
			foreach (KeyValuePair<string, TomlValue> entry3 in Entries)
			{
				Extensions.Deconstruct(entry3, out one, out two);
				string subKey3 = one;
				if (two is TomlArray tomlArray2 && !tomlArray2.CanBeSerializedInline)
				{
					WriteValueToStringBuilder(keyName, subKey3, stringBuilder);
				}
			}
			return stringBuilder.ToString();
		}

		private void WriteValueToStringBuilder(string? keyName, string subKey, StringBuilder builder)
		{
			TomlValue value = GetValue(subKey);
			subKey = EscapeKeyIfNeeded(subKey);
			if (keyName != null)
			{
				keyName = EscapeKeyIfNeeded(keyName);
			}
			string text = ((keyName == null) ? subKey : (keyName + "." + subKey));
			bool flag = builder.Length < 2 || builder[builder.Length - 2] == '\n';
			if (value.Comments.PrecedingComment != null)
			{
				builder.Append(value.Comments.FormatPrecedingComment()).Append('\n');
			}
			if (value is TomlArray tomlArray)
			{
				if (!tomlArray.CanBeSerializedInline)
				{
					if (!flag)
					{
						builder.Append('\n');
					}
					builder.Append(tomlArray.SerializeTableArray(text));
					return;
				}
				TomlArray tomlArray2 = tomlArray;
				builder.Append(subKey).Append(" = ").Append(tomlArray2.SerializedValue);
			}
			else if (value is TomlTable tomlTable)
			{
				if (!tomlTable.ShouldBeSerializedInline)
				{
					TomlTable tomlTable2 = tomlTable;
					builder.Append(tomlTable2.SerializeNonInlineTable(text)).Append('\n');
					return;
				}
				builder.Append(subKey).Append(" = ").Append(tomlTable.SerializedValue);
			}
			else
			{
				builder.Append(subKey).Append(" = ").Append(value.SerializedValue);
			}
			if (value.Comments.InlineComment != null)
			{
				builder.Append(" # ").Append(value.Comments.InlineComment);
			}
			builder.Append('\n');
		}

		private string EscapeKeyIfNeeded(string key)
		{
			bool flag = false;
			if (key.StartsWith("\"") && key.EndsWith("\"") && key.Count((char c) => c == '"') == 2)
			{
				return key;
			}
			if (key.StartsWith("'") && key.EndsWith("'") && key.Count((char c) => c == '\'') == 2)
			{
				return key;
			}
			if (key.Contains("\"") || key.Contains("'"))
			{
				key = TomlUtils.AddCorrectQuotes(key);
				flag = true;
			}
			string text = TomlUtils.EscapeStringValue(key);
			if (text.Contains(" ") || (text.Contains("\\") && !flag))
			{
				text = TomlUtils.AddCorrectQuotes(text);
			}
			return text;
		}

		internal void ParserPutValue(string key, TomlValue value, int lineNumber)
		{
			if (Locked)
			{
				throw new TomlTableLockedException(lineNumber, key);
			}
			InternalPutValue(key, value, lineNumber, callParserForm: true);
		}

		public void PutValue(string key, TomlValue value, bool quote = false)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			if (quote)
			{
				key = TomlUtils.AddCorrectQuotes(key);
			}
			InternalPutValue(key, value, null, callParserForm: false);
		}

		public void Put<T>(string key, T t, bool quote = false)
		{
			TomlValue tomlValue2 = ((!((object)t is TomlValue tomlValue)) ? TomletMain.ValueFrom(t) : tomlValue);
			if (tomlValue2 == null)
			{
				throw new ArgumentException("Value to insert into TOML table serialized to null.", "t");
			}
			PutValue(key, tomlValue2, quote);
		}

		public string DeQuoteKey(string key)
		{
			if ((key.StartsWith("\"") && key.EndsWith("\"")) || (key.StartsWith("'") && key.EndsWith("'")))
			{
				return key.Substring(1, key.Length - 2);
			}
			return key;
		}

		private void InternalPutValue(string key, TomlValue value, int? lineNumber, bool callParserForm)
		{
			key = key.Trim();
			TomlKeyUtils.GetTopLevelAndSubKeys(key, out string ourKeyName, out string restOfKey);
			if (!string.IsNullOrEmpty(restOfKey))
			{
				if (!Entries.TryGetValue(DeQuoteKey(ourKeyName), out TomlValue value2))
				{
					TomlTable tomlTable = new TomlTable();
					if (callParserForm)
					{
						ParserPutValue(ourKeyName, tomlTable, lineNumber.Value);
					}
					else
					{
						PutValue(ourKeyName, tomlTable);
					}
					if (callParserForm)
					{
						tomlTable.ParserPutValue(restOfKey, value, lineNumber.Value);
					}
					else
					{
						tomlTable.PutValue(restOfKey, value);
					}
					return;
				}
				if (!(value2 is TomlTable tomlTable2))
				{
					if (lineNumber.HasValue)
					{
						throw new TomlDottedKeyParserException(lineNumber.Value, ourKeyName);
					}
					throw new TomlDottedKeyException(ourKeyName);
				}
				if (callParserForm)
				{
					tomlTable2.ParserPutValue(restOfKey, value, lineNumber.Value);
				}
				else
				{
					tomlTable2.PutValue(restOfKey, value);
				}
			}
			else
			{
				key = DeQuoteKey(key);
				if (Entries.ContainsKey(key) && lineNumber.HasValue)
				{
					throw new TomlKeyRedefinitionException(lineNumber.Value, key);
				}
				Entries[key] = value;
			}
		}

		public bool ContainsKey(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			TomlKeyUtils.GetTopLevelAndSubKeys(key, out string ourKeyName, out string restOfKey);
			if (string.IsNullOrEmpty(restOfKey))
			{
				return Entries.ContainsKey(DeQuoteKey(key));
			}
			if (!Entries.TryGetValue(ourKeyName, out TomlValue value))
			{
				return false;
			}
			if (value is TomlTable tomlTable)
			{
				return tomlTable.ContainsKey(restOfKey);
			}
			throw new TomlContainsDottedKeyNonTableException(key);
		}

		public bool TryGetValue(string key, out TomlValue? value)
		{
			if (ContainsKey(key))
			{
				return (value = GetValue(key)) != null;
			}
			value = null;
			return false;
		}

		public TomlValue GetValue(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			if (!ContainsKey(key))
			{
				throw new TomlNoSuchValueException(key);
			}
			TomlKeyUtils.GetTopLevelAndSubKeys(key, out string ourKeyName, out string restOfKey);
			if (string.IsNullOrEmpty(restOfKey))
			{
				return Entries[DeQuoteKey(key)];
			}
			if (!Entries.TryGetValue(ourKeyName, out TomlValue value))
			{
				throw new TomlNoSuchValueException(key);
			}
			if (value is TomlTable tomlTable)
			{
				return tomlTable.GetValue(restOfKey);
			}
			throw new Exception("Tomlet Internal bug - existing key is not a table in TomlTable GetValue, but we didn't throw in ContainsKey?");
		}

		public string GetString(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key));
			return ((value as TomlString) ?? throw new TomlTypeMismatchException(typeof(TomlString), value.GetType(), typeof(string))).Value;
		}

		public int GetInteger(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key));
			return (int)((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(int))).Value;
		}

		public long GetLong(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key));
			return ((value as TomlLong) ?? throw new TomlTypeMismatchException(typeof(TomlLong), value.GetType(), typeof(int))).Value;
		}

		public float GetFloat(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key));
			return (float)((value as TomlDouble) ?? throw new TomlTypeMismatchException(typeof(TomlDouble), value.GetType(), typeof(float))).Value;
		}

		public bool GetBoolean(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key));
			return ((value as TomlBoolean) ?? throw new TomlTypeMismatchException(typeof(TomlBoolean), value.GetType(), typeof(bool))).Value;
		}

		public TomlArray GetArray(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key));
			return (value as TomlArray) ?? throw new TomlTypeMismatchException(typeof(TomlArray), value.GetType(), typeof(TomlArray));
		}

		public TomlTable GetSubTable(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			TomlValue value = GetValue(TomlUtils.AddCorrectQuotes(key));
			return (value as TomlTable) ?? throw new TomlTypeMismatchException(typeof(TomlTable), value.GetType(), typeof(TomlTable));
		}
	}
	public abstract class TomlValue
	{
		public TomlCommentData Comments { get; } = new TomlCommentData();


		public abstract string StringValue { get; }

		public abstract string SerializedValue { get; }
	}
	public interface ITomlValueWithDateTime
	{
		DateTime Value { get; }
	}
}
namespace Tomlet.Exceptions
{
	public class InvalidTomlDateTimeException : TomlExceptionWithLine
	{
		private readonly string _inputString;

		public override string Message => $"Found an invalid TOML date/time string '{_inputString}' on line {LineNumber}";

		public InvalidTomlDateTimeException(int lineNumber, string inputString)
			: base(lineNumber)
		{
			_inputString = inputString;
		}
	}
	public class InvalidTomlEscapeException : TomlExceptionWithLine
	{
		private readonly string _escapeSequence;

		public override string Message => $"Found an invalid escape sequence '\\{_escapeSequence}' on line {LineNumber}";

		public InvalidTomlEscapeException(int lineNumber, string escapeSequence)
			: base(lineNumber)
		{
			_escapeSequence = escapeSequence;
		}
	}
	public class InvalidTomlInlineTableException : TomlExceptionWithLine
	{
		public override string Message => $"Found an invalid inline TOML table on line {LineNumber}. See further down for cause.";

		public InvalidTomlInlineTableException(int lineNumber, TomlException cause)
			: base(lineNumber, cause)
		{
		}
	}
	public class InvalidTomlKeyException : TomlException
	{
		private readonly string _key;

		public override string Message => "The string |" + _key + "| (between the two bars) contains at least one of both a double quote and a single quote, so it cannot be used for a TOML key.";

		public InvalidTomlKeyException(string key)
		{
			_key = key;
		}
	}
	public class InvalidTomlNumberException : TomlExceptionWithLine
	{
		private readonly string _input;

		public override string Message => $"While reading input line {LineNumber}, found an invalid number literal '{_input}'";

		public InvalidTomlNumberException(int lineNumber, string input)
			: base(lineNumber)
		{
			_input = input;
		}
	}
	public class MissingIntermediateInTomlTableArraySpecException : TomlExceptionWithLine
	{
		private readonly string _missing;

		public override string Message => $"Missing intermediate definition for {_missing} in table-array specification on line {LineNumber}. This is undefined behavior, and I chose to define it as an error.";

		public MissingIntermediateInTomlTableArraySpecException(int lineNumber, string missing)
			: base(lineNumber)
		{
			_missing = missing;
		}
	}
	public class NewLineInTomlInlineTableException : TomlExceptionWithLine
	{
		public override string Message => "Found a new-line character within a TOML inline table. This is not allowed.";

		public NewLineInTomlInlineTableException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class NoTomlKeyException : TomlExceptionWithLine
	{
		public override string Message => $"Expected a TOML key on line {LineNumber}, but found an equals sign ('=').";

		public NoTomlKeyException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class TimeOffsetOnTomlDateOrTimeException : TomlExceptionWithLine
	{
		private readonly string _tzString;

		public override string Message => $"Found a time offset string {_tzString} in a partial datetime on line {LineNumber}. This is not allowed - either specify both the date and the time, or remove the offset specifier.";

		public TimeOffsetOnTomlDateOrTimeException(int lineNumber, string tzString)
			: base(lineNumber)
		{
			_tzString = tzString;
		}
	}
	public class TomlArraySyntaxException : TomlExceptionWithLine
	{
		private readonly char _charFound;

		public override string Message => $"Expecting ',' or ']' after value in array on line {LineNumber}, found '{_charFound}'";

		public TomlArraySyntaxException(int lineNumber, char charFound)
			: base(lineNumber)
		{
			_charFound = charFound;
		}
	}
	public class TomlContainsDottedKeyNonTableException : TomlException
	{
		internal readonly string Key;

		public override string Message => "A call was made on a TOML table which attempted to access a sub-key of " + Key + ", but the value it refers to is not a table";

		public TomlContainsDottedKeyNonTableException(string key)
		{
			Key = key;
		}
	}
	public class TomlDateTimeMissingSeparatorException : TomlExceptionWithLine
	{
		public override string Message => $"Found a date-time on line {LineNumber} which is missing a separator (T, t, or a space) between the date and time.";

		public TomlDateTimeMissingSeparatorException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class TomlDateTimeUnnecessarySeparatorException : TomlExceptionWithLine
	{
		public override string Message => $"Found an unnecessary date-time separator (T, t, or a space) in a date or time on line {LineNumber}";

		public TomlDateTimeUnnecessarySeparatorException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class TomlDottedKeyException : TomlException
	{
		private readonly string _key;

		public override string Message => "Tried to redefine key " + _key + " as a table (by way of a dotted key) when it's already defined as not being a table.";

		public TomlDottedKeyException(string key)
		{
			_key = key;
		}
	}
	public class TomlDottedKeyParserException : TomlExceptionWithLine
	{
		private readonly string _key;

		public override string Message => $"Tried to redefine key {_key} as a table (by way of a dotted key on line {LineNumber}) when it's already defined as not being a table.";

		public TomlDottedKeyParserException(int lineNumber, string key)
			: base(lineNumber)
		{
			_key = key;
		}
	}
	public class TomlDoubleDottedKeyException : TomlExceptionWithLine
	{
		public override string Message => "Found two consecutive dots, or a leading dot, in a key on line " + LineNumber;

		public TomlDoubleDottedKeyException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class TomlEndOfFileException : TomlExceptionWithLine
	{
		public override string Message => $"Found unexpected EOF on line {LineNumber} when parsing TOML file";

		public TomlEndOfFileException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class TomlEnumParseException : TomlException
	{
		private string _valueName;

		private Type _enumType;

		public override string Message => $"Could not find enum value by name \"{_valueName}\" in enum class {_enumType} while deserializing.";

		public TomlEnumParseException(string valueName, Type enumType)
		{
			_valueName = valueName;
			_enumType = enumType;
		}
	}
	public abstract class TomlException : Exception
	{
		protected TomlException()
		{
		}

		protected TomlException(Exception cause)
			: base("", cause)
		{
		}
	}
	public abstract class TomlExceptionWithLine : TomlException
	{
		protected int LineNumber;

		protected TomlExceptionWithLine(int lineNumber)
		{
			LineNumber = lineNumber;
		}

		protected TomlExceptionWithLine(int lineNumber, Exception cause)
			: base(cause)
		{
			LineNumber = lineNumber;
		}
	}
	public class TomlFieldTypeMismatchException : TomlTypeMismatchException
	{
		private readonly Type _typeBeingInstantiated;

		private readonly FieldInfo _fieldBeingDeserialized;

		public override string Message => $"While deserializing an object of type {_typeBeingInstantiated}, found field {_fieldBeingDeserialized.Name} expecting a type of {ExpectedTypeName}, but value in TOML was of type {ActualTypeName}";

		public TomlFieldTypeMismatchException(Type typeBeingInstantiated, FieldInfo fieldBeingDeserialized, TomlTypeMismatchException cause)
			: base(cause.ExpectedType, cause.ActualType, fieldBeingDeserialized.FieldType)
		{
			_typeBeingInstantiated = typeBeingInstantiated;
			_fieldBeingDeserialized = fieldBeingDeserialized;
		}
	}
	public class TomlInlineTableSeparatorException : TomlExceptionWithLine
	{
		private readonly char _found;

		public override string Message => $"Expected '}}' or ',' after key-value pair in TOML inline table, found '{_found}'";

		public TomlInlineTableSeparatorException(int lineNumber, char found)
			: base(lineNumber)
		{
			_found = found;
		}
	}
	public class TomlInstantiationException : TomlException
	{
		private readonly Type _type;

		public override string Message => "Could not find a no-argument constructor for type " + _type.FullName;

		public TomlInstantiationException(Type type)
		{
			_type = type;
		}
	}
	public class TomlInternalException : TomlExceptionWithLine
	{
		public override string Message => $"An internal exception occured while parsing line {LineNumber} of the TOML document";

		public TomlInternalException(int lineNumber, Exception cause)
			: base(lineNumber, cause)
		{
		}
	}
	public class TomlInvalidValueException : TomlExceptionWithLine
	{
		private readonly char _found;

		public override string Message => $"Expected the start of a number, string literal, boolean, array, or table on line {LineNumber}, found '{_found}'";

		public TomlInvalidValueException(int lineNumber, char found)
			: base(lineNumber)
		{
			_found = found;
		}
	}
	public class TomlKeyRedefinitionException : TomlExceptionWithLine
	{
		private readonly string _key;

		public override string Message => $"TOML document attempts to re-define key '{_key}' on line {LineNumber}";

		public TomlKeyRedefinitionException(int lineNumber, string key)
			: base(lineNumber)
		{
			_key = key;
		}
	}
	public class TomlMissingEqualsException : TomlExceptionWithLine
	{
		private readonly char _found;

		public override string Message => $"Expecting an equals sign ('=') on line {LineNumber}, but found '{_found}'";

		public TomlMissingEqualsException(int lineNumber, char found)
			: base(lineNumber)
		{
			_found = found;
		}
	}
	public class TomlMissingNewlineException : TomlExceptionWithLine
	{
		private readonly char _found;

		public override string Message => $"Expecting a newline character at the end of a statement on line {LineNumber}, but found an unexpected '{_found}'";

		public TomlMissingNewlineException(int lineNumber, char found)
			: base(lineNumber)
		{
			_found = found;
		}
	}
	public class TomlNewlineInInlineCommentException : TomlException
	{
		public override string Message => "An attempt was made to set an inline comment which contains a newline. This obviously cannot be done, as inline comments must fit on one line.";
	}
	public class TomlNonTableArrayUsedAsTableArrayException : TomlExceptionWithLine
	{
		private readonly string _arrayName;

		public override string Message => $"{_arrayName} is used as a table-array on line {LineNumber} when it has previously been defined as a static array. This is not allowed.";

		public TomlNonTableArrayUsedAsTableArrayException(int lineNumber, string arrayName)
			: base(lineNumber)
		{
			_arrayName = arrayName;
		}
	}
	public class TomlNoSuchValueException : TomlException
	{
		private readonly string _key;

		public override string Message => "Attempted to get the value for key " + _key + " but no value is associated with that key";

		public TomlNoSuchValueException(string key)
		{
			_key = key;
		}
	}
	public class TomlPrimitiveToDocumentException : TomlException
	{
		private Type primitiveType;

		public override string Message => "Tried to create a TOML document from a primitive value of type " + primitiveType.Name + ". Documents can only be created from objects.";

		public TomlPrimitiveToDocumentException(Type primitiveType)
		{
			this.primitiveType = primitiveType;
		}
	}
	public class TomlPropertyTypeMismatchException : TomlTypeMismatchException
	{
		private readonly Type _typeBeingInstantiated;

		private readonly PropertyInfo _propBeingDeserialized;

		public override string Message => $"While deserializing an object of type {_typeBeingInstantiated}, found property {_propBeingDeserialized.Name} expecting a type of {ExpectedTypeName}, but value in TOML was of type {ActualTypeName}";

		public TomlPropertyTypeMismatchException(Type typeBeingInstantiated, PropertyInfo propBeingDeserialized, TomlTypeMismatchException cause)
			: base(cause.ExpectedType, cause.ActualType, propBeingDeserialized.PropertyType)
		{
			_typeBeingInstantiated = typeBeingInstantiated;
			_propBeingDeserialized = propBeingDeserialized;
		}
	}
	public class TomlStringException : TomlExceptionWithLine
	{
		public override string Message => $"Found an invalid TOML string on line {LineNumber}";

		public TomlStringException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class TomlTableArrayAlreadyExistsAsNonArrayException : TomlExceptionWithLine
	{
		private readonly string _arrayName;

		public override string Message => $"{_arrayName} is defined as a table-array (double-bracketed section) on line {LineNumber} but it has previously been used as a non-array type.";

		public TomlTableArrayAlreadyExistsAsNonArrayException(int lineNumber, string arrayName)
			: base(lineNumber)
		{
			_arrayName = arrayName;
		}
	}
	public class TomlTableLockedException : TomlExceptionWithLine
	{
		private readonly string _key;

		public override string Message => $"TOML table is locked (e.g. defined inline), cannot add or update key {_key} to it on line {LineNumber}";

		public TomlTableLockedException(int lineNumber, string key)
			: base(lineNumber)
		{
			_key = key;
		}
	}
	public class TomlTableRedefinitionException : TomlExceptionWithLine
	{
		private readonly string _key;

		public override string Message => $"TOML document attempts to re-define table '{_key}' on line {LineNumber}";

		public TomlTableRedefinitionException(int lineNumber, string key)
			: base(lineNumber)
		{
			_key = key;
		}
	}
	public class TomlTripleQuotedKeyException : TomlExceptionWithLine
	{
		public override string Message => $"Found a triple-quoted key on line {LineNumber}. This is not allowed.";

		public TomlTripleQuotedKeyException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class TomlTypeMismatchException : TomlException
	{
		protected readonly string ExpectedTypeName;

		protected readonly string ActualTypeName;

		protected internal readonly Type ExpectedType;

		protected internal readonly Type ActualType;

		private readonly Type _context;

		public override string Message => $"While trying to convert to type {_context}, a TOML value of type {ExpectedTypeName} was required but a value of type {ActualTypeName} was found";

		public TomlTypeMismatchException(Type expected, Type actual, Type context)
		{
			ExpectedTypeName = (typeof(TomlValue).IsAssignableFrom(expected) ? expected.Name.Replace("Toml", "") : expected.Name);
			ActualTypeName = (typeof(TomlValue).IsAssignableFrom(actual) ? actual.Name.Replace("Toml", "") : actual.Name);
			ExpectedType = expected;
			ActualType = actual;
			_context = context;
		}
	}
	public class TomlUnescapedUnicodeControlCharException : TomlExceptionWithLine
	{
		private readonly int _theChar;

		public override string Message => $"Found an unescaped unicode control character U+{_theChar:0000} on line {LineNumber}. Control character other than tab (U+0009) are not allowed in TOML unless they are escaped.";

		public TomlUnescapedUnicodeControlCharException(int lineNumber, int theChar)
			: base(lineNumber)
		{
			_theChar = theChar;
		}
	}
	public class TomlWhitespaceInKeyException : TomlExceptionWithLine
	{
		public override string Message => "Found whitespace in an unquoted TOML key at line " + LineNumber;

		public TomlWhitespaceInKeyException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class TripleQuoteInTomlMultilineLiteralException : TomlExceptionWithLine
	{
		public override string Message => $"Found a triple-single-quote (''') inside a multiline string literal on line {LineNumber}. This is not allowed.";

		public TripleQuoteInTomlMultilineLiteralException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class TripleQuoteInTomlMultilineSimpleStringException : TomlExceptionWithLine
	{
		public override string Message => $"Found a triple-double-quote (\"\"\") inside a multiline simple string on line {LineNumber}. This is not allowed.";

		public TripleQuoteInTomlMultilineSimpleStringException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class UnterminatedTomlKeyException : TomlExceptionWithLine
	{
		public override string Message => $"Found an unterminated quoted key on line {LineNumber}";

		public UnterminatedTomlKeyException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class UnterminatedTomlStringException : TomlExceptionWithLine
	{
		public override string Message => $"Found an unterminated TOML string on line {LineNumber}";

		public UnterminatedTomlStringException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class UnterminatedTomlTableArrayException : TomlExceptionWithLine
	{
		public override string Message => $"Found an unterminated table-array (expecting two ]s to close it) on line {LineNumber}";

		public UnterminatedTomlTableArrayException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
	public class UnterminatedTomlTableNameException : TomlExceptionWithLine
	{
		public override string Message => $"Found an unterminated table name on line {LineNumber}";

		public UnterminatedTomlTableNameException(int lineNumber)
			: base(lineNumber)
		{
		}
	}
}
namespace Tomlet.Attributes
{
	internal class NoCoverageAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class)]
	public class TomlDoNotInlineObjectAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
	public class TomlInlineCommentAttribute : Attribute
	{
		internal string Comment { get; }

		public TomlInlineCommentAttribute(string comment)
		{
			Comment = comment;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
	public class TomlPrecedingCommentAttribute : Attribute
	{
		internal string Comment { get; }

		public TomlPrecedingCommentAttribute(string comment)
		{
			Comment = comment;
		}
	}
	[AttributeUsage(AttributeTargets.Property)]
	public class TomlPropertyAttribute : Attribute
	{
		private readonly string _mapFrom;

		public TomlPropertyAttribute(string mapFrom)
		{
			_mapFrom = mapFrom;
		}

		public string GetMappedString()
		{
			return _mapFrom;
		}
	}
}

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/BepInEx.MelonLoader.Loader/WebSocketDotNet.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using WebSocketDotNet.Http;
using WebSocketDotNet.Messages;
using WebSocketDotNet.Protocol;
using WebSocketDotNet.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("WebSocketDotNet.Tests")]
[assembly: AssemblyCompany("N/A")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("\r\n            WebSocketDotNet is a .NET library for WebSockets. Compared to similar libraries, the main advantage is that it works\r\n            on more versions of .NET, from .NET Framework 3.5 to .NET 6.0.\r\n        ")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+e1c3c33f40bfed34fd57b5a048540bcb1e8db26f")]
[assembly: AssemblyProduct("WebSocketDotNet")]
[assembly: AssemblyTitle("WebSocketDotNet")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace WebSocketDotNet
{
	internal static class AssemblyInfo
	{
		public static readonly string Name = Assembly.GetExecutingAssembly().GetName().Name;

		public static readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version;
	}
	public enum MessageChunkingMode
	{
		AlwaysUseExtendedLength,
		LimitTo16BitExtendedLength,
		NeverUseExtendedLength
	}
	public class WebSocket
	{
		private static readonly Guid WebsocketKeyGuid = new Guid("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");

		private readonly Random _random = new Random();

		private readonly SHA1 _sha1 = SHA1.Create();

		private readonly HttpHandler _httpHandler;

		private readonly List<WebSocketFragment> _currentPartialFragments = new List<WebSocketFragment>();

		private readonly object _sendLock = new object();

		private readonly object _receiveLock = new object();

		private Thread? _receiveThread;

		private WebSocketCloseMessage? _closeMessage;

		private WebSocketConfiguration _configuration;

		public WebSocketState State { get; private set; }

		public event Action Opened = delegate
		{
		};

		public event Action<WebSocketCloseCode, string?> Closing = delegate
		{
		};

		public event Action<WebSocketCloseCode, string?> Closed = delegate
		{
		};

		public event Action<byte[]> PongReceived = delegate
		{
		};

		public event Action<byte[]> BinaryReceived = delegate
		{
		};

		public event Action<string> TextReceived = delegate
		{
		};

		public event Action<WebSocketMessage> MessageReceived = delegate
		{
		};

		[Obsolete("Use the constructor that takes a WebSocketConfiguration instead")]
		public WebSocket(string url, bool autoConnect = true, bool useReceiveThread = true)
			: this(url, new WebSocketConfiguration
			{
				AutoConnect = autoConnect,
				UseAutomaticReceiveThread = useReceiveThread
			})
		{
		}

		public WebSocket(string url, WebSocketConfiguration configuration = default(WebSocketConfiguration))
		{
			_configuration = configuration;
			UriUtils.ValidateUrlScheme(ref url);
			_httpHandler = new HttpHandler(new Uri(url));
			State = WebSocketState.Closed;
			if (configuration.AutoConnect)
			{
				Connect();
			}
		}

		public void Connect()
		{
			if (State != WebSocketState.Closed)
			{
				throw new InvalidOperationException("Cannot connect while in state " + State);
			}
			try
			{
				SendHandshakeRequest();
			}
			catch (Exception e)
			{
				OnException(e);
				throw;
			}
			OnOpen();
		}

		private void SendHandshakeRequest()
		{
			State = WebSocketState.Connecting;
			Dictionary<string, string> dictionary = BuildHandshakeHeaders();
			HttpResponse resp = _httpHandler.SendRequestWithHeaders(dictionary);
			ValidateResponse(resp, dictionary["Sec-WebSocket-Key"]);
		}

		private Dictionary<string, string> BuildHandshakeHeaders()
		{
			byte[] array = new byte[16];
			_random.NextBytes(array);
			string value = Convert.ToBase64String(array);
			return new Dictionary<string, string>
			{
				{ "Upgrade", "websocket" },
				{ "Connection", "Upgrade" },
				{ "Sec-WebSocket-Key", value },
				{ "Sec-WebSocket-Version", "13" }
			};
		}

		private void ValidateResponse(HttpResponse resp, string key)
		{
			string text = Convert.ToBase64String(_sha1.ComputeHash(Encoding.UTF8.GetBytes(key + WebsocketKeyGuid.ToString().ToUpperInvariant())));
			if (resp.StatusCode != HttpStatusCode.SwitchingProtocols)
			{
				throw new WebException($"Expecting HTTP 101/SwitchingProtocols, got {(int)resp.StatusCode}/{resp.StatusCode}");
			}
			if (!resp.Headers.TryGetValue("Upgrade", out string value) || value != "websocket")
			{
				throw new WebException("Expecting Upgrade: websocket, got \"" + value + "\"");
			}
			if (!resp.Headers.TryGetValue("Sec-WebSocket-Accept", out string value2) || value2 != text)
			{
				throw new WebException("Invalid or no Sec-WebSocket-Accept header in response (got \"" + value2 + "\", expected \"" + text + "\")");
			}
		}

		public void Send(WebSocketMessage message)
		{
			WebSocketState state = State;
			if (state != WebSocketState.Open && state != WebSocketState.Closing)
			{
				throw new InvalidOperationException("WebSocket is not open");
			}
			List<WebSocketFragment> list = message.ToFrame().ToFragments(_configuration.MessageChunkingMode);
			Stream orOpenStream = _httpHandler.GetOrOpenStream();
			Monitor.Enter(_sendLock);
			foreach (WebSocketFragment item in list)
			{
				byte[] bytes = item.Serialize();
				Extensions.Write(orOpenStream, bytes);
			}
			Monitor.Exit(_sendLock);
		}

		public void SendClose(WebSocketCloseCode code = WebSocketCloseCode.ClosedOk, string? reason = null)
		{
			if (State == WebSocketState.Closed)
			{
				return;
			}
			if (State == WebSocketState.Closing)
			{
				if (code == WebSocketCloseCode.InternalError)
				{
					this.Closing(code, reason);
				}
				return;
			}
			if (State == WebSocketState.Connecting)
			{
				if (code == WebSocketCloseCode.ProtocolError || code == WebSocketCloseCode.InternalError)
				{
					this.Closing(code, reason);
					_closeMessage = new WebSocketCloseMessage(code, reason);
					OnClose();
					return;
				}
				throw new InvalidOperationException("Cannot send close message while connecting");
			}
			if (code == WebSocketCloseCode.Reserved)
			{
				throw new ArgumentException("Cannot use reserved close codes", "code");
			}
			State = WebSocketState.Closing;
			_closeMessage = new WebSocketCloseMessage(code, reason);
			this.Closing(code, reason);
			try
			{
				Send(_closeMessage);
			}
			catch (Exception e)
			{
				OnException(e);
			}
		}

		public void ReceiveAllAvailable()
		{
			WebSocketState state = State;
			if (state != WebSocketState.Open && state != WebSocketState.Closing)
			{
				return;
			}
			List<WebSocketFragment> list = new List<WebSocketFragment>();
			Monitor.Enter(_receiveLock);
			do
			{
				try
				{
					WebSocketFragment item = ReceiveOneFragment();
					list.Add(item);
				}
				catch (Exception e)
				{
					OnException(e);
				}
			}
			while (_httpHandler.AnyDataAvailable);
			Monitor.Exit(_receiveLock);
			try
			{
				list.ForEach(ProcessFragment);
			}
			catch (Exception e2)
			{
				OnException(e2);
			}
		}

		private void ReceiveLoop()
		{
			while (true)
			{
				WebSocketState state = State;
				if (state == WebSocketState.Open || state == WebSocketState.Closing)
				{
					try
					{
						ReceiveAllAvailable();
					}
					catch (Exception e)
					{
						OnException(e);
					}
					Thread.Sleep(10);
					continue;
				}
				break;
			}
		}

		private WebSocketFragment ReceiveOneFragment()
		{
			WebSocketState state = State;
			if (state != WebSocketState.Open && state != WebSocketState.Closing)
			{
				throw new InvalidOperationException("WebSocket is not open");
			}
			return WebSocketFragment.Read(_httpHandler.GetOrOpenStream());
		}

		private void ProcessFragment(WebSocketFragment fragment)
		{
			if (fragment.Reserved1 || fragment.Reserved2 || fragment.Reserved3)
			{
				throw new WebSocketProtocolException("Reserved bits set in fragment");
			}
			if (fragment.Opcode == WebSocketOpcode.Continuation)
			{
				if (_currentPartialFragments.Count == 0)
				{
					throw new WebSocketProtocolException("Received unexpected continuation fragment with no partial fragments");
				}
				_currentPartialFragments.Add(fragment);
				if (fragment.IsFinal)
				{
					WebSocketFrame frame = WebSocketFrame.FromFragments(_currentPartialFragments);
					_currentPartialFragments.Clear();
					ProcessFrame(frame);
				}
				return;
			}
			if (_currentPartialFragments.Count > 0 && !fragment.Opcode.IsControlOpcode())
			{
				throw new WebSocketProtocolException("Received non-continuation, non-control fragment with incomplete frame in buffer");
			}
			if (fragment.IsFinal)
			{
				ProcessFrame(WebSocketFrame.FromFragment(fragment));
				return;
			}
			if (fragment.Opcode.IsControlOpcode())
			{
				throw new WebSocketProtocolException($"Received fragmented control frame! (opcode: {fragment.Opcode})");
			}
			_currentPartialFragments.Add(fragment);
		}

		private void ProcessFrame(WebSocketFrame frame)
		{
			ProcessMessage(WebSocketMessage.FromFrame(frame));
		}

		private void ProcessMessage(WebSocketMessage message)
		{
			if (!(message is WebSocketPingMessage webSocketPingMessage))
			{
				if (!(message is WebSocketPongMessage webSocketPongMessage))
				{
					if (!(message is WebSocketCloseMessage webSocketCloseMessage))
					{
						if (!(message is WebSocketBinaryMessage webSocketBinaryMessage))
						{
							if (message is WebSocketTextMessage webSocketTextMessage)
							{
								this.TextReceived(webSocketTextMessage.Text);
							}
						}
						else
						{
							this.BinaryReceived(webSocketBinaryMessage.Data);
						}
					}
					else if (State == WebSocketState.Closing)
					{
						_closeMessage = webSocketCloseMessage;
						OnClose();
					}
					else
					{
						WebSocketCloseMessage webSocketCloseMessage2 = webSocketCloseMessage;
						SendClose(webSocketCloseMessage2.CloseReason, webSocketCloseMessage2.CloseReasonText);
					}
				}
				else
				{
					this.PongReceived(webSocketPongMessage.PongPayload);
				}
			}
			else
			{
				Send(new WebSocketPongMessage(webSocketPingMessage.PingPayload));
			}
			this.MessageReceived(message);
		}

		private void OnClose()
		{
			if (State != WebSocketState.Closing || _closeMessage == null)
			{
				_closeMessage = new WebSocketCloseMessage(WebSocketCloseCode.AbnormalClosure, "Unexpected close");
			}
			_httpHandler.CloseAnyExistingStream();
			State = WebSocketState.Closed;
			this.Closed(_closeMessage.CloseReason, _closeMessage.CloseReasonText);
		}

		private void OnOpen()
		{
			_closeMessage = null;
			_currentPartialFragments.Clear();
			this.Opened();
			if (_receiveThread != null)
			{
				if (_receiveThread.IsAlive)
				{
					Console.WriteLine("Warning - receive thread still running!");
				}
				_receiveThread = null;
			}
			State = WebSocketState.Open;
			if (_configuration.UseAutomaticReceiveThread)
			{
				_receiveThread = new Thread(ReceiveLoop)
				{
					Name = "WebSocket Receive Thread",
					IsBackground = true
				};
				_receiveThread.Start();
			}
		}

		private void OnException(Exception e)
		{
			if (e is WebSocketProtocolException ex)
			{
				SendClose(WebSocketCloseCode.ProtocolError, ex.Message);
				return;
			}
			if (e is IOException ex2)
			{
				if (ex2.InnerException is SocketException ex3)
				{
					e = ex3;
				}
				else if (State == WebSocketState.Closing)
				{
					OnClose();
					return;
				}
			}
			if (e is SocketException ex4)
			{
				if (ex4.SocketErrorCode == SocketError.ConnectionReset)
				{
					if (State == WebSocketState.Closing)
					{
						_closeMessage = new WebSocketCloseMessage(WebSocketCloseCode.ClosedOk, "Websocket closed");
						State = WebSocketState.Closing;
						OnClose();
					}
					else
					{
						OnClose();
					}
					return;
				}
				if (ex4.SocketErrorCode == SocketError.ConnectionRefused)
				{
					_closeMessage = new WebSocketCloseMessage(WebSocketCloseCode.ProtocolError, "Connection refused");
					State = WebSocketState.Closing;
					OnClose();
					return;
				}
			}
			SendClose(WebSocketCloseCode.InternalError, e.Message);
		}
	}
	public enum WebSocketCloseCode : ushort
	{
		Unspecified = 0,
		ClosedOk = 1000,
		GoingAway = 1001,
		ProtocolError = 1002,
		UnsupportedData = 1003,
		Reserved = 1004,
		NoStatus = 1005,
		AbnormalClosure = 1006,
		MismatchTypeAndPayload = 1007,
		PolicyViolation = 1008,
		MessageTooBig = 1009,
		MissingMandatoryExtension = 1010,
		InternalError = 1011,
		TlsHandshakeFailure = 1015
	}
	public struct WebSocketConfiguration
	{
		public bool AutoConnect { get; set; }

		public bool UseAutomaticReceiveThread { get; set; }

		public MessageChunkingMode MessageChunkingMode { get; set; }

		public WebSocketConfiguration()
		{
			AutoConnect = true;
			UseAutomaticReceiveThread = true;
			MessageChunkingMode = MessageChunkingMode.LimitTo16BitExtendedLength;
		}
	}
	[NoCoverage]
	public class WebSocketProtocolException : Exception
	{
		public WebSocketProtocolException(string message)
			: base(message)
		{
		}
	}
	public enum WebSocketState
	{
		Connecting,
		Open,
		Closing,
		Closed
	}
}
namespace WebSocketDotNet.Utils
{
	internal static class Extensions
	{
		internal static byte[] ReadToEnd(this Stream s, NetworkStreamProvider provider)
		{
			List<byte> list = new List<byte>();
			byte[] array = new byte[1024];
			int num;
			while (provider.AnythingToRead && (num = s.Read(array, 0, array.Length)) > 0)
			{
				byte[] array2 = new byte[num];
				Array.Copy(array, 0, array2, 0, num);
				list.AddRange(array2);
			}
			return list.ToArray();
		}

		internal static void Write(this Stream s, byte[] bytes)
		{
			s.Write(bytes, 0, bytes.Length);
		}

		internal static bool Bit(this byte b, int bit)
		{
			return (b & (1 << bit)) != 0;
		}

		internal static byte Bits(this byte b, int start, int end)
		{
			int num = 255 >> 8 - (end - start + 1);
			return (byte)((b >> start) & num);
		}

		public static bool IsControlOpcode(this WebSocketOpcode opcode)
		{
			if (opcode != WebSocketOpcode.Close && opcode != WebSocketOpcode.Ping)
			{
				return opcode == WebSocketOpcode.Pong;
			}
			return true;
		}
	}
	internal static class MiscUtils
	{
		public static T[] EmptyArray<T>()
		{
			return new T[0];
		}
	}
	internal class NoCoverageAttribute : Attribute
	{
	}
	internal static class UriUtils
	{
		public static void ValidateUrlScheme(ref string url)
		{
			Uri uri = new Uri(url);
			if (uri.Scheme == "http")
			{
				url = $"ws://{uri.Host}:{uri.Port}{uri.PathAndQuery}";
				return;
			}
			if (uri.Scheme == "https")
			{
				url = $"wss://{uri.Host}:{uri.Port}{uri.PathAndQuery}";
				return;
			}
			string scheme = uri.Scheme;
			if (scheme == "ws" || scheme == "wss")
			{
				return;
			}
			throw new WebException("Invalid url protocol. Must be one of http, https, ws or wss");
		}
	}
}
namespace WebSocketDotNet.Protocol
{
	internal class WebSocketFragment
	{
		private const byte MaxSingleFragmentPayloadSize = 125;

		private const byte ShortLengthExtended16Bit = 126;

		private const byte ShortLengthExtended64Bit = 127;

		private static readonly Random MaskGenerator = new Random();

		public bool IsFinal;

		public bool Reserved1;

		public bool Reserved2;

		public bool Reserved3;

		public WebSocketOpcode Opcode;

		public bool IsMasked;

		private byte _shortPayloadLength;

		private ulong _extendedPayloadLength;

		public byte[] Mask;

		private byte[] _rawPayload;

		public ulong PayloadLength
		{
			get
			{
				if (!UsesExtendedPayloadLength)
				{
					return _shortPayloadLength;
				}
				return _extendedPayloadLength;
			}
		}

		public byte[] Payload => _rawPayload;

		private bool UsesExtendedPayloadLength => _extendedPayloadLength != ulong.MaxValue;

		private WebSocketFragment()
		{
			Mask = new byte[4];
			_rawPayload = MiscUtils.EmptyArray<byte>();
		}

		public WebSocketFragment(bool final, WebSocketOpcode opcode, byte[] payload, bool mask)
			: this()
		{
			IsFinal = final;
			Opcode = opcode;
			_rawPayload = (byte[])payload.Clone();
			ComputeOutgoingLength();
			if (mask)
			{
				MaskPayload();
			}
		}

		private void XorPayloadWithMask()
		{
			for (int i = 0; i < _rawPayload.Length; i++)
			{
				int num = i % 4;
				byte b = Mask[num];
				_rawPayload[i] ^= b;
			}
		}

		private void UnmaskPayload()
		{
			XorPayloadWithMask();
			IsMasked = false;
			Array.Clear(Mask, 0, 4);
		}

		private void MaskPayload()
		{
			MaskGenerator.NextBytes(Mask);
			XorPayloadWithMask();
			IsMasked = true;
		}

		private void ReadLength(byte[] initialHeader, Stream stream)
		{
			byte b = initialHeader[1].Bits(0, 6);
			switch (b)
			{
			case 126:
			{
				if (stream.Read(initialHeader, 0, 2) != 2)
				{
					throw new IOException("Failed to read 2-byte extended length from stream");
				}
				ref byte reference = ref initialHeader[0];
				ref byte reference2 = ref initialHeader[1];
				byte b2 = initialHeader[1];
				byte b3 = initialHeader[0];
				reference = b2;
				reference2 = b3;
				_extendedPayloadLength = BitConverter.ToUInt16(initialHeader, 0);
				break;
			}
			case 127:
				initialHeader = new byte[8];
				if (stream.Read(initialHeader, 0, 8) != 8)
				{
					throw new IOException("Failed to read 8-byte extended length from stream");
				}
				Array.Reverse((Array)initialHeader);
				_extendedPayloadLength = BitConverter.ToUInt64(initialHeader, 0);
				if (_extendedPayloadLength >> 63 != 0L)
				{
					throw new IOException("64-bit extended payload length has most significant bit set, which is not allowed");
				}
				break;
			default:
				_shortPayloadLength = b;
				_extendedPayloadLength = ulong.MaxValue;
				break;
			}
		}

		private void ComputeOutgoingLength()
		{
			if (_rawPayload.Length <= 125)
			{
				_shortPayloadLength = (byte)_rawPayload.Length;
				_extendedPayloadLength = ulong.MaxValue;
				return;
			}
			if (_rawPayload.Length <= 65535)
			{
				_shortPayloadLength = 126;
			}
			else
			{
				_shortPayloadLength = 127;
			}
			_extendedPayloadLength = (ulong)_rawPayload.Length;
		}

		public static WebSocketFragment Read(Stream from)
		{
			byte[] array = new byte[2];
			if (from.Read(array, 0, 2) != 2)
			{
				throw new IOException("Failed to read 2-byte header from stream");
			}
			WebSocketFragment webSocketFragment = ParseTwoByteHeader(array);
			webSocketFragment.ReadLength(array, from);
			if (webSocketFragment.IsMasked && from.Read(webSocketFragment.Mask, 0, 4) != 4)
			{
				throw new IOException("Failed to read 4-byte mask from stream");
			}
			if (webSocketFragment.PayloadLength > int.MaxValue)
			{
				throw new IOException($"Cannot read >2GiB payload (length in header was {webSocketFragment.PayloadLength} bytes)");
			}
			webSocketFragment._rawPayload = new byte[(uint)webSocketFragment.PayloadLength];
			if (from.Read(webSocketFragment._rawPayload, 0, (int)webSocketFragment.PayloadLength) != (int)webSocketFragment.PayloadLength)
			{
				throw new IOException("Failed to read payload from stream");
			}
			if (webSocketFragment.IsMasked)
			{
				webSocketFragment.UnmaskPayload();
			}
			return webSocketFragment;
		}

		private static WebSocketFragment ParseTwoByteHeader(byte[] buf)
		{
			return new WebSocketFragment
			{
				IsFinal = buf[0].Bit(7),
				Reserved1 = buf[0].Bit(6),
				Reserved2 = buf[0].Bit(5),
				Reserved3 = buf[0].Bit(4),
				Opcode = (WebSocketOpcode)buf[0].Bits(0, 3),
				IsMasked = buf[1].Bit(7)
			};
		}

		public byte[] Serialize()
		{
			byte[] array;
			if (!UsesExtendedPayloadLength && !IsMasked)
			{
				array = new byte[2 + _rawPayload.Length];
				WriteTwoByteHeader(array);
				Array.Copy(_rawPayload, 0, array, 2, _rawPayload.Length);
			}
			else if (!UsesExtendedPayloadLength && IsMasked)
			{
				array = new byte[6 + _rawPayload.Length];
				WriteTwoByteHeader(array);
				Array.Copy(Mask, 0, array, 2, 4);
				Array.Copy(_rawPayload, 0, array, 6, _rawPayload.Length);
			}
			else
			{
				int num = ((_shortPayloadLength == 126) ? 2 : 8);
				int num2 = (IsMasked ? 4 : 0);
				array = new byte[2 + num + num2 + _rawPayload.Length];
				WriteTwoByteHeader(array);
				if (num == 2)
				{
					array[2] = (byte)(_extendedPayloadLength >> 8);
					array[3] = (byte)_extendedPayloadLength;
				}
				else
				{
					byte[] bytes = BitConverter.GetBytes(_extendedPayloadLength);
					Array.Reverse((Array)bytes);
					Array.Copy(bytes, 0, array, 2, 8);
				}
				if (IsMasked)
				{
					Array.Copy(Mask, 0, array, 2 + num, 4);
				}
				Array.Copy(_rawPayload, 0, array, 2 + num + num2, _rawPayload.Length);
			}
			return array;
		}

		private void WriteTwoByteHeader(byte[] toWrite)
		{
			toWrite[0] = (byte)((uint)Opcode | (uint)(byte)(IsFinal ? 128u : 0u) | (byte)(Reserved1 ? 64u : 0u) | (byte)(Reserved2 ? 32u : 0u) | (byte)(Reserved3 ? 16u : 0u));
			toWrite[1] = (byte)(_shortPayloadLength | (byte)(IsMasked ? 128u : 0u));
		}
	}
	internal class WebSocketFrame
	{
		public WebSocketOpcode Opcode { get; set; }

		public byte[] Payload { get; set; }

		public WebSocketFrame(WebSocketOpcode opcode, byte[] payload)
		{
			Opcode = opcode;
			Payload = payload;
		}

		internal List<WebSocketFragment> ToFragments(MessageChunkingMode configurationMessageChunkingMode)
		{
			List<WebSocketFragment> list = new List<WebSocketFragment>();
			int num = configurationMessageChunkingMode switch
			{
				MessageChunkingMode.AlwaysUseExtendedLength => int.MaxValue, 
				MessageChunkingMode.NeverUseExtendedLength => 127, 
				MessageChunkingMode.LimitTo16BitExtendedLength => 65535, 
				_ => throw new ArgumentOutOfRangeException("configurationMessageChunkingMode", configurationMessageChunkingMode, null), 
			};
			if (Payload.Length < num)
			{
				list.Add(new WebSocketFragment(final: true, Opcode, Payload, mask: true));
			}
			else
			{
				int num2 = 0;
				int num3 = Payload.Length;
				WebSocketOpcode opcode = Opcode;
				while (num3 > 0)
				{
					int num4 = Math.Min(num3, num);
					byte[] array = new byte[num4];
					Array.Copy(Payload, num2, array, 0, num4);
					num3 -= num4;
					num2 += num4;
					WebSocketFragment item = new WebSocketFragment(num3 == 0, opcode, array, mask: true);
					list.Add(item);
					opcode = WebSocketOpcode.Continuation;
				}
			}
			return list;
		}

		internal static WebSocketFrame FromFragments(List<WebSocketFragment> fragments)
		{
			List<byte> list = new List<byte>();
			foreach (WebSocketFragment fragment in fragments)
			{
				list.AddRange(fragment.Payload);
			}
			return new WebSocketFrame(fragments[0].Opcode, list.ToArray());
		}

		internal static WebSocketFrame FromFragment(WebSocketFragment fragment)
		{
			return new WebSocketFrame(fragment.Opcode, fragment.Payload);
		}
	}
	public enum WebSocketOpcode : byte
	{
		Continuation,
		Text,
		Binary,
		ReservedData3,
		ReservedData4,
		ReservedData5,
		ReservedData6,
		ReservedData7,
		Close,
		Ping,
		Pong,
		ReservedControlB,
		ReservedControlC,
		ReservedControlD,
		ReservedControlE
	}
}
namespace WebSocketDotNet.Messages
{
	public class WebSocketBinaryMessage : WebSocketMessage
	{
		public byte[] Data { get; private set; }

		protected override WebSocketOpcode OpcodeToSend => WebSocketOpcode.Binary;

		public WebSocketBinaryMessage(byte[] data)
		{
			Data = data;
		}

		internal WebSocketBinaryMessage()
		{
			Data = MiscUtils.EmptyArray<byte>();
		}

		protected override void ReadData(byte[] payload)
		{
			Data = payload;
		}

		protected override byte[] GetPayload()
		{
			return Data;
		}
	}
	public class WebSocketCloseMessage : WebSocketMessage
	{
		public WebSocketCloseCode CloseReason { get; private set; }

		public string? CloseReasonText { get; private set; }

		protected override WebSocketOpcode OpcodeToSend => WebSocketOpcode.Close;

		public WebSocketCloseMessage(WebSocketCloseCode closeReason, string? closeReasonText = null)
		{
			CloseReason = closeReason;
			CloseReasonText = closeReasonText;
		}

		internal WebSocketCloseMessage()
		{
			CloseReason = WebSocketCloseCode.NoStatus;
		}

		protected override void ReadData(byte[] payload)
		{
			if (payload.Length != 0)
			{
				if (payload.Length < 2)
				{
					throw new WebSocketProtocolException($"Close message payload is too short. Expected at least 2 bytes, got {payload.Length}");
				}
				CloseReason = (WebSocketCloseCode)((payload[0] << 8) | payload[1]);
				if (payload.Length > 2)
				{
					CloseReasonText = Encoding.UTF8.GetString(payload, 2, payload.Length - 2);
				}
			}
		}

		protected override byte[] GetPayload()
		{
			if (CloseReasonText == null)
			{
				if (CloseReason != 0)
				{
					return new byte[2]
					{
						(byte)((int)CloseReason >> 8),
						(byte)(CloseReason & (WebSocketCloseCode)255)
					};
				}
				return MiscUtils.EmptyArray<byte>();
			}
			byte[] array = new byte[Encoding.UTF8.GetByteCount(CloseReasonText) + 2];
			array[0] = (byte)((int)CloseReason >> 8);
			array[1] = (byte)(CloseReason & (WebSocketCloseCode)255);
			Encoding.UTF8.GetBytes(CloseReasonText, 0, CloseReasonText.Length, array, 2);
			return array;
		}
	}
	public abstract class WebSocketMessage
	{
		protected abstract WebSocketOpcode OpcodeToSend { get; }

		protected abstract void ReadData(byte[] payload);

		protected abstract byte[] GetPayload();

		internal WebSocketFrame ToFrame()
		{
			return new WebSocketFrame(OpcodeToSend, GetPayload());
		}

		internal static WebSocketMessage FromFrame(WebSocketFrame frame)
		{
			WebSocketMessage webSocketMessage;
			switch (frame.Opcode)
			{
			case WebSocketOpcode.Continuation:
				throw new Exception("How did we get here? Received continuation frame?");
			case WebSocketOpcode.Text:
				webSocketMessage = new WebSocketTextMessage();
				break;
			case WebSocketOpcode.Binary:
				webSocketMessage = new WebSocketBinaryMessage();
				break;
			case WebSocketOpcode.Close:
				webSocketMessage = new WebSocketCloseMessage();
				break;
			case WebSocketOpcode.Ping:
				webSocketMessage = new WebSocketPingMessage();
				break;
			case WebSocketOpcode.Pong:
				webSocketMessage = new WebSocketPongMessage();
				break;
			case WebSocketOpcode.ReservedData3:
			case WebSocketOpcode.ReservedData4:
			case WebSocketOpcode.ReservedData5:
			case WebSocketOpcode.ReservedData6:
			case WebSocketOpcode.ReservedData7:
			case WebSocketOpcode.ReservedControlB:
			case WebSocketOpcode.ReservedControlC:
			case WebSocketOpcode.ReservedControlD:
			case WebSocketOpcode.ReservedControlE:
				throw new WebSocketProtocolException($"Received frame with reserved opcode {frame.Opcode}");
			default:
				throw new ArgumentOutOfRangeException("Opcode", "Unknown opcode");
			}
			webSocketMessage.ReadData(frame.Payload);
			return webSocketMessage;
		}
	}
	public class WebSocketPingMessage : WebSocketMessage
	{
		public byte[] PingPayload { get; private set; }

		protected override WebSocketOpcode OpcodeToSend => WebSocketOpcode.Ping;

		public WebSocketPingMessage()
			: this(MiscUtils.EmptyArray<byte>())
		{
		}

		public WebSocketPingMessage(string payload)
			: this(Encoding.UTF8.GetBytes(payload))
		{
		}

		public WebSocketPingMessage(byte[] payload)
		{
			if (payload.Length > 125)
			{
				throw new ArgumentException("Ping payload must be at most 125 bytes", "payload");
			}
			PingPayload = payload;
		}

		protected override void ReadData(byte[] payload)
		{
			PingPayload = payload;
		}

		protected override byte[] GetPayload()
		{
			return PingPayload;
		}
	}
	public class WebSocketPongMessage : WebSocketMessage
	{
		public byte[] PongPayload { get; private set; }

		protected override WebSocketOpcode OpcodeToSend => WebSocketOpcode.Pong;

		public WebSocketPongMessage(byte[] pongPayload)
		{
			PongPayload = pongPayload;
		}

		internal WebSocketPongMessage()
		{
			PongPayload = MiscUtils.EmptyArray<byte>();
		}

		protected override void ReadData(byte[] payload)
		{
			PongPayload = payload;
		}

		protected override byte[] GetPayload()
		{
			return PongPayload;
		}
	}
	public class WebSocketTextMessage : WebSocketMessage
	{
		public string Text { get; private set; }

		protected override WebSocketOpcode OpcodeToSend => WebSocketOpcode.Text;

		public WebSocketTextMessage(string text)
		{
			Text = text;
		}

		internal WebSocketTextMessage()
		{
			Text = "Incoming message not decoded yet.";
		}

		protected override void ReadData(byte[] payload)
		{
			Text = Encoding.UTF8.GetString(payload);
		}

		protected override byte[] GetPayload()
		{
			return Encoding.UTF8.GetBytes(Text);
		}
	}
}
namespace WebSocketDotNet.Http
{
	internal class EncryptedNetworkStreamProvider : RawTcpNetworkStreamProvider
	{
		public EncryptedNetworkStreamProvider(string host, int port)
			: base(host, port)
		{
		}

		public override Stream GetStream()
		{
			SslStream sslStream = new SslStream(base.GetStream(), leaveInnerStreamOpen: false);
			sslStream.AuthenticateAsClient(base.Host);
			return sslStream;
		}
	}
	internal class HttpHandler
	{
		private Uri _uri;

		private NetworkStreamProvider _underlyingClient;

		private Stream? _stream;

		public bool AnyDataAvailable => _underlyingClient.AnythingToRead;

		public Stream GetOrOpenStream()
		{
			return _stream ?? (_stream = _underlyingClient.GetStream());
		}

		public void CloseAnyExistingStream()
		{
			_stream?.Close();
			_stream = null;
		}

		public HttpHandler(Uri uri)
		{
			_uri = uri;
			_underlyingClient = ((_uri.Scheme == "wss") ? new EncryptedNetworkStreamProvider(uri.DnsSafeHost, uri.Port) : new RawTcpNetworkStreamProvider(uri.DnsSafeHost, uri.Port));
		}

		public HttpResponse SendRequestWithHeaders(Dictionary<string, string> headers)
		{
			AddRequiredHeaders(headers);
			Stream orOpenStream = GetOrOpenStream();
			Extensions.Write(orOpenStream, GetRequestBytes(headers));
			_underlyingClient.WaitForData();
			return HttpResponse.Parse(orOpenStream.ReadToEnd(_underlyingClient));
		}

		private byte[] GetRequestBytes(Dictionary<string, string> headers)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(BuildProtocolLine()).Append("\r\n");
			foreach (KeyValuePair<string, string> header in headers)
			{
				stringBuilder.Append(BuildHeaderLine(header)).Append("\r\n");
			}
			stringBuilder.Append("\r\n");
			string s = stringBuilder.ToString();
			return Encoding.UTF8.GetBytes(s);
		}

		private void AddRequiredHeaders(Dictionary<string, string> headers)
		{
			if (!headers.ContainsKey("User-Agent"))
			{
				headers.Add("User-Agent", $"{AssemblyInfo.Name}/{AssemblyInfo.Version}");
			}
			headers["Host"] = _uri.Host;
		}

		private string BuildProtocolLine()
		{
			return "GET " + _uri.PathAndQuery + " HTTP/1.1";
		}

		private string BuildHeaderLine(KeyValuePair<string, string> header)
		{
			if (!header.Key.Contains(":"))
			{
				return header.Key + ": " + header.Value;
			}
			throw new Exception("Invalid HTTP Header " + header.Key);
		}
	}
	internal class HttpResponse
	{
		public HttpStatusCode StatusCode { get; }

		public string StatusDescription { get; }

		public Dictionary<string, string> Headers { get; }

		private HttpResponse(HttpStatusCode statusCode, string statusDescription, Dictionary<string, string> headers)
		{
			StatusCode = statusCode;
			StatusDescription = statusDescription;
			Headers = headers;
		}

		public static HttpResponse Parse(byte[] resultBytes)
		{
			string @string = Encoding.UTF8.GetString(resultBytes);
			if (!@string.StartsWith("HTTP/1.1"))
			{
				throw new Exception("Invalid response from server - not a HTTP/1.1 response");
			}
			string[] array = @string.Split(new string[1] { "\r\n" }, StringSplitOptions.None);
			string text = array[0];
			string text2 = text.Substring(9, text.Length - 9);
			int num = text2.IndexOf(' ');
			int statusCode = int.Parse(text2.Substring(0, num));
			text = text2;
			int num2 = num + 1;
			string statusDescription = text.Substring(num2, text.Length - num2);
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			for (int i = 1; i < array.Length; i++)
			{
				string text3 = array[i];
				if (text3.Length == 0)
				{
					break;
				}
				int num3 = text3.IndexOf(':');
				string key = text3.Substring(0, num3);
				text = text3;
				num2 = num3 + 2;
				string value = text.Substring(num2, text.Length - num2);
				dictionary.Add(key, value);
			}
			return new HttpResponse((HttpStatusCode)statusCode, statusDescription, dictionary);
		}
	}
	internal abstract class NetworkStreamProvider
	{
		private const int WaitIntervalMs = 10;

		protected string Host { get; }

		protected int Port { get; }

		public abstract bool AnythingToRead { get; }

		protected NetworkStreamProvider(string host, int port)
		{
			Host = host;
			Port = port;
		}

		public abstract Stream GetStream();

		public void WaitForData(int timeout = 5000)
		{
			int num = 0;
			while (!AnythingToRead)
			{
				if ((num += 10) > timeout)
				{
					throw new Exception("Timeout waiting for response to initial handshake");
				}
				Thread.Sleep(10);
			}
		}
	}
	internal class RawTcpNetworkStreamProvider : NetworkStreamProvider
	{
		private TcpClient? _client;

		private NetworkStream? _lastStream;

		public override bool AnythingToRead => _lastStream?.DataAvailable ?? false;

		public virtual bool IsClosed => false;

		public RawTcpNetworkStreamProvider(string host, int port)
			: base(host, port)
		{
		}

		private void ResetClient()
		{
			_client?.Close();
			_client = new TcpClient();
			_lastStream = null;
		}

		public override Stream GetStream()
		{
			ResetClient();
			_client.Connect(base.Host, base.Port);
			return _lastStream = _client.GetStream();
		}
	}
}

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/Demeo.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using Boardgame.Modding;
using HarmonyLib;
using MelonLoader;
using MelonLoader.Modules;
using Prototyping;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("MelonLoader")]
[assembly: AssemblyDescription("MelonLoader")]
[assembly: AssemblyCompany("discord.gg/2Wn3N2P")]
[assembly: AssemblyProduct("MelonLoader")]
[assembly: AssemblyCopyright("Created by Lava Gang")]
[assembly: AssemblyTrademark("discord.gg/2Wn3N2P")]
[assembly: Guid("FEAA0159-5871-4419-9827-3CF5CAD69A53")]
[assembly: AssemblyFileVersion("0.5.7")]
[assembly: PatchShield]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.5.7.0")]
[module: UnverifiableCode]
namespace MelonLoader
{
	[AttributeUsage(AttributeTargets.Assembly)]
	public class Demeo_LobbyRequirement : Attribute
	{
	}
}
namespace MelonLoader.CompatibilityLayers
{
	internal static class Extensions
	{
		private static FieldInfo name_field;

		private static MethodInfo name_get_method;

		private static MethodInfo name_set_method;

		private static FieldInfo version_field;

		private static MethodInfo version_method;

		private static FieldInfo author_field;

		private static MethodInfo author_method;

		private static FieldInfo description_field;

		private static MethodInfo description_method;

		private static FieldInfo isNetworkCompatible_field;

		private static MethodInfo isNetworkCompatible_method;

		internal static string GetName(this ModInformation info)
		{
			if (MelonUtils.IsGameIl2Cpp())
			{
				if (name_get_method == null)
				{
					name_get_method = AccessTools.Property(typeof(ModInformation), "name").GetGetMethod();
				}
				if (name_get_method != null)
				{
					return (string)name_get_method.Invoke(info, new object[0]);
				}
			}
			else
			{
				if (name_field == null)
				{
					name_field = AccessTools.Field(typeof(ModInformation), "name");
				}
				if (name_field != null)
				{
					return (string)name_field.GetValue(info);
				}
			}
			return null;
		}

		internal static void SetName(this ModInformation info, string name)
		{
			if (MelonUtils.IsGameIl2Cpp())
			{
				if (name_set_method == null)
				{
					name_set_method = AccessTools.Property(typeof(ModInformation), "name").GetSetMethod();
				}
				if (name_set_method != null)
				{
					name_set_method.Invoke(info, new object[1] { name });
				}
			}
			else
			{
				if (name_field == null)
				{
					name_field = AccessTools.Field(typeof(ModInformation), "name");
				}
				if (name_field != null)
				{
					name_field.SetValue(info, name);
				}
			}
		}

		internal static string GetVersion(this ModInformation info)
		{
			if (MelonUtils.IsGameIl2Cpp())
			{
				if (version_method == null)
				{
					version_method = AccessTools.Property(typeof(ModInformation), "version").GetGetMethod();
				}
				if (version_method != null)
				{
					return (string)version_method.Invoke(info, new object[0]);
				}
			}
			else
			{
				if (version_field == null)
				{
					version_field = AccessTools.Field(typeof(ModInformation), "version");
				}
				if (version_field != null)
				{
					return (string)version_field.GetValue(info);
				}
			}
			return null;
		}

		internal static void SetVersion(this ModInformation info, string version)
		{
			if (MelonUtils.IsGameIl2Cpp())
			{
				if (version_method == null)
				{
					version_method = AccessTools.Property(typeof(ModInformation), "version").GetSetMethod();
				}
				if (version_method != null)
				{
					version_method.Invoke(info, new object[1] { version });
				}
			}
			else
			{
				if (version_field == null)
				{
					version_field = AccessTools.Field(typeof(ModInformation), "version");
				}
				if (version_field != null)
				{
					version_field.SetValue(info, version);
				}
			}
		}

		internal static string GetAuthor(this ModInformation info)
		{
			if (MelonUtils.IsGameIl2Cpp())
			{
				if (author_method == null)
				{
					author_method = AccessTools.Property(typeof(ModInformation), "author").GetGetMethod();
				}
				if (author_method != null)
				{
					return (string)author_method.Invoke(info, new object[0]);
				}
			}
			else
			{
				if (author_field == null)
				{
					author_field = AccessTools.Field(typeof(ModInformation), "author");
				}
				if (author_field != null)
				{
					return (string)author_field.GetValue(info);
				}
			}
			return null;
		}

		internal static void SetAuthor(this ModInformation info, string author)
		{
			if (MelonUtils.IsGameIl2Cpp())
			{
				if (author_method == null)
				{
					author_method = AccessTools.Property(typeof(ModInformation), "author").GetSetMethod();
				}
				if (author_method != null)
				{
					author_method.Invoke(info, new object[1] { author });
				}
			}
			else
			{
				if (author_field == null)
				{
					author_field = AccessTools.Field(typeof(ModInformation), "author");
				}
				if (author_field != null)
				{
					author_field.SetValue(info, author);
				}
			}
		}

		internal static void SetDescription(this ModInformation info, string description)
		{
			if (MelonUtils.IsGameIl2Cpp())
			{
				if (description_method == null)
				{
					description_method = AccessTools.Property(typeof(ModInformation), "description").GetSetMethod();
				}
				if (description_method != null)
				{
					description_method.Invoke(info, new object[1] { description });
				}
			}
			else
			{
				if (description_field == null)
				{
					description_field = AccessTools.Field(typeof(ModInformation), "description");
				}
				if (description_field != null)
				{
					description_field.SetValue(info, description);
				}
			}
		}

		internal static void SetIsNetworkCompatible(this ModInformation info, bool isNetworkCompatible)
		{
			if (MelonUtils.IsGameIl2Cpp())
			{
				if (isNetworkCompatible_method == null)
				{
					isNetworkCompatible_method = AccessTools.Property(typeof(ModInformation), "isNetworkCompatible").GetSetMethod();
				}
				if (isNetworkCompatible_method != null)
				{
					isNetworkCompatible_method.Invoke(info, new object[1] { isNetworkCompatible });
				}
			}
			else
			{
				if (isNetworkCompatible_field == null)
				{
					isNetworkCompatible_field = AccessTools.Field(typeof(ModInformation), "isNetworkCompatible");
				}
				if (isNetworkCompatible_field != null)
				{
					isNetworkCompatible_field.SetValue(info, isNetworkCompatible);
				}
			}
		}
	}
	internal class Demeo_Module : MelonModule
	{
		private static Dictionary<MelonBase, ModInformation> ModInformation = new Dictionary<MelonBase, ModInformation>();

		public override void OnInitialize()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			((MelonEventBase<LemonAction>)(object)MelonEvents.OnApplicationStart).Subscribe(new LemonAction(OnPreAppStart), int.MaxValue, false);
			((MelonEventBase<LemonAction<MelonBase>>)(object)MelonBase.OnMelonRegistered).Subscribe((LemonAction<MelonBase>)ParseMelon<MelonBase>, int.MaxValue, false);
			((MelonEventBase<LemonAction<MelonBase>>)(object)MelonBase.OnMelonUnregistered).Subscribe((LemonAction<MelonBase>)OnUnregister, int.MaxValue, false);
		}

		private static void OnPreAppStart()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			new Harmony("DemeoIntegration").Patch((MethodBase)Assembly.Load("Assembly-CSharp").GetType("Prototyping.RG").GetMethod("Initialize", BindingFlags.Static | BindingFlags.Public), MelonUtils.ToNewHarmonyMethod(typeof(Demeo_Module).GetMethod("InitFix", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			foreach (MelonPlugin registeredMelon in MelonTypeBase<MelonPlugin>.RegisteredMelons)
			{
				ParseMelon<MelonPlugin>(registeredMelon);
			}
			foreach (MelonMod registeredMelon2 in MelonTypeBase<MelonMod>.RegisteredMelons)
			{
				ParseMelon<MelonMod>(registeredMelon2);
			}
		}

		private static void OnUnregister(MelonBase melon)
		{
			if (melon != null && ModInformation.ContainsKey(melon))
			{
				ModInformation.Remove(melon);
				if (ModdingAPI.ExternallyInstalledMods == null)
				{
					ModdingAPI.ExternallyInstalledMods = new List<ModInformation>();
				}
				else
				{
					ModdingAPI.ExternallyInstalledMods.Remove(ModInformation[melon]);
				}
			}
		}

		private static void ParseMelon<T>(T melon) where T : MelonBase
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			if (melon != null && !ModInformation.ContainsKey((MelonBase)(object)melon))
			{
				ModInformation val = new ModInformation();
				val.SetName(((MelonBase)melon).Info.Name);
				val.SetVersion(((MelonBase)melon).Info.Version);
				val.SetAuthor(((MelonBase)melon).Info.Author);
				val.SetDescription(((MelonBase)melon).Info.DownloadLink);
				val.SetIsNetworkCompatible(MelonUtils.PullAttributeFromAssembly<Demeo_LobbyRequirement>(((MelonBase)melon).MelonAssembly.Assembly, false) == null);
				ModInformation.Add((MelonBase)(object)melon, val);
				if (ModdingAPI.ExternallyInstalledMods == null)
				{
					ModdingAPI.ExternallyInstalledMods = new List<ModInformation>();
				}
				ModdingAPI.ExternallyInstalledMods.Add(val);
			}
		}

		private static bool InitFix()
		{
			if (MotherbrainGlobalVars.IsRunningOnDesktop)
			{
				RG.SetVrMode(false);
			}
			else
			{
				RG.SetVrMode(RG.XRDeviceIsPresent());
			}
			return true;
		}
	}
}

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/IPA.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using IllusionInjector;
using IllusionPlugin;
using MelonLoader;
using MelonLoader.Modules;
using MelonLoader.MonoInternals;
using MelonLoader.Preferences;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("MelonLoader")]
[assembly: AssemblyDescription("MelonLoader")]
[assembly: AssemblyCompany("discord.gg/2Wn3N2P")]
[assembly: AssemblyProduct("MelonLoader")]
[assembly: AssemblyCopyright("Created by Lava Gang")]
[assembly: AssemblyTrademark("discord.gg/2Wn3N2P")]
[assembly: Guid("5100810A-9842-4073-9658-E5841FDF9D73")]
[assembly: AssemblyFileVersion("0.5.7")]
[assembly: PatchShield]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.5.7.0")]
[module: UnverifiableCode]
namespace IllusionInjector
{
	public static class PluginManager
	{
		public class AppInfo
		{
			public static string StartupPath => MelonUtils.GameDirectory;
		}

		internal static List<IPlugin> _Plugins = new List<IPlugin>();

		public static IEnumerable<IPlugin> Plugins => _Plugins;
	}
}
namespace IllusionPlugin
{
	public interface IEnhancedPlugin : IPlugin
	{
		string[] Filter { get; }

		void OnLateUpdate();
	}
	public interface IPlugin
	{
		string Name { get; }

		string Version { get; }

		void OnApplicationStart();

		void OnApplicationQuit();

		void OnLevelWasLoaded(int level);

		void OnLevelWasInitialized(int level);

		void OnUpdate();

		void OnFixedUpdate();
	}
	public static class ModPrefs
	{
		public static string GetString(string section, string name, string defaultValue = "", bool autoSave = false)
		{
			MelonPreferences_Category val = MelonPreferences.GetCategory(section);
			if (val == null)
			{
				val = MelonPreferences.CreateCategory(section);
			}
			MelonPreferences_Entry<string> val2 = val.GetEntry<string>(name);
			if (val2 == null)
			{
				val2 = val.CreateEntry<string>(name, defaultValue, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			}
			return val2.Value;
		}

		public static int GetInt(string section, string name, int defaultValue = 0, bool autoSave = false)
		{
			MelonPreferences_Category val = MelonPreferences.GetCategory(section);
			if (val == null)
			{
				val = MelonPreferences.CreateCategory(section);
			}
			MelonPreferences_Entry<int> val2 = val.GetEntry<int>(name);
			if (val2 == null)
			{
				val2 = val.CreateEntry<int>(name, defaultValue, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			}
			return val2.Value;
		}

		public static float GetFloat(string section, string name, float defaultValue = 0f, bool autoSave = false)
		{
			MelonPreferences_Category val = MelonPreferences.GetCategory(section);
			if (val == null)
			{
				val = MelonPreferences.CreateCategory(section);
			}
			MelonPreferences_Entry<float> val2 = val.GetEntry<float>(name);
			if (val2 == null)
			{
				val2 = val.CreateEntry<float>(name, defaultValue, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			}
			return val2.Value;
		}

		public static bool GetBool(string section, string name, bool defaultValue = false, bool autoSave = false)
		{
			MelonPreferences_Category val = MelonPreferences.GetCategory(section);
			if (val == null)
			{
				val = MelonPreferences.CreateCategory(section);
			}
			MelonPreferences_Entry<bool> val2 = val.GetEntry<bool>(name);
			if (val2 == null)
			{
				val2 = val.CreateEntry<bool>(name, defaultValue, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			}
			return val2.Value;
		}

		public static bool HasKey(string section, string name)
		{
			return MelonPreferences.HasEntry(section, name);
		}

		public static void SetFloat(string section, string name, float value)
		{
			MelonPreferences_Category val = MelonPreferences.GetCategory(section);
			if (val == null)
			{
				val = MelonPreferences.CreateCategory(section);
			}
			MelonPreferences_Entry<float> val2 = val.GetEntry<float>(name);
			if (val2 == null)
			{
				val2 = val.CreateEntry<float>(name, value, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			}
			val2.Value = value;
		}

		public static void SetInt(string section, string name, int value)
		{
			MelonPreferences_Category val = MelonPreferences.GetCategory(section);
			if (val == null)
			{
				val = MelonPreferences.CreateCategory(section);
			}
			MelonPreferences_Entry<int> val2 = val.GetEntry<int>(name);
			if (val2 == null)
			{
				val2 = val.CreateEntry<int>(name, value, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			}
			val2.Value = value;
		}

		public static void SetString(string section, string name, string value)
		{
			MelonPreferences_Category val = MelonPreferences.GetCategory(section);
			if (val == null)
			{
				val = MelonPreferences.CreateCategory(section);
			}
			MelonPreferences_Entry<string> val2 = val.GetEntry<string>(name);
			if (val2 == null)
			{
				val2 = val.CreateEntry<string>(name, value, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			}
			val2.Value = value;
		}

		public static void SetBool(string section, string name, bool value)
		{
			MelonPreferences_Category val = MelonPreferences.GetCategory(section);
			if (val == null)
			{
				val = MelonPreferences.CreateCategory(section);
			}
			MelonPreferences_Entry<bool> val2 = val.GetEntry<bool>(name);
			if (val2 == null)
			{
				val2 = val.CreateEntry<bool>(name, value, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
			}
			val2.Value = value;
		}
	}
}
namespace MelonLoader.CompatibilityLayers
{
	internal class IPAPluginWrapper : MelonMod
	{
		internal IPlugin pluginInstance;

		public override void OnInitializeMelon()
		{
			pluginInstance.OnApplicationStart();
		}

		public override void OnDeinitializeMelon()
		{
			pluginInstance.OnApplicationQuit();
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			pluginInstance.OnLevelWasLoaded(buildIndex);
		}

		public override void OnSceneWasInitialized(int buildIndex, string sceneName)
		{
			pluginInstance.OnLevelWasInitialized(buildIndex);
		}

		public override void OnUpdate()
		{
			pluginInstance.OnUpdate();
		}

		public override void OnFixedUpdate()
		{
			pluginInstance.OnFixedUpdate();
		}

		public override void OnLateUpdate()
		{
			if (pluginInstance is IEnhancedPlugin enhancedPlugin)
			{
				enhancedPlugin.OnLateUpdate();
			}
		}
	}
	internal class IPA_Module : MelonModule
	{
		public override void OnInitialize()
		{
			string[] obj = new string[2] { "IllusionPlugin", "IllusionInjector" };
			Assembly assembly = typeof(IPA_Module).Assembly;
			string[] array = obj;
			for (int i = 0; i < array.Length; i++)
			{
				MonoResolveManager.GetAssemblyResolveInfo(array[i]).Override = assembly;
			}
			MelonAssembly.CustomMelonResolvers += Resolve;
		}

		private ResolvedMelons Resolve(Assembly asm)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			IEnumerable<Type> validTypes = MelonUtils.GetValidTypes(asm, (LemonFunc<Type, bool>)delegate(Type x)
			{
				Type[] interfaces = x.GetInterfaces();
				return interfaces != null && interfaces.Any() && interfaces.Contains(typeof(IPlugin));
			});
			if (validTypes != null && validTypes.Any())
			{
				List<MelonBase> list = new List<MelonBase>();
				List<RottenMelon> list2 = new List<RottenMelon>();
				foreach (Type item in validTypes)
				{
					RottenMelon rottenMelon;
					MelonBase val = LoadPlugin(asm, item, out rottenMelon);
					if (val != null)
					{
						list.Add(val);
					}
					else
					{
						list2.Add(rottenMelon);
					}
				}
				return new ResolvedMelons(list.ToArray(), list2.ToArray());
			}
			return new ResolvedMelons((MelonBase[])null, (RottenMelon[])null);
		}

		private MelonBase LoadPlugin(Assembly asm, Type pluginType, out RottenMelon rottenMelon)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			rottenMelon = null;
			IPlugin plugin;
			try
			{
				plugin = Activator.CreateInstance(pluginType) as IPlugin;
			}
			catch (Exception ex)
			{
				rottenMelon = new RottenMelon(pluginType, "Failed to create a new instance of the IPA Plugin.", ex);
				return null;
			}
			MelonProcessAttribute[] array = null;
			if (plugin is IEnhancedPlugin enhancedPlugin)
			{
				array = enhancedPlugin.Filter?.Select((Func<string, MelonProcessAttribute>)((string x) => new MelonProcessAttribute(x))).ToArray();
			}
			string text = plugin.Name;
			if (string.IsNullOrEmpty(text))
			{
				text = pluginType.FullName;
			}
			string text2 = plugin.Version;
			if (string.IsNullOrEmpty(text2))
			{
				text2 = asm.GetName().Version.ToString();
			}
			if (string.IsNullOrEmpty(text2) || text2.Equals("0.0.0.0"))
			{
				text2 = "1.0.0.0";
			}
			IPAPluginWrapper iPAPluginWrapper = MelonBase.CreateWrapper<IPAPluginWrapper>(text, (string)null, text2, (MelonGameAttribute[])null, array, 0, (ConsoleColor?)null, (ConsoleColor?)null, (string)null);
			iPAPluginWrapper.pluginInstance = plugin;
			PluginManager._Plugins.Add(plugin);
			return (MelonBase)(object)iPAPluginWrapper;
		}
	}
}

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/MelonStartScreen.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.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using AssetRipper.VersionUtilities;
using Il2CppSystem;
using MelonLoader;
using MelonLoader.InternalUtils;
using MelonLoader.MelonStartScreen.NativeUtils;
using MelonLoader.MelonStartScreen.Properties;
using MelonLoader.MelonStartScreen.UI;
using MelonLoader.MelonStartScreen.UI.Objects;
using MelonLoader.MelonStartScreen.UI.Themes;
using MelonLoader.Modules;
using MelonLoader.NativeUtils;
using MelonLoader.NativeUtils.PEParser;
using MelonLoader.Preferences;
using MelonUnityEngine;
using MelonUnityEngine.CoreModule;
using MelonUnityEngine.Rendering;
using Tomlet;
using Tomlet.Attributes;
using Tomlet.Models;
using UnhollowerMini;
using UnityPlayer;
using Windows;
using mgGif;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("MelonLoader")]
[assembly: AssemblyDescription("MelonLoader")]
[assembly: AssemblyCompany("discord.gg/2Wn3N2P")]
[assembly: AssemblyProduct("MelonLoader")]
[assembly: AssemblyCopyright("Created by Lava Gang")]
[assembly: AssemblyTrademark("discord.gg/2Wn3N2P")]
[assembly: Guid("762d7545-6f6b-441a-b040-49cc31a1713b")]
[assembly: AssemblyFileVersion("0.5.7")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.5.7.0")]
[module: UnverifiableCode]
namespace Windows
{
	[StructLayout(LayoutKind.Sequential)]
	internal class DropFile
	{
		private uint pFiles = 14u;

		public Point pt;

		public bool fNC;

		private bool fWide = true;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 300)]
		public string file = "";
	}
	internal struct Msg
	{
		public IntPtr hwnd;

		public WindowMessage message;

		public IntPtr wParam;

		public IntPtr lParam;

		public uint time;

		public Point pt;
	}
	internal struct Point
	{
		public int x;

		public int y;
	}
	internal static class User32
	{
		public delegate void TimerProc(IntPtr hWnd, uint uMsg, IntPtr nIDEvent, uint dwTime);

		[DllImport("user32.dll")]
		public static extern bool PeekMessage(out Msg lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);

		[DllImport("user32.dll")]
		public static extern bool TranslateMessage([In] ref Msg lpMsg);

		[DllImport("user32.dll")]
		public static extern IntPtr DispatchMessage([In] ref Msg lpmsg);

		[DllImport("user32.dll")]
		public static extern IntPtr GetMessageExtraInfo();

		[DllImport("user32.dll", ExactSpelling = true)]
		public static extern IntPtr SetTimer(IntPtr hWnd, IntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);

		[DllImport("user32.dll", ExactSpelling = true)]
		public static extern bool KillTimer(IntPtr hWnd, IntPtr uIDEvent);

		[DllImport("user32.dll")]
		public static extern IntPtr SetClipboardData(uint uFormat, ref DropFile hMem);
	}
	internal enum WindowMessage : uint
	{
		NULL = 0u,
		CREATE = 1u,
		DESTROY = 2u,
		MOVE = 3u,
		SIZE = 5u,
		ACTIVATE = 6u,
		SETFOCUS = 7u,
		KILLFOCUS = 8u,
		ENABLE = 10u,
		SETREDRAW = 11u,
		SETTEXT = 12u,
		GETTEXT = 13u,
		GETTEXTLENGTH = 14u,
		PAINT = 15u,
		CLOSE = 16u,
		QUERYENDSESSION = 17u,
		QUERYOPEN = 19u,
		ENDSESSION = 22u,
		QUIT = 18u,
		ERASEBKGND = 20u,
		SYSCOLORCHANGE = 21u,
		SHOWWINDOW = 24u,
		WININICHANGE = 26u,
		SETTINGCHANGE = 26u,
		DEVMODECHANGE = 27u,
		ACTIVATEAPP = 28u,
		FONTCHANGE = 29u,
		TIMECHANGE = 30u,
		CANCELMODE = 31u,
		SETCURSOR = 32u,
		MOUSEACTIVATE = 33u,
		CHILDACTIVATE = 34u,
		QUEUESYNC = 35u,
		GETMINMAXINFO = 36u,
		PAINTICON = 38u,
		ICONERASEBKGND = 39u,
		NEXTDLGCTL = 40u,
		SPOOLERSTATUS = 42u,
		DRAWITEM = 43u,
		MEASUREITEM = 44u,
		DELETEITEM = 45u,
		VKEYTOITEM = 46u,
		CHARTOITEM = 47u,
		SETFONT = 48u,
		GETFONT = 49u,
		SETHOTKEY = 50u,
		GETHOTKEY = 51u,
		QUERYDRAGICON = 55u,
		COMPAREITEM = 57u,
		GETOBJECT = 61u,
		COMPACTING = 65u,
		[Obsolete]
		COMMNOTIFY = 68u,
		WINDOWPOSCHANGING = 70u,
		WINDOWPOSCHANGED = 71u,
		[Obsolete]
		POWER = 72u,
		COPYDATA = 74u,
		CANCELJOURNAL = 75u,
		NOTIFY = 78u,
		INPUTLANGCHANGEREQUEST = 80u,
		INPUTLANGCHANGE = 81u,
		TCARD = 82u,
		HELP = 83u,
		USERCHANGED = 84u,
		NOTIFYFORMAT = 85u,
		CONTEXTMENU = 123u,
		STYLECHANGING = 124u,
		STYLECHANGED = 125u,
		DISPLAYCHANGE = 126u,
		GETICON = 127u,
		SETICON = 128u,
		NCCREATE = 129u,
		NCDESTROY = 130u,
		NCCALCSIZE = 131u,
		NCHITTEST = 132u,
		NCPAINT = 133u,
		NCACTIVATE = 134u,
		GETDLGCODE = 135u,
		SYNCPAINT = 136u,
		NCMOUSEMOVE = 160u,
		NCLBUTTONDOWN = 161u,
		NCLBUTTONUP = 162u,
		NCLBUTTONDBLCLK = 163u,
		NCRBUTTONDOWN = 164u,
		NCRBUTTONUP = 165u,
		NCRBUTTONDBLCLK = 166u,
		NCMBUTTONDOWN = 167u,
		NCMBUTTONUP = 168u,
		NCMBUTTONDBLCLK = 169u,
		NCXBUTTONDOWN = 171u,
		NCXBUTTONUP = 172u,
		NCXBUTTONDBLCLK = 173u,
		INPUT_DEVICE_CHANGE = 254u,
		INPUT = 255u,
		KEYFIRST = 256u,
		KEYDOWN = 256u,
		KEYUP = 257u,
		CHAR = 258u,
		DEADCHAR = 259u,
		SYSKEYDOWN = 260u,
		SYSKEYUP = 261u,
		SYSCHAR = 262u,
		SYSDEADCHAR = 263u,
		UNICHAR = 265u,
		KEYLAST = 264u,
		IME_STARTCOMPOSITION = 269u,
		IME_ENDCOMPOSITION = 270u,
		IME_COMPOSITION = 271u,
		IME_KEYLAST = 271u,
		INITDIALOG = 272u,
		COMMAND = 273u,
		SYSCOMMAND = 274u,
		TIMER = 275u,
		HSCROLL = 276u,
		VSCROLL = 277u,
		INITMENU = 278u,
		INITMENUPOPUP = 279u,
		MENUSELECT = 287u,
		MENUCHAR = 288u,
		ENTERIDLE = 289u,
		MENURBUTTONUP = 290u,
		MENUDRAG = 291u,
		MENUGETOBJECT = 292u,
		UNINITMENUPOPUP = 293u,
		MENUCOMMAND = 294u,
		CHANGEUISTATE = 295u,
		UPDATEUISTATE = 296u,
		QUERYUISTATE = 297u,
		CTLCOLORMSGBOX = 306u,
		CTLCOLOREDIT = 307u,
		CTLCOLORLISTBOX = 308u,
		CTLCOLORBTN = 309u,
		CTLCOLORDLG = 310u,
		CTLCOLORSCROLLBAR = 311u,
		CTLCOLORSTATIC = 312u,
		MOUSEFIRST = 512u,
		MOUSEMOVE = 512u,
		LBUTTONDOWN = 513u,
		LBUTTONUP = 514u,
		LBUTTONDBLCLK = 515u,
		RBUTTONDOWN = 516u,
		RBUTTONUP = 517u,
		RBUTTONDBLCLK = 518u,
		MBUTTONDOWN = 519u,
		MBUTTONUP = 520u,
		MBUTTONDBLCLK = 521u,
		MOUSEWHEEL = 522u,
		XBUTTONDOWN = 523u,
		XBUTTONUP = 524u,
		XBUTTONDBLCLK = 525u,
		MOUSEHWHEEL = 526u,
		MOUSELAST = 526u,
		PARENTNOTIFY = 528u,
		ENTERMENULOOP = 529u,
		EXITMENULOOP = 530u,
		NEXTMENU = 531u,
		SIZING = 532u,
		CAPTURECHANGED = 533u,
		MOVING = 534u,
		POWERBROADCAST = 536u,
		DEVICECHANGE = 537u,
		MDICREATE = 544u,
		MDIDESTROY = 545u,
		MDIACTIVATE = 546u,
		MDIRESTORE = 547u,
		MDINEXT = 548u,
		MDIMAXIMIZE = 549u,
		MDITILE = 550u,
		MDICASCADE = 551u,
		MDIICONARRANGE = 552u,
		MDIGETACTIVE = 553u,
		MDISETMENU = 560u,
		ENTERSIZEMOVE = 561u,
		EXITSIZEMOVE = 562u,
		DROPFILES = 563u,
		MDIREFRESHMENU = 564u,
		IME_SETCONTEXT = 641u,
		IME_NOTIFY = 642u,
		IME_CONTROL = 643u,
		IME_COMPOSITIONFULL = 644u,
		IME_SELECT = 645u,
		IME_CHAR = 646u,
		IME_REQUEST = 648u,
		IME_KEYDOWN = 656u,
		IME_KEYUP = 657u,
		MOUSEHOVER = 673u,
		MOUSELEAVE = 675u,
		NCMOUSEHOVER = 672u,
		NCMOUSELEAVE = 674u,
		WTSSESSION_CHANGE = 689u,
		TABLET_FIRST = 704u,
		TABLET_LAST = 735u,
		CUT = 768u,
		COPY = 769u,
		PASTE = 770u,
		CLEAR = 771u,
		UNDO = 772u,
		RENDERFORMAT = 773u,
		RENDERALLFORMATS = 774u,
		DESTROYCLIPBOARD = 775u,
		DRAWCLIPBOARD = 776u,
		PAINTCLIPBOARD = 777u,
		VSCROLLCLIPBOARD = 778u,
		SIZECLIPBOARD = 779u,
		ASKCBFORMATNAME = 780u,
		CHANGECBCHAIN = 781u,
		HSCROLLCLIPBOARD = 782u,
		QUERYNEWPALETTE = 783u,
		PALETTEISCHANGING = 784u,
		PALETTECHANGED = 785u,
		HOTKEY = 786u,
		PRINT = 791u,
		PRINTCLIENT = 792u,
		APPCOMMAND = 793u,
		THEMECHANGED = 794u,
		CLIPBOARDUPDATE = 797u,
		DWMCOMPOSITIONCHANGED = 798u,
		DWMNCRENDERINGCHANGED = 799u,
		DWMCOLORIZATIONCOLORCHANGED = 800u,
		DWMWINDOWMAXIMIZEDCHANGE = 801u,
		GETTITLEBARINFOEX = 831u,
		HANDHELDFIRST = 856u,
		HANDHELDLAST = 863u,
		AFXFIRST = 864u,
		AFXLAST = 895u,
		PENWINFIRST = 896u,
		PENWINLAST = 911u,
		APP = 32768u,
		USER = 1024u,
		CPL_LAUNCH = 5120u,
		CPL_LAUNCHED = 5121u,
		SYSTIMER = 280u,
		HSHELL_ACCESSIBILITYSTATE = 11u,
		HSHELL_ACTIVATESHELLWINDOW = 3u,
		HSHELL_APPCOMMAND = 12u,
		HSHELL_GETMINRECT = 5u,
		HSHELL_LANGUAGE = 8u,
		HSHELL_REDRAW = 6u,
		HSHELL_TASKMAN = 7u,
		HSHELL_WINDOWCREATED = 1u,
		HSHELL_WINDOWDESTROYED = 2u,
		HSHELL_WINDOWACTIVATED = 4u,
		HSHELL_WINDOWREPLACED = 13u
	}
}
namespace UnityPlayer
{
	internal class GfxDevice
	{
		private delegate void PresentFrameDelegate();

		private delegate void WaitForLastPresentationAndGetTimestampDelegate(IntPtr gfxDevice);

		private delegate IntPtr GetRealGfxDeviceDelegate();

		[NativeSignature(1u, NativeSignatureFlags.X86, "e8 ?? ?? ?? ?? 85 c0 74 12 e8 ?? ?? ?? ?? 8b ?? 8b ?? 8b 42 70 ff d0 84 c0 75", new string[] { "2017.1.0", "5.6.0", "2017.1.0" })]
		[NativeSignature(2u, NativeSignatureFlags.X86, "55 8b ec 51 e8 ?? ?? ?? ?? 85 c0 74 12 e8 ?? ?? ?? ?? 8b c8 8b 10 8b 42 ?? ff d0 84 c0 75", new string[] { "2018.1.0" })]
		[NativeSignature(3u, NativeSignatureFlags.X86, "55 8b ec 51 e8 ?? ?? ?? ?? 85 c0 74 15 e8 ?? ?? ?? ?? 8b c8 8b 10 8b 82 ?? 00 00 00 ff d0", new string[] { "2018.4.9", "2019.1.0" })]
		[NativeSignature(4u, NativeSignatureFlags.X86, "55 8b ec 51 56 e8 ?? ?? ?? ?? 8b f0 8b ce e8 ?? ?? ?? ?? e8 ?? ?? ?? ?? 85 c0 74 ?? e8", new string[] { "2018.4.18", "2019.3.0", "2020.1.0" })]
		[NativeSignature(1u, NativeSignatureFlags.X64, "48 83 ec 28 e8 ?? ?? ?? ?? 48 85 c0 74 15 e8 ?? ?? ?? ?? 48 8b c8 48 8b 10 ff 92 e0 00 00 00 84 c0", new string[] { "5.6.0", "2017.1.0" })]
		[NativeSignature(2u, NativeSignatureFlags.X64, "48 83 ec 28 e8 ?? ?? ?? ?? 48 85 c0 74 15 e8 ?? ?? ?? ?? 48 8b c8 48 8b 10 ff 92 ?? ?? 00 00 84 c0", new string[] { "2018.3.0", "2019.1.0" })]
		[NativeSignature(3u, NativeSignatureFlags.X64, "40 53 48 83 ec 20 e8 ?? ?? ?? ?? 48 8b c8 48 8b d8 e8 ?? ?? ?? ?? e8 ?? ?? ?? ?? 48 85 c0 74", new string[] { "2018.4.18", "2019.3.0", "2020.1.0" })]
		private static PresentFrameDelegate m_PresentFrame;

		[NativeSignature(0u, NativeSignatureFlags.None, null, new string[] { "2017.1.0" })]
		[NativeSignature(1u, NativeSignatureFlags.X86, "55 8b ec 83 ec 40 53 56 8b d9 57 89 5d fc e8 ?? ?? ?? ?? 6a 02 8b c8", new string[] { "2020.2.7", "2020.3.0", "2021.1.0" })]
		[NativeSignature(2u, NativeSignatureFlags.X86, "55 8b ec 83 ec 48 53 56 8b d9 57 89 5d fc e8 ?? ?? ?? ?? 6a 02 8b c8", new string[] { "2021.1.5", "2021.2.0" })]
		[NativeSignature(3u, NativeSignatureFlags.X86, "55 8b ec 83 ec 58 53 56 8b d9 57 89 5d fc e8 ?? ?? ?? ?? 6a 02 8b c8", new string[] { "2022.1.0" })]
		[NativeSignature(4u, (NativeSignatureFlags)18, null, new string[] { "2020.3.9" })]
		[NativeSignature(1u, NativeSignatureFlags.X64, "48 89 5c 24 10 56 48 81 ec 90 00 00 00 0f 29 b4 24 80 00 00 00 48 8b f1", new string[] { "2020.2.7", "2020.3.0", "2021.1.0" })]
		[NativeSignature(2u, NativeSignatureFlags.X64, "48 89 5c 24 10 56 48 81 ec b0 00 00 00 0f 29 b4 24 a0 00 00 00 48 8b f1", new string[] { "2022.1.0" })]
		private static WaitForLastPresentationAndGetTimestampDelegate m_D3D11WaitForLastPresentationAndGetTimestamp;

		[NativeSignature(0u, NativeSignatureFlags.None, null, new string[] { "2017.1.0" })]
		[NativeSignature(1u, NativeSignatureFlags.X86, "55 8b ec 83 ec 40 53 56 57 8b f9 89 7d f4 e8 ?? ?? ?? ?? 6a 02 8b c8", new string[] { "2020.2.7", "2020.3.0", "2021.1.0" })]
		[NativeSignature(2u, NativeSignatureFlags.X86, "55 8b ec 83 ec 48 56 57 8b f9 89 7d f0 e8 ?? ?? ?? ?? 6a 02 8b c8", new string[] { "2020.3.9", "2021.1.5" })]
		[NativeSignature(3u, NativeSignatureFlags.X86, "55 8b ec 83 ec 48 56 57 8b f9 89 7d f8 e8 ?? ?? ?? ?? 6a 02 8b c8", new string[] { "2021.2.0" })]
		[NativeSignature(4u, NativeSignatureFlags.X86, "55 8b ec 83 ec 58 56 57 8b f9 89 7d f8 e8 ?? ?? ?? ?? 6a 02 8b c8", new string[] { "2022.1.0" })]
		[NativeSignature(1u, NativeSignatureFlags.X64, "48 89 5c 24 08 57 48 81 ec 90 00 00 00 0f 29 b4 24 80 00 00 00 48 8b d9", new string[] { "2020.2.7", "2020.3.0", "2021.1.0" })]
		[NativeSignature(2u, NativeSignatureFlags.X64, "48 89 5c 24 08 57 48 81 ec b0 00 00 00 0f 29 b4 24 a0 00 00 00 48 8b d9", new string[] { "2022.1.0" })]
		private static WaitForLastPresentationAndGetTimestampDelegate m_D3D12WaitForLastPresentationAndGetTimestamp;

		private static GetRealGfxDeviceDelegate m_GetRealGfxDevice;

		static GfxDevice()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			UnityVersion engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[3] { "2020.2.7", "2020.3.0", "2021.1.0" }))
			{
				m_GetRealGfxDevice = (GetRealGfxDeviceDelegate)Marshal.GetDelegateForFunctionPointer(CppUtils.ResolveRelativeInstruction((IntPtr)((long)UnityInternals.ResolveICall("UnityEngine.FrameTimingManager::CaptureFrameTimings") + ((!MelonUtils.IsGame32Bit()) ? 4 : 0))), typeof(GetRealGfxDeviceDelegate));
			}
		}

		public static void PresentFrame()
		{
			m_PresentFrame();
		}

		public static IntPtr GetRealGfxDevice()
		{
			return m_GetRealGfxDevice();
		}

		internal static void WaitForLastPresentationAndGetTimestamp(uint deviceType)
		{
			if (m_GetRealGfxDevice == null)
			{
				throw new NotImplementedException();
			}
			IntPtr realGfxDevice = GetRealGfxDevice();
			if (realGfxDevice == IntPtr.Zero)
			{
				throw new NotImplementedException();
			}
			switch (deviceType)
			{
			case 2u:
				if (m_D3D11WaitForLastPresentationAndGetTimestamp == null)
				{
					throw new NotImplementedException();
				}
				m_D3D11WaitForLastPresentationAndGetTimestamp(realGfxDevice);
				break;
			case 18u:
				if (m_D3D12WaitForLastPresentationAndGetTimestamp == null)
				{
					throw new NotImplementedException();
				}
				m_D3D12WaitForLastPresentationAndGetTimestamp(realGfxDevice);
				break;
			default:
				throw new NotImplementedException();
			}
		}
	}
}
namespace MelonUnityEngine
{
	[StructLayout(LayoutKind.Explicit)]
	internal struct Color
	{
		private static readonly IntPtr m_ToString;

		[FieldOffset(0)]
		public float r;

		[FieldOffset(4)]
		public float g;

		[FieldOffset(8)]
		public float b;

		[FieldOffset(12)]
		public float a;

		static Color()
		{
			InternalClassPointerStore<Color>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Color");
			UnityInternals.runtime_class_init(InternalClassPointerStore<Color>.NativeClassPtr);
			m_ToString = UnityInternals.GetMethod(InternalClassPointerStore<Color>.NativeClassPtr, "ToString", "System.String");
		}

		public Color(float r, float g, float b, float a = 1f)
		{
			this.r = r;
			this.g = g;
			this.b = b;
			this.a = a;
		}
	}
	[StructLayout(LayoutKind.Explicit)]
	internal struct Color32
	{
		[FieldOffset(0)]
		public byte r;

		[FieldOffset(1)]
		public byte g;

		[FieldOffset(2)]
		public byte b;

		[FieldOffset(3)]
		public byte a;

		[FieldOffset(0)]
		public int rgba;

		static Color32()
		{
			InternalClassPointerStore<Color32>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Color32");
			UnityInternals.runtime_class_init(InternalClassPointerStore<Color32>.NativeClassPtr);
		}

		public Color32(byte r, byte g, byte b, byte a)
		{
			rgba = 0;
			this.r = r;
			this.g = g;
			this.b = b;
			this.a = a;
		}

		public static implicit operator Color(Color32 c)
		{
			return new Color((float)(int)c.r / 255f, (float)(int)c.g / 255f, (float)(int)c.b / 255f, (float)(int)c.a / 255f);
		}
	}
	internal enum FilterMode
	{
		Point,
		Bilinear,
		Trilinear
	}
	internal sealed class GL
	{
		private delegate bool d_get_sRGBWrite();

		private static readonly d_get_sRGBWrite m_get_sRGBWrite;

		public static bool sRGBWrite => m_get_sRGBWrite();

		static GL()
		{
			m_get_sRGBWrite = UnityInternals.ResolveICall<d_get_sRGBWrite>("UnityEngine.GL::get_sRGBWrite");
		}
	}
	internal class Graphics : InternalObjectBase
	{
		private delegate IntPtr Internal_DrawMeshNow1_InjectedDelegate(IntPtr mesh, int subsetIndex, ref Vector3 position, ref Quaternion rotation);

		private delegate void Internal_DrawTextureDelegate(IntPtr args);

		private static readonly Internal_DrawTextureDelegate fd_Internal_DrawTexture;

		private static readonly Internal_DrawMeshNow1_InjectedDelegate fd_Internal_DrawMeshNow1_Injected;

		private static readonly int m_DrawTexture_Internal_struct;

		static Graphics()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//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_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)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: 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)
			m_DrawTexture_Internal_struct = -1;
			InternalClassPointerStore<Graphics>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Graphics");
			fd_Internal_DrawTexture = UnityInternals.ResolveICall<Internal_DrawTextureDelegate>("UnityEngine.Graphics::Internal_DrawTexture");
			UnityVersion engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[2] { "2018.2.0", "2019.1.0" }))
			{
				fd_Internal_DrawMeshNow1_Injected = UnityInternals.ResolveICall<Internal_DrawMeshNow1_InjectedDelegate>("UnityEngine.Graphics::Internal_DrawMeshNow1_Injected");
			}
			else
			{
				fd_Internal_DrawMeshNow1_Injected = UnityInternals.ResolveICall<Internal_DrawMeshNow1_InjectedDelegate>("UnityEngine.Graphics::INTERNAL_CALL_Internal_DrawMeshNow1");
			}
			engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[2] { "2019.3.0", "2020.1.0" }))
			{
				m_DrawTexture_Internal_struct = 3;
				return;
			}
			engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[2] { "2018.2.0", "2019.1.0" }))
			{
				m_DrawTexture_Internal_struct = 2;
				return;
			}
			engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[2] { "2017.3.0", "2018.1.0" }))
			{
				m_DrawTexture_Internal_struct = 1;
				return;
			}
			engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[1] { "2017.2.0" }))
			{
				m_DrawTexture_Internal_struct = 0;
			}
		}

		public Graphics(IntPtr ptr)
			: base(ptr)
		{
		}

		public unsafe static void DrawTexture(Rect screenRect, Texture2D texture)
		{
			if (texture != null && !(texture.Pointer == IntPtr.Zero))
			{
				if (m_DrawTexture_Internal_struct == 0)
				{
					Internal_DrawTextureArguments_2017 internal_DrawTextureArguments_ = default(Internal_DrawTextureArguments_2017);
					internal_DrawTextureArguments_.screenRect = screenRect;
					internal_DrawTextureArguments_.sourceRect = new Rect(0, 0, 1, 1);
					internal_DrawTextureArguments_.color = new Color32(128, 128, 128, 128);
					internal_DrawTextureArguments_.texture = UnityInternals.ObjectBaseToPtrNotNull(texture);
					fd_Internal_DrawTexture((IntPtr)(&internal_DrawTextureArguments_));
				}
				else if (m_DrawTexture_Internal_struct == 1)
				{
					Internal_DrawTextureArguments_2018 internal_DrawTextureArguments_2 = default(Internal_DrawTextureArguments_2018);
					internal_DrawTextureArguments_2.screenRect = screenRect;
					internal_DrawTextureArguments_2.sourceRect = new Rect(0, 0, 1, 1);
					internal_DrawTextureArguments_2.color = new Color32(128, 128, 128, 128);
					internal_DrawTextureArguments_2.texture = UnityInternals.ObjectBaseToPtrNotNull(texture);
					fd_Internal_DrawTexture((IntPtr)(&internal_DrawTextureArguments_2));
				}
				else if (m_DrawTexture_Internal_struct == 2)
				{
					Internal_DrawTextureArguments_2019 internal_DrawTextureArguments_3 = default(Internal_DrawTextureArguments_2019);
					internal_DrawTextureArguments_3.screenRect = screenRect;
					internal_DrawTextureArguments_3.sourceRect = new Rect(0, 0, 1, 1);
					internal_DrawTextureArguments_3.color = new Color(0.5f, 0.5f, 0.5f, 0.5f);
					internal_DrawTextureArguments_3.texture = UnityInternals.ObjectBaseToPtrNotNull(texture);
					fd_Internal_DrawTexture((IntPtr)(&internal_DrawTextureArguments_3));
				}
				else if (m_DrawTexture_Internal_struct == 3)
				{
					Internal_DrawTextureArguments_2020 internal_DrawTextureArguments_4 = default(Internal_DrawTextureArguments_2020);
					internal_DrawTextureArguments_4.screenRect = screenRect;
					internal_DrawTextureArguments_4.sourceRect = new Rect(0, 0, 1, 1);
					internal_DrawTextureArguments_4.color = new Color(0.5f, 0.5f, 0.5f, 0.5f);
					internal_DrawTextureArguments_4.leftBorderColor = new Color(0f, 0f, 0f);
					internal_DrawTextureArguments_4.topBorderColor = new Color(0f, 0f, 0f);
					internal_DrawTextureArguments_4.rightBorderColor = new Color(0f, 0f, 0f);
					internal_DrawTextureArguments_4.bottomBorderColor = new Color(0f, 0f, 0f);
					internal_DrawTextureArguments_4.smoothCorners = true;
					internal_DrawTextureArguments_4.texture = UnityInternals.ObjectBaseToPtrNotNull(texture);
					fd_Internal_DrawTexture((IntPtr)(&internal_DrawTextureArguments_4));
				}
			}
		}

		public static void DrawMeshNow(Mesh mesh, Vector3 position, Quaternion rotation)
		{
			DrawMeshNow(mesh, position, rotation, -1);
		}

		public static void DrawMeshNow(Mesh mesh, Vector3 position, Quaternion rotation, int materialIndex)
		{
			if (mesh == null)
			{
				throw new ArgumentNullException("mesh");
			}
			Internal_DrawMeshNow1(mesh, materialIndex, position, rotation);
		}

		private static void Internal_DrawMeshNow1(Mesh mesh, int subsetIndex, Vector3 position, Quaternion rotation)
		{
			Internal_DrawMeshNow1_Injected(mesh, subsetIndex, ref position, ref rotation);
		}

		private static void Internal_DrawMeshNow1_Injected(Mesh mesh, int subsetIndex, ref Vector3 position, ref Quaternion rotation)
		{
			if (mesh != null && !(mesh.Pointer == IntPtr.Zero))
			{
				fd_Internal_DrawMeshNow1_Injected(UnityInternals.ObjectBaseToPtr(mesh), subsetIndex, ref position, ref rotation);
			}
		}
	}
	internal enum HideFlags
	{
		None = 0,
		HideInHierarchy = 1,
		HideInInspector = 2,
		DontSaveInEditor = 4,
		NotEditable = 8,
		DontSaveInBuild = 16,
		DontUnloadUnusedAsset = 32,
		DontSave = 52,
		HideAndDontSave = 61
	}
	internal static class ImageConversion
	{
		private delegate bool ImageConversion_LoadImage_Delegate(IntPtr tex, IntPtr data, bool markNonReadable);

		private static ImageConversion_LoadImage_Delegate ImageConversion_LoadImage;

		static ImageConversion()
		{
			IntPtr intPtr = UnityInternals.ResolveICall("UnityEngine.ImageConversion::LoadImage(UnityEngine.Texture2D,System.Byte[],System.Boolean)");
			if (intPtr != IntPtr.Zero)
			{
				ImageConversion_LoadImage = (ImageConversion_LoadImage_Delegate)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(ImageConversion_LoadImage_Delegate));
			}
			else
			{
				MelonLogger.Error("Failed to resolve icall UnityEngine.ImageConversion::LoadImage(UnityEngine.Texture2D,System.Byte[],System.Boolean)");
			}
		}

		public unsafe static bool LoadImage(Texture2D tex, byte[] data, bool markNonReadable)
		{
			if (ImageConversion_LoadImage == null)
			{
				MelonLogger.Error("Failed to run UnityEngine.ImageConversion::LoadImage(UnityEngine.Texture2D,System.Byte[],System.Boolean)");
				return false;
			}
			IntPtr intPtr = UnityInternals.array_new(InternalClassPointerStore<byte>.NativeClassPtr, (uint)data.Length);
			for (int i = 0; i < data.Length; i++)
			{
				((byte*)((IntPtr)((long)intPtr + 4 * IntPtr.Size)).ToPointer())[i] = data[i];
			}
			return ImageConversion_LoadImage(tex.Pointer, intPtr, markNonReadable);
		}
	}
	internal struct Internal_DrawTextureArguments_2017
	{
		public Rect screenRect;

		public Rect sourceRect;

		public int leftBorder;

		public int rightBorder;

		public int topBorder;

		public int bottomBorder;

		public Color32 color;

		public Vector4 borderWidths;

		public float cornerRadius;

		public int pass;

		public IntPtr texture;

		public IntPtr mat;
	}
	internal struct Internal_DrawTextureArguments_2018
	{
		public Rect screenRect;

		public Rect sourceRect;

		public int leftBorder;

		public int rightBorder;

		public int topBorder;

		public int bottomBorder;

		public Color32 color;

		public Vector4 borderWidths;

		public Vector4 cornerRadius;

		public int pass;

		public IntPtr texture;

		public IntPtr mat;
	}
	internal struct Internal_DrawTextureArguments_2019
	{
		public Rect screenRect;

		public Rect sourceRect;

		public int leftBorder;

		public int rightBorder;

		public int topBorder;

		public int bottomBorder;

		public Color color;

		public Vector4 borderWidths;

		public Vector4 cornerRadius;

		public int pass;

		public IntPtr texture;

		public IntPtr mat;
	}
	internal struct Internal_DrawTextureArguments_2020
	{
		public Rect screenRect;

		public Rect sourceRect;

		public int leftBorder;

		public int rightBorder;

		public int topBorder;

		public int bottomBorder;

		public Color leftBorderColor;

		public Color rightBorderColor;

		public Color topBorderColor;

		public Color bottomBorderColor;

		public Color color;

		public Vector4 borderWidths;

		public Vector4 cornerRadiuses;

		public bool smoothCorners;

		public int pass;

		public IntPtr texture;

		public IntPtr mat;
	}
	internal class Material : UnityObject
	{
		private delegate bool d_SetPass(IntPtr @this, int pass);

		private static readonly d_SetPass m_SetPass;

		static Material()
		{
			InternalClassPointerStore<Material>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Material");
			UnityInternals.runtime_class_init(InternalClassPointerStore<Material>.NativeClassPtr);
			m_SetPass = UnityInternals.ResolveICall<d_SetPass>("UnityEngine.Material::SetPass");
		}

		public Material(IntPtr ptr)
			: base(ptr)
		{
		}

		public bool SetPass(int pass)
		{
			return m_SetPass(UnityInternals.ObjectBaseToPtrNotNull(this), pass);
		}
	}
	internal sealed class Mesh : UnityObject
	{
		private delegate void SetArrayForChannelImpl_2017(IntPtr @this, int channel, int format, int dim, IntPtr values, int arraySize);

		private delegate void SetArrayForChannelImpl_2019(IntPtr @this, int channel, int format, int dim, IntPtr values, int arraySize, int valuesStart, int valuesCount);

		private delegate void SetArrayForChannelImpl_2020(IntPtr @this, int channel, int format, int dim, IntPtr values, int arraySize, int valuesStart, int valuesCount, int updateFlags);

		private static readonly IntPtr m_ctor;

		private static readonly IntPtr m_set_triangles;

		private static readonly IntPtr m_RecalculateBounds;

		private static readonly SetArrayForChannelImpl_2017 m_SetArrayForChannelImpl_2017;

		private static readonly SetArrayForChannelImpl_2019 m_SetArrayForChannelImpl_2019;

		private static readonly SetArrayForChannelImpl_2020 m_SetArrayForChannelImpl_2020;

		private static readonly int type_SetArrayForChannelImpl;

		public unsafe Vector3[] vertices
		{
			set
			{
				int num = value.Length;
				IntPtr intPtr = UnityInternals.array_new(InternalClassPointerStore<Vector3>.NativeClassPtr, (ulong)num);
				for (int i = 0; i < num; i++)
				{
					*(Vector3*)((nint)((long)intPtr + 4 * IntPtr.Size) + (nint)i * (nint)sizeof(Vector3)) = value[i];
				}
				SetArrayForChannelImpl(VertexAttribute.Vertex, intPtr, 3, num);
			}
		}

		public unsafe Vector3[] normals
		{
			set
			{
				int num = value.Length;
				IntPtr intPtr = UnityInternals.array_new(InternalClassPointerStore<Vector3>.NativeClassPtr, (ulong)num);
				for (int i = 0; i < num; i++)
				{
					*(Vector3*)((nint)((long)intPtr + 4 * IntPtr.Size) + (nint)i * (nint)sizeof(Vector3)) = value[i];
				}
				SetArrayForChannelImpl(VertexAttribute.Normal, intPtr, 3, num);
			}
		}

		public unsafe Vector4[] tangents
		{
			set
			{
				int num = value.Length;
				IntPtr intPtr = UnityInternals.array_new(InternalClassPointerStore<Vector4>.NativeClassPtr, (ulong)num);
				for (int i = 0; i < num; i++)
				{
					*(Vector4*)((nint)((long)intPtr + 4 * IntPtr.Size) + (nint)i * (nint)sizeof(Vector4)) = value[i];
				}
				SetArrayForChannelImpl(VertexAttribute.Tangent, intPtr, 4, num);
			}
		}

		public unsafe Vector2[] uv
		{
			set
			{
				int num = value.Length;
				IntPtr intPtr = UnityInternals.array_new(InternalClassPointerStore<Vector2>.NativeClassPtr, (ulong)num);
				for (int i = 0; i < num; i++)
				{
					*(Vector2*)((nint)((long)intPtr + 4 * IntPtr.Size) + (nint)i * (nint)sizeof(Vector2)) = value[i];
				}
				SetArrayForChannelImpl(VertexAttribute.TexCoord0, intPtr, 2, num);
			}
		}

		public unsafe Color[] colors
		{
			set
			{
				int num = value.Length;
				IntPtr intPtr = UnityInternals.array_new(InternalClassPointerStore<Color>.NativeClassPtr, (ulong)num);
				for (int i = 0; i < num; i++)
				{
					*(Color*)((nint)((long)intPtr + 4 * IntPtr.Size) + (nint)i * (nint)sizeof(Color)) = value[i];
				}
				SetArrayForChannelImpl(VertexAttribute.Color, intPtr, 4, num);
			}
		}

		public unsafe int[] triangles
		{
			set
			{
				UnityInternals.ObjectBaseToPtrNotNull(this);
				IntPtr intPtr = UnityInternals.array_new(InternalClassPointerStore<int>.NativeClassPtr, (ulong)value.Length);
				for (int i = 0; i < value.Length; i++)
				{
					*(int*)((nint)((long)intPtr + 4 * IntPtr.Size) + (nint)i * (nint)4) = value[i];
				}
				void** ptr = stackalloc void*[1];
				*ptr = (void*)intPtr;
				IntPtr exc = default(IntPtr);
				UnityInternals.runtime_invoke(m_set_triangles, UnityInternals.ObjectBaseToPtrNotNull(this), ptr, ref exc);
				Il2CppException.RaiseExceptionIfNecessary(exc);
			}
		}

		static Mesh()
		{
			//IL_008e: 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_00c6: 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_00fe: 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)
			type_SetArrayForChannelImpl = -1;
			InternalClassPointerStore<Mesh>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Mesh");
			UnityInternals.runtime_class_init(InternalClassPointerStore<Mesh>.NativeClassPtr);
			m_ctor = UnityInternals.GetMethod(InternalClassPointerStore<Mesh>.NativeClassPtr, ".ctor", "System.Void");
			m_set_triangles = UnityInternals.GetMethod(InternalClassPointerStore<Mesh>.NativeClassPtr, "set_triangles", "System.Void", "System.Int32[]");
			m_RecalculateBounds = UnityInternals.GetMethod(InternalClassPointerStore<Mesh>.NativeClassPtr, "RecalculateBounds", "System.Void");
			UnityVersion engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[1] { "2020.1.0" }))
			{
				m_SetArrayForChannelImpl_2020 = UnityInternals.ResolveICall<SetArrayForChannelImpl_2020>("UnityEngine.Mesh::SetArrayForChannelImpl");
				type_SetArrayForChannelImpl = 2;
				return;
			}
			engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[1] { "2019.3.0" }))
			{
				m_SetArrayForChannelImpl_2019 = UnityInternals.ResolveICall<SetArrayForChannelImpl_2019>("UnityEngine.Mesh::SetArrayForChannelImpl");
				type_SetArrayForChannelImpl = 1;
				return;
			}
			engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[1] { "2017.1.0" }))
			{
				m_SetArrayForChannelImpl_2017 = UnityInternals.ResolveICall<SetArrayForChannelImpl_2017>("UnityEngine.Mesh::SetArrayForChannelImpl");
				type_SetArrayForChannelImpl = 0;
			}
		}

		public Mesh(IntPtr ptr)
			: base(ptr)
		{
		}

		public unsafe Mesh()
			: base(UnityInternals.object_new(InternalClassPointerStore<Mesh>.NativeClassPtr))
		{
			IntPtr exc = default(IntPtr);
			UnityInternals.runtime_invoke(m_ctor, UnityInternals.ObjectBaseToPtrNotNull(this), null, ref exc);
			Il2CppException.RaiseExceptionIfNecessary(exc);
		}

		private void SetArrayForChannelImpl(int channel, IntPtr values, int channelDimensions, int valuesCount)
		{
			if (type_SetArrayForChannelImpl == 0)
			{
				m_SetArrayForChannelImpl_2017(UnityInternals.ObjectBaseToPtrNotNull(this), channel, 0, channelDimensions, values, valuesCount);
				return;
			}
			if (type_SetArrayForChannelImpl == 1)
			{
				m_SetArrayForChannelImpl_2019(UnityInternals.ObjectBaseToPtrNotNull(this), channel, 0, channelDimensions, values, valuesCount, 0, valuesCount);
				return;
			}
			if (type_SetArrayForChannelImpl == 2)
			{
				m_SetArrayForChannelImpl_2020(UnityInternals.ObjectBaseToPtrNotNull(this), channel, 0, channelDimensions, values, valuesCount, 0, valuesCount, 0);
				return;
			}
			throw new NotImplementedException("SetArrayForChannel isn't implemented for this version of Unity");
		}

		public unsafe void RecalculateBounds()
		{
			UnityInternals.ObjectBaseToPtrNotNull(this);
			IntPtr exc = default(IntPtr);
			UnityInternals.runtime_invoke(m_RecalculateBounds, UnityInternals.ObjectBaseToPtrNotNull(this), null, ref exc);
			Il2CppException.RaiseExceptionIfNecessary(exc);
		}
	}
	[StructLayout(LayoutKind.Explicit)]
	internal struct Quaternion
	{
		[FieldOffset(0)]
		public float x;

		[FieldOffset(4)]
		public float y;

		[FieldOffset(8)]
		public float z;

		[FieldOffset(12)]
		public float w;

		public static Quaternion identity => default(Quaternion);

		static Quaternion()
		{
			InternalClassPointerStore<Quaternion>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Quaternion");
		}
	}
	[StructLayout(LayoutKind.Explicit)]
	internal struct Rect
	{
		[FieldOffset(0)]
		public float m_XMin;

		[FieldOffset(4)]
		public float m_YMin;

		[FieldOffset(8)]
		public float m_Width;

		[FieldOffset(12)]
		public float m_Height;

		static Rect()
		{
			InternalClassPointerStore<Rect>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Rect");
			UnityInternals.runtime_class_init(InternalClassPointerStore<Rect>.NativeClassPtr);
		}

		public Rect(int x, int y, int width, int height)
		{
			m_XMin = x;
			m_YMin = y;
			m_Width = width;
			m_Height = height;
		}
	}
	internal class Resources
	{
		private static readonly IntPtr m_GetBuiltinResource;

		static Resources()
		{
			InternalClassPointerStore<Resources>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Resources");
			m_GetBuiltinResource = UnityInternals.GetMethod(InternalClassPointerStore<Resources>.NativeClassPtr, "GetBuiltinResource", "UnityEngine.Object", "System.Type", "System.String");
		}

		public unsafe static IntPtr GetBuiltinResource(Il2CppSystem.Type type, string path)
		{
			void** ptr = stackalloc void*[2];
			*ptr = (void*)UnityInternals.ObjectBaseToPtr(type);
			ptr[1] = (void*)UnityInternals.ManagedStringToInternal(path);
			IntPtr exc = default(IntPtr);
			MelonDebug.Msg("Calling runtime_invoke for GetBuiltinResource");
			IntPtr result = UnityInternals.runtime_invoke(m_GetBuiltinResource, IntPtr.Zero, ptr, ref exc);
			MelonDebug.Msg("returnedException: " + exc + ", objectPointer: " + result);
			Il2CppException.RaiseExceptionIfNecessary(exc);
			return result;
		}

		public static T GetBuiltinResource<T>(string path) where T : InternalObjectBase
		{
			MelonDebug.Msg("GetBuiltinResource<T>");
			IntPtr builtinResource = GetBuiltinResource(InternalType.Of<T>(), path);
			if (!(builtinResource != IntPtr.Zero))
			{
				return null;
			}
			return (T)typeof(T).GetConstructor(new System.Type[1] { typeof(IntPtr) }).Invoke(new object[1] { builtinResource });
		}
	}
	internal class Screen
	{
		private static IntPtr m_get_width;

		private static IntPtr m_get_height;

		public unsafe static int width
		{
			get
			{
				IntPtr* param = null;
				IntPtr exc = IntPtr.Zero;
				IntPtr obj = UnityInternals.runtime_invoke(m_get_width, IntPtr.Zero, (void**)param, ref exc);
				Il2CppException.RaiseExceptionIfNecessary(exc);
				return *(int*)(void*)UnityInternals.object_unbox(obj);
			}
		}

		public unsafe static int height
		{
			get
			{
				IntPtr* param = null;
				IntPtr exc = IntPtr.Zero;
				IntPtr obj = UnityInternals.runtime_invoke(m_get_height, IntPtr.Zero, (void**)param, ref exc);
				Il2CppException.RaiseExceptionIfNecessary(exc);
				return *(int*)(void*)UnityInternals.object_unbox(obj);
			}
		}

		static Screen()
		{
			InternalClassPointerStore<Screen>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Screen");
			m_get_width = UnityInternals.GetMethod(InternalClassPointerStore<Screen>.NativeClassPtr, "get_width", "System.Int32");
			m_get_height = UnityInternals.GetMethod(InternalClassPointerStore<Screen>.NativeClassPtr, "get_height", "System.Int32");
		}
	}
	internal class Texture : UnityObject
	{
		private delegate int GetDataWidthDelegate(IntPtr @this);

		private delegate int GetDataHeightDelegate(IntPtr @this);

		private delegate int set_filterModeDelegate(IntPtr @this, FilterMode filterMode);

		private static readonly GetDataWidthDelegate getDataWidth;

		private static readonly GetDataHeightDelegate getDataHeight;

		private static readonly set_filterModeDelegate set_filterMode_;

		public int width => getDataWidth(UnityInternals.ObjectBaseToPtrNotNull(this));

		public int height => getDataHeight(UnityInternals.ObjectBaseToPtrNotNull(this));

		public FilterMode filterMode
		{
			set
			{
				set_filterMode_(UnityInternals.ObjectBaseToPtrNotNull(this), value);
			}
		}

		static Texture()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			InternalClassPointerStore<Texture>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Texture");
			UnityVersion engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[1] { "2018.1.0" }))
			{
				getDataWidth = UnityInternals.ResolveICall<GetDataWidthDelegate>("UnityEngine.Texture::GetDataWidth");
				getDataHeight = UnityInternals.ResolveICall<GetDataHeightDelegate>("UnityEngine.Texture::GetDataHeight");
			}
			else
			{
				engineVersion = UnityInformationHandler.EngineVersion;
				if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[1] { "2017.1.0" }))
				{
					getDataWidth = UnityInternals.ResolveICall<GetDataWidthDelegate>("UnityEngine.Texture::Internal_GetWidth");
					getDataHeight = UnityInternals.ResolveICall<GetDataHeightDelegate>("UnityEngine.Texture::Internal_GetHeight");
				}
			}
			set_filterMode_ = UnityInternals.ResolveICall<set_filterModeDelegate>("UnityEngine.Texture::set_filterMode");
		}

		public Texture(IntPtr ptr)
			: base(ptr)
		{
		}
	}
	internal class Texture2D : Texture
	{
		private delegate void SetPixelsImplDelegate_2017(IntPtr @this, int x, int y, int w, int h, IntPtr pixel, int miplevel);

		private delegate void SetPixelsImplDelegate_2018(IntPtr @this, int x, int y, int w, int h, IntPtr pixel, int miplevel, int frame);

		private static readonly IntPtr m_get_whiteTexture;

		private static readonly IntPtr m_ctor;

		private static readonly SetPixelsImplDelegate_2017 m_SetPixelsImpl_2017;

		private static readonly SetPixelsImplDelegate_2018 m_SetPixelsImpl_2018;

		private static readonly IntPtr m_Apply;

		private static readonly int type_SetPixelsImpl;

		public unsafe static Texture2D whiteTexture
		{
			get
			{
				IntPtr exc = IntPtr.Zero;
				IntPtr intPtr = UnityInternals.runtime_invoke(m_get_whiteTexture, IntPtr.Zero, null, ref exc);
				Il2CppException.RaiseExceptionIfNecessary(exc);
				if (!(intPtr == IntPtr.Zero))
				{
					return new Texture2D(intPtr);
				}
				return null;
			}
		}

		static Texture2D()
		{
			//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_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)
			type_SetPixelsImpl = -1;
			InternalClassPointerStore<Texture2D>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Texture2D");
			UnityInternals.runtime_class_init(InternalClassPointerStore<Texture2D>.NativeClassPtr);
			m_ctor = UnityInternals.GetMethod(InternalClassPointerStore<Texture2D>.NativeClassPtr, ".ctor", "System.Void", "System.Int32", "System.Int32");
			m_get_whiteTexture = UnityInternals.GetMethod(InternalClassPointerStore<Texture2D>.NativeClassPtr, "get_whiteTexture", "UnityEngine.Texture2D");
			UnityVersion engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[1] { "2018.1.0" }))
			{
				type_SetPixelsImpl = 1;
				m_SetPixelsImpl_2018 = UnityInternals.ResolveICall<SetPixelsImplDelegate_2018>("UnityEngine.Texture2D::SetPixelsImpl");
			}
			else
			{
				engineVersion = UnityInformationHandler.EngineVersion;
				if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[1] { "2017.1.0" }))
				{
					type_SetPixelsImpl = 0;
					m_SetPixelsImpl_2017 = UnityInternals.ResolveICall<SetPixelsImplDelegate_2017>("UnityEngine.Texture2D::SetPixels");
				}
			}
			m_Apply = UnityInternals.GetMethod(InternalClassPointerStore<Texture2D>.NativeClassPtr, "Apply", "System.Void");
		}

		public Texture2D(IntPtr ptr)
			: base(ptr)
		{
		}

		public unsafe Texture2D(int width, int height)
			: base(UnityInternals.object_new(InternalClassPointerStore<Texture2D>.NativeClassPtr))
		{
			void** ptr = stackalloc void*[2];
			*ptr = &width;
			ptr[1] = &height;
			IntPtr exc = default(IntPtr);
			UnityInternals.runtime_invoke(m_ctor, UnityInternals.ObjectBaseToPtrNotNull(this), ptr, ref exc);
			Il2CppException.RaiseExceptionIfNecessary(exc);
		}

		public void SetPixels(Color[] colors)
		{
			SetPixels(0, 0, base.width, base.height, colors);
		}

		public void SetPixels(int x, int y, int blockWidth, int blockHeight, Color[] colors, int miplevel = 0)
		{
			SetPixelsImpl(x, y, blockWidth, blockHeight, colors, miplevel, 0);
		}

		public unsafe void SetPixelsImpl(int x, int y, int w, int h, Color[] pixel, int miplevel, int frame)
		{
			IntPtr intPtr = UnityInternals.array_new(InternalClassPointerStore<Color>.NativeClassPtr, (uint)pixel.Length);
			for (int i = 0; i < pixel.Length; i++)
			{
				*(Color*)((byte*)((IntPtr)((long)intPtr + 4 * IntPtr.Size)).ToPointer() + (nint)i * (nint)sizeof(Color)) = pixel[i];
			}
			if (type_SetPixelsImpl == 0)
			{
				m_SetPixelsImpl_2017(UnityInternals.ObjectBaseToPtrNotNull(this), x, y, w, h, intPtr, miplevel);
			}
			else if (type_SetPixelsImpl == 1)
			{
				m_SetPixelsImpl_2018(UnityInternals.ObjectBaseToPtrNotNull(this), x, y, w, h, intPtr, miplevel, frame);
			}
		}

		public unsafe void Apply()
		{
			IntPtr exc = default(IntPtr);
			UnityInternals.runtime_invoke(m_Apply, UnityInternals.ObjectBaseToPtrNotNull(this), null, ref exc);
			Il2CppException.RaiseExceptionIfNecessary(exc);
		}
	}
	internal static class UnityDebug
	{
		private delegate bool get_isDebugBuild_Delegate();

		private static get_isDebugBuild_Delegate get_isDebugBuild_Ptr;

		internal static bool isDebugBuild => get_isDebugBuild_Ptr();

		static UnityDebug()
		{
			IntPtr intPtr = UnityInternals.ResolveICall("UnityEngine.Debug::get_isDebugBuild");
			if (intPtr != IntPtr.Zero)
			{
				get_isDebugBuild_Ptr = (get_isDebugBuild_Delegate)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(get_isDebugBuild_Delegate));
			}
			else
			{
				MelonLogger.Error("Failed to resolve icall UnityEngine.Debug::get_isDebugBuild");
			}
		}
	}
	internal class UnityObject : InternalObjectBase
	{
		private delegate HideFlags get_hideFlags_Delegate(IntPtr obj);

		private delegate void set_hideFlags_Delegate(IntPtr obj, HideFlags hideFlags);

		private static get_hideFlags_Delegate m_get_hideFlags;

		private static set_hideFlags_Delegate m_set_hideFlags;

		private static IntPtr m_DestroyImmediate;

		private static IntPtr m_DontDestroyOnLoad;

		public HideFlags hideFlags
		{
			get
			{
				if (base.Pointer == IntPtr.Zero)
				{
					return HideFlags.None;
				}
				return m_get_hideFlags(base.Pointer);
			}
			set
			{
				if (!(base.Pointer == IntPtr.Zero))
				{
					m_set_hideFlags(base.Pointer, value);
				}
			}
		}

		static UnityObject()
		{
			InternalClassPointerStore<UnityObject>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Object");
			m_DestroyImmediate = UnityInternals.GetMethod(InternalClassPointerStore<UnityObject>.NativeClassPtr, "DestroyImmediate", "System.Void", "UnityEngine.Object");
			m_DontDestroyOnLoad = UnityInternals.GetMethod(InternalClassPointerStore<UnityObject>.NativeClassPtr, "DontDestroyOnLoad", "System.Void", "UnityEngine.Object");
			m_get_hideFlags = UnityInternals.ResolveICall<get_hideFlags_Delegate>("UnityEngine.Object::get_hideFlags(UnityEngine.Object)");
			m_set_hideFlags = UnityInternals.ResolveICall<set_hideFlags_Delegate>("UnityEngine.Object::set_hideFlags(UnityEngine.Object)");
		}

		public UnityObject(IntPtr ptr)
			: base(ptr)
		{
		}

		public unsafe void DestroyImmediate()
		{
			if (!(base.Pointer == IntPtr.Zero))
			{
				void** ptr = stackalloc void*[1];
				*ptr = base.Pointer.ToPointer();
				IntPtr exc = IntPtr.Zero;
				UnityInternals.runtime_invoke(m_DestroyImmediate, IntPtr.Zero, ptr, ref exc);
				Il2CppException.RaiseExceptionIfNecessary(exc);
			}
		}

		public unsafe void DontDestroyOnLoad()
		{
			if (!(base.Pointer == IntPtr.Zero))
			{
				void** ptr = stackalloc void*[1];
				*ptr = base.Pointer.ToPointer();
				IntPtr exc = IntPtr.Zero;
				UnityInternals.runtime_invoke(m_DontDestroyOnLoad, IntPtr.Zero, ptr, ref exc);
				Il2CppException.RaiseExceptionIfNecessary(exc);
			}
		}
	}
	[StructLayout(LayoutKind.Explicit)]
	internal struct Vector2
	{
		[FieldOffset(0)]
		public float x;

		[FieldOffset(4)]
		public float y;

		static Vector2()
		{
			InternalClassPointerStore<Vector2>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Vector2");
		}

		public Vector2(float x, float y)
		{
			this.x = x;
			this.y = y;
		}
	}
	[StructLayout(LayoutKind.Explicit)]
	internal struct Vector3
	{
		[FieldOffset(0)]
		public float x;

		[FieldOffset(4)]
		public float y;

		[FieldOffset(8)]
		public float z;

		public static Vector3 zero => default(Vector3);

		static Vector3()
		{
			InternalClassPointerStore<Vector3>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Vector3");
		}

		public Vector3(float x, float y, float z)
		{
			this.x = x;
			this.y = y;
			this.z = z;
		}

		public static Vector3 operator *(Vector3 a, float d)
		{
			return new Vector3(a.x * d, a.y * d, a.z * d);
		}

		public override string ToString()
		{
			return $"{x} {y} {z}";
		}
	}
	[StructLayout(LayoutKind.Explicit)]
	internal struct Vector4
	{
		[FieldOffset(0)]
		public float x;

		[FieldOffset(4)]
		public float y;

		[FieldOffset(8)]
		public float z;

		[FieldOffset(12)]
		public float w;

		static Vector4()
		{
			InternalClassPointerStore<Vector4>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.CoreModule.dll", "UnityEngine", "Vector4");
		}

		public static explicit operator Vector2(Vector4 src)
		{
			return new Vector2(src.x, src.y);
		}
	}
	internal enum VerticalWrapMode
	{
		Truncate,
		Overflow
	}
	internal class Font : UnityObject
	{
		private static IntPtr m_get_material;

		public unsafe Material material
		{
			get
			{
				UnityInternals.ObjectBaseToPtrNotNull(this);
				IntPtr exc = default(IntPtr);
				IntPtr intPtr = UnityInternals.runtime_invoke(m_get_material, UnityInternals.ObjectBaseToPtrNotNull(this), null, ref exc);
				Il2CppException.RaiseExceptionIfNecessary(exc);
				if (!(intPtr != IntPtr.Zero))
				{
					return null;
				}
				return new Material(intPtr);
			}
		}

		static Font()
		{
			InternalClassPointerStore<Font>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.TextRenderingModule.dll", "UnityEngine", "Font");
			UnityInternals.runtime_class_init(InternalClassPointerStore<Font>.NativeClassPtr);
			m_get_material = UnityInternals.GetMethod(InternalClassPointerStore<Font>.NativeClassPtr, "get_material", "UnityEngine.Material");
		}

		public Font(IntPtr ptr)
			: base(ptr)
		{
		}
	}
	internal enum FontStyle
	{
		Normal,
		Bold,
		Italic,
		BoldAndItalic
	}
	internal enum TextAnchor
	{
		UpperLeft,
		UpperCenter,
		UpperRight,
		MiddleLeft,
		MiddleCenter,
		MiddleRight,
		LowerLeft,
		LowerCenter,
		LowerRight
	}
	internal class TextGenerationSettings : InternalObjectBase
	{
		private static readonly int classsize;

		private static readonly IntPtr f_font;

		private static readonly IntPtr f_color;

		private static readonly IntPtr f_fontSize;

		private static readonly IntPtr f_lineSpacing;

		private static readonly IntPtr f_richText;

		private static readonly IntPtr f_scaleFactor;

		private static readonly IntPtr f_fontStyle;

		private static readonly IntPtr f_textAnchor;

		private static readonly IntPtr f_verticalOverflow;

		private static readonly IntPtr f_generationExtents;

		private static readonly IntPtr f_pivot;

		public unsafe Font font
		{
			get
			{
				IntPtr intPtr = *(IntPtr*)((uint)(int)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_font));
				if (!(intPtr != IntPtr.Zero))
				{
					return null;
				}
				return new Font(intPtr);
			}
			set
			{
				*(IntPtr*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_font)) = UnityInternals.ObjectBaseToPtr(value);
			}
		}

		public unsafe Color color
		{
			get
			{
				return *(Color*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_color));
			}
			set
			{
				*(Color*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_color)) = value;
			}
		}

		public unsafe int fontSize
		{
			get
			{
				return *(int*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_fontSize));
			}
			set
			{
				*(int*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_fontSize)) = value;
			}
		}

		public unsafe float lineSpacing
		{
			get
			{
				return *(float*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_lineSpacing));
			}
			set
			{
				*(float*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_lineSpacing)) = value;
			}
		}

		public unsafe bool richText
		{
			get
			{
				return *(bool*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_richText));
			}
			set
			{
				*(bool*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_richText)) = value;
			}
		}

		public unsafe float scaleFactor
		{
			get
			{
				return *(float*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_scaleFactor));
			}
			set
			{
				*(float*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_scaleFactor)) = value;
			}
		}

		public unsafe FontStyle fontStyle
		{
			get
			{
				return *(FontStyle*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_fontStyle));
			}
			set
			{
				*(FontStyle*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_fontStyle)) = value;
			}
		}

		public unsafe TextAnchor textAnchor
		{
			get
			{
				return *(TextAnchor*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_textAnchor));
			}
			set
			{
				*(TextAnchor*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_textAnchor)) = value;
			}
		}

		public unsafe VerticalWrapMode verticalOverflow
		{
			get
			{
				return *(VerticalWrapMode*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_verticalOverflow));
			}
			set
			{
				*(VerticalWrapMode*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_verticalOverflow)) = value;
			}
		}

		public unsafe Vector2 generationExtents
		{
			get
			{
				return *(Vector2*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_generationExtents));
			}
			set
			{
				*(Vector2*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_generationExtents)) = value;
			}
		}

		public unsafe Vector2 pivot
		{
			get
			{
				return *(Vector2*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_pivot));
			}
			set
			{
				*(Vector2*)((long)UnityInternals.ObjectBaseToPtrNotNull(this) + UnityInternals.field_get_offset(f_pivot)) = value;
			}
		}

		static TextGenerationSettings()
		{
			InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.TextRenderingModule.dll", "UnityEngine", "TextGenerationSettings");
			uint align = 0u;
			classsize = UnityInternals.class_value_size(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, ref align);
			f_font = UnityInternals.GetField(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, "font");
			f_color = UnityInternals.GetField(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, "color");
			f_fontSize = UnityInternals.GetField(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, "fontSize");
			f_lineSpacing = UnityInternals.GetField(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, "lineSpacing");
			f_richText = UnityInternals.GetField(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, "richText");
			f_scaleFactor = UnityInternals.GetField(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, "scaleFactor");
			f_fontStyle = UnityInternals.GetField(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, "fontStyle");
			f_textAnchor = UnityInternals.GetField(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, "textAnchor");
			f_verticalOverflow = UnityInternals.GetField(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, "verticalOverflow");
			f_generationExtents = UnityInternals.GetField(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, "generationExtents");
			f_pivot = UnityInternals.GetField(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, "pivot");
		}

		public TextGenerationSettings(IntPtr ptr)
			: base(ptr)
		{
		}

		public unsafe TextGenerationSettings()
		{
			byte** ptr = stackalloc byte*[classsize];
			IntPtr obj = UnityInternals.value_box(InternalClassPointerStore<TextGenerationSettings>.NativeClassPtr, (IntPtr)ptr);
			myGcHandle = UnityInternals.gchandle_new(obj, pinned: false);
		}
	}
	internal class TextGenerator : InternalObjectBase
	{
		private delegate int get_vertexCountDelegate(IntPtr @this);

		private delegate IntPtr GetVerticesArrayDelegate(IntPtr @this);

		private static readonly IntPtr m_ctor;

		private static readonly IntPtr m_Populate;

		private static readonly get_vertexCountDelegate fd_get_vertexCount;

		private static readonly GetVerticesArrayDelegate fd_GetVerticesArray;

		public int vertexCount => fd_get_vertexCount(UnityInternals.ObjectBaseToPtrNotNull(this));

		static TextGenerator()
		{
			InternalClassPointerStore<TextGenerator>.NativeClassPtr = UnityInternals.GetClass("UnityEngine.TextRenderingModule.dll", "UnityEngine", "TextGenerator");
			UnityInternals.runtime_class_init(InternalClassPointerStore<TextGenerator>.NativeClassPtr);
			m_ctor = UnityInternals.GetMethod(InternalClassPointerStore<TextGenerator>.NativeClassPtr, ".ctor", "System.Void");
			m_Populate = UnityInternals.GetMethod(InternalClassPointerStore<TextGenerator>.NativeClassPtr, "Populate", "System.Boolean", "System.String", "UnityEngine.TextGenerationSettings");
			fd_get_vertexCount = UnityInternals.ResolveICall<get_vertexCountDelegate>("UnityEngine.TextGenerator::get_vertexCount");
			fd_GetVerticesArray = UnityInternals.ResolveICall<GetVerticesArrayDelegate>("UnityEngine.TextGenerator::GetVerticesArray");
		}

		public TextGenerator(IntPtr ptr)
			: base(ptr)
		{
		}

		public unsafe TextGenerator()
			: this(UnityInternals.object_new(InternalClassPointerStore<TextGenerator>.NativeClassPtr))
		{
			IntPtr exc = default(IntPtr);
			UnityInternals.runtime_invoke(m_ctor, UnityInternals.ObjectBaseToPtrNotNull(this), null, ref exc);
			Il2CppException.RaiseExceptionIfNecessary(exc);
		}

		public unsafe bool Populate(string str, TextGenerationSettings settings)
		{
			void** ptr = stackalloc void*[2];
			*ptr = (void*)UnityInternals.ManagedStringToInternal(str);
			ptr[1] = (void*)UnityInternals.object_unbox(UnityInternals.ObjectBaseToPtrNotNull(settings));
			IntPtr exc = default(IntPtr);
			IntPtr obj = UnityInternals.runtime_invoke(m_Populate, UnityInternals.ObjectBaseToPtrNotNull(this), ptr, ref exc);
			Il2CppException.RaiseExceptionIfNecessary(exc);
			return *(bool*)(void*)UnityInternals.object_unbox(obj);
		}

		public UIVertexWrapper[] GetVerticesArray()
		{
			IntPtr intPtr = fd_GetVerticesArray(UnityInternals.ObjectBaseToPtrNotNull(this));
			if (intPtr == IntPtr.Zero)
			{
				return null;
			}
			UIVertexWrapper[] array = new UIVertexWrapper[UnityInternals.array_length(intPtr)];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new UIVertexWrapper((IntPtr)((long)intPtr + 4 * IntPtr.Size + i * UIVertexWrapper.sizeOfElement));
			}
			return array;
		}
	}
	internal struct UIVertex_2020
	{
		public Vector3 position;

		public Vector3 normal;

		public Vector4 tangent;

		public Color32 color;

		public Vector4 uv0;

		public Vector4 uv1;

		public Vector4 uv2;

		public Vector4 uv3;
	}
	internal struct UIVertex_2018
	{
		public Vector3 position;

		public Vector3 normal;

		public Vector4 tangent;

		public Color32 color;

		public Vector2 uv0;

		public Vector2 uv1;

		public Vector2 uv2;

		public Vector2 uv3;
	}
	internal struct UIVertex_2017
	{
		public Vector3 position;

		public Vector3 normal;

		public Color32 color;

		public Vector2 uv0;

		public Vector2 uv1;

		public Vector2 uv2;

		public Vector2 uv3;

		public Vector4 tangent;
	}
	internal struct UIVertexWrapper
	{
		private static readonly int mode;

		public static readonly int sizeOfElement;

		private IntPtr ptr;

		public unsafe Vector3 position
		{
			get
			{
				if (mode != 2)
				{
					if (mode != 1)
					{
						if (mode != 0)
						{
							throw new Exception("UIVertex mode not set");
						}
						return ((UIVertex_2017*)(void*)ptr)->position;
					}
					return ((UIVertex_2018*)(void*)ptr)->position;
				}
				return ((UIVertex_2020*)(void*)ptr)->position;
			}
		}

		public unsafe Vector3 normal
		{
			get
			{
				if (mode != 2)
				{
					if (mode != 1)
					{
						if (mode != 0)
						{
							throw new Exception("UIVertex mode not set");
						}
						return ((UIVertex_2017*)(void*)ptr)->normal;
					}
					return ((UIVertex_2018*)(void*)ptr)->normal;
				}
				return ((UIVertex_2020*)(void*)ptr)->normal;
			}
		}

		public unsafe Vector4 tangent
		{
			get
			{
				if (mode != 2)
				{
					if (mode != 1)
					{
						if (mode != 0)
						{
							throw new Exception("UIVertex mode not set");
						}
						return ((UIVertex_2017*)(void*)ptr)->tangent;
					}
					return ((UIVertex_2018*)(void*)ptr)->tangent;
				}
				return ((UIVertex_2020*)(void*)ptr)->tangent;
			}
		}

		public unsafe Color32 color
		{
			get
			{
				if (mode != 2)
				{
					if (mode != 1)
					{
						if (mode != 0)
						{
							throw new Exception("UIVertex mode not set");
						}
						return ((UIVertex_2017*)(void*)ptr)->color;
					}
					return ((UIVertex_2018*)(void*)ptr)->color;
				}
				return ((UIVertex_2020*)(void*)ptr)->color;
			}
		}

		public unsafe Vector2 uv0
		{
			get
			{
				if (mode != 2)
				{
					if (mode != 1)
					{
						if (mode != 0)
						{
							throw new Exception("UIVertex mode not set");
						}
						return ((UIVertex_2017*)(void*)ptr)->uv0;
					}
					return ((UIVertex_2018*)(void*)ptr)->uv0;
				}
				return (Vector2)((UIVertex_2020*)(void*)ptr)->uv0;
			}
		}

		unsafe static UIVertexWrapper()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: 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_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)
			mode = -1;
			sizeOfElement = 0;
			UnityVersion engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[2] { "2020.2.0", "2021.1.0" }))
			{
				mode = 2;
				sizeOfElement = sizeof(UIVertex_2020);
				return;
			}
			engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[1] { "2018.1.0" }))
			{
				mode = 1;
				sizeOfElement = sizeof(UIVertex_2018);
				return;
			}
			engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[1] { "2017.2.0" }))
			{
				mode = 0;
				sizeOfElement = sizeof(UIVertex_2017);
			}
		}

		public UIVertexWrapper(IntPtr ptr)
		{
			this.ptr = ptr;
		}
	}
}
namespace MelonUnityEngine.Rendering
{
	internal static class VertexAttribute
	{
		public static int Vertex = 0;

		public static int Normal = 1;

		[NativeFieldValue(1u, NativeSignatureFlags.None, 7, new string[] { "2017.1.0" })]
		[NativeFieldValue(2u, NativeSignatureFlags.None, 2, new string[] { "2018.1.0" })]
		public static int Tangent = 0;

		[NativeFieldValue(1u, NativeSignatureFlags.None, 2, new string[] { "2017.1.0" })]
		[NativeFieldValue(2u, NativeSignatureFlags.None, 3, new string[] { "2018.1.0" })]
		public static int Color = 0;

		[NativeFieldValue(1u, NativeSignatureFlags.None, 3, new string[] { "2017.1.0" })]
		[NativeFieldValue(2u, NativeSignatureFlags.None, 4, new string[] { "2018.1.0" })]
		public static int TexCoord0 = 0;
	}
}
namespace MelonUnityEngine.CoreModule
{
	internal sealed class SystemInfo
	{
		private delegate uint d_GetGraphicsDeviceType();

		private static readonly d_GetGraphicsDeviceType m_GetGraphicsDeviceType;

		static SystemInfo()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			UnityVersion engineVersion = UnityInformationHandler.EngineVersion;
			if (NativeSignatureResolver.IsUnityVersionOverOrEqual(((UnityVersion)(ref engineVersion)).ToStringWithoutType(), new string[1] { "2018.1.0" }))
			{
				m_GetGraphicsDeviceType = UnityInternals.ResolveICall<d_GetGraphicsDeviceType>("UnityEngine.SystemInfo::GetGraphicsDeviceType");
			}
			else
			{
				m_GetGraphicsDeviceType = UnityInternals.ResolveICall<d_GetGraphicsDeviceType>("UnityEngine.SystemInfo::get_graphicsDeviceType");
			}
		}

		public static uint GetGraphicsDeviceType()
		{
			return m_GetGraphicsDeviceType();
		}
	}
}
namespace Il2CppSystem
{
	[StructLayout(LayoutKind.Explicit)]
	internal class Byte
	{
		[FieldOffset(0)]
		public byte m_value;

		static Byte()
		{
			InternalClassPointerStore<byte>.NativeClassPtr = UnityInternals.GetClass("mscorlib.dll", "System", "Byte");
			UnityInternals.runtime_class_init(InternalClassPointerStore<byte>.NativeClassPtr);
		}
	}
	[StructLayout(LayoutKind.Explicit)]
	internal class Int32
	{
		[FieldOffset(0)]
		public int m_value;

		static Int32()
		{
			InternalClassPointerStore<int>.NativeClassPtr = UnityInternals.GetClass("mscorlib.dll", "System", "Int32");
			UnityInternals.runtime_class_init(InternalClassPointerStore<int>.NativeClassPtr);
		}
	}
	internal class Type : InternalObjectBase
	{
		private static readonly IntPtr m_internal_from_handle;

		static Type()
		{
			InternalClassPointerStore<Type>.NativeClassPtr = UnityInternals.GetClass("mscorlib.dll", "System", "Type");
			m_internal_from_handle = UnityInternals.GetMethod(InternalClassPointerStore<Type>.NativeClassPtr, "internal_from_handle", "System.Type", "System.IntPtr");
		}

		public Type(IntPtr ptr)
			: base(ptr)
		{
		}

		public unsafe static Type internal_from_handle(IntPtr handle)
		{
			void** ptr = stackalloc void*[1];
			*ptr = &handle;
			IntPtr exc = default(IntPtr);
			IntPtr intPtr = UnityInternals.runtime_invoke(m_internal_from_handle, IntPtr.Zero, ptr, ref exc);
			Il2CppException.RaiseExceptionIfNecessary(exc);
			if (!(intPtr != IntPtr.Zero))
			{
				return null;
			}
			return new Type(intPtr);
		}
	}
}
namespace UnhollowerMini
{
	internal class Il2CppException : Exception
	{
		[ThreadStatic]
		private static byte[] ourMessageBytes;

		public static Func<IntPtr, string> ParseMessageHook;

		public Il2CppException(IntPtr exception)
			: base(BuildMessage(exception))
		{
		}

		private unsafe static string BuildMessage(IntPtr exception)
		{
			if (ParseMessageHook != null)
			{
				return ParseMessageHook(exception);
			}
			if (ourMessageBytes == null)
			{
				ourMessageBytes = new byte[65536];
			}
			fixed (byte* message = ourMessageBytes)
			{
				UnityInternals.format_exception(exception, message, ourMessageBytes.Length);
			}
			string @string = Encoding.UTF8.GetString(ourMessageBytes, 0, Array.IndexOf(ourMessageBytes, (byte)0));
			fixed (byte* output = ourMessageBytes)
			{
				UnityInternals.format_stack_trace(exception, output, ourMessageBytes.Length);
			}
			return @string + "\n" + Encoding.UTF8.GetString(ourMessageBytes, 0, Array.IndexOf(ourMessageBytes, (byte)0));
		}

		public static void RaiseExceptionIfNecessary(IntPtr returnedException)
		{
			if (returnedException == IntPtr.Zero)
			{
				return;
			}
			throw new Il2CppException(returnedException);
		}
	}
	internal static class InternalClassPointerStore<T>
	{
		public static IntPtr NativeClassPtr;

		public static System.Type CreatedTypeRedirect;

		static InternalClassPointerStore()
		{
			System.Type typeFromHandle = typeof(T);
			RuntimeHelpers.RunClassConstructor(typeFromHandle.TypeHandle);
			if (typeFromHandle.IsPrimitive || (object)typeFromHandle == typeof(string))
			{
				MelonDebug.Msg("Running class constructor on Il2Cpp" + typeFromHandle.FullName);
				RuntimeHelpers.RunClassConstructor(typeof(InternalClassPointerStore<>).Assembly.GetType("Il2Cpp" + typeFromHandle.FullName).TypeHandle);
				MelonDebug.Msg("Done running class constructor");
			}
		}
	}
	internal class InternalObjectBase
	{
		protected uint myGcHandle;

		public IntPtr Pointer
		{
			get
			{
				IntPtr intPtr = UnityInternals.gchandle_get_target(myGcHandle);
				if (intPtr == IntPtr.Zero)
				{
					throw new ObjectCollectedException("Object was garbage collected");
				}
				return intPtr;
			}
		}

		protected InternalObjectBase()
		{
		}

		public InternalObjectBase(IntPtr pointer)
		{
			if (pointer == IntPtr.Zero)
			{
				throw new NullReferenceException();
			}
			myGcHandle = UnityInternals.gchandle_new(pointer, pinned: false);
		}

		~InternalObjectBase()
		{
			UnityInternals.gchandle_free(myGcHandle);
		}
	}
	internal static class InternalType
	{
		public static Il2CppSystem.Type TypeFromPointer(IntPtr classPointer, string typeName = "<unknown type>")
		{
			if (classPointer == IntPtr.Zero)
			{
				throw new ArgumentException(typeName + " does not have a corresponding internal class pointer");
			}
			IntPtr intPtr = UnityInternals.class_get_type(classPointer);
			if (intPtr == IntPtr.Zero)
			{
				throw new ArgumentException(typeName + " does not have a corresponding class type pointer");
			}
			return Il2CppSystem.Type.internal_from_handle(intPtr);
		}

		public static Il2CppSystem.Type Of<T>()
		{
			return TypeFromPointer(InternalClassPointerStore<T>.NativeClassPtr, typeof(T).Name);
		}
	}
	internal class ObjectCollectedException : Exception
	{
		public ObjectCollectedException(string message)
			: base(message)
		{
		}
	}
	internal static class UnityInternals
	{
		private delegate void delegate_gfunc_mono_assembly_foreach(IntPtr assembly, IntPtr user_data);

		private class InternalAssembly
		{
			public IntPtr ptr;

			public string name;

			public InternalAssembly(IntPtr ptr)
			{
				this.ptr = ptr;
				if (MelonUtils.IsGameIl2Cpp())
				{
					name = Marshal.PtrToStringAnsi(il2cpp_image_get_filename(this.ptr));
				}
				else
				{
					name = Marshal.PtrToStringAnsi(mono_image_get_filename(this.ptr));
				}
			}
		}

		private class InternalClass
		{
			public IntPtr ptr;

			public string name;

			public string name_space;

			public InternalClass(IntPtr ptr)
			{
				this.ptr = ptr;
				if (MelonUtils.IsGameIl2Cpp())
				{
					name = Marshal.PtrToStringAnsi(il2cpp_class_get_name(ptr));
					name_space = Marshal.PtrToStringAnsi(il2cpp_class_get_namespace(ptr));
					return;
				}
				throw new NotImplementedException();
			}

			public InternalClass(IntPtr ptr, string name, string name_space)
			{
				if (MelonUtils.IsGameIl2Cpp())
				{
					throw new NotImplementedException();
				}
				this.ptr = ptr;
				this.name = name;
				this.name_space = name_space;
			}
		}

		private struct MonoMethod
		{
			public ushort flags;

			public ushort iflags;

			public uint token;

			public unsafe MonoClass* klass;

			public unsafe MonoMethodSignature* signature;

			public unsafe byte* name;

			public IntPtr method_pointer;

			public IntPtr invoke_pointer;

			public ushort bitfield;

			public int slot;

			internal unsafe void applyZeroes()
			{
				flags = 0;
				iflags = 0;
				token = 0u;
				klass = null;
				signature = null;
				name = null;
				method_pointer = IntPtr.Zero;
				invoke_pointer = IntPtr.Zero;
				bitfield = 0;
				slot = 0;
			}
		}

		private struct MonoMethodSignature
		{
			public IntPtr ret;

			public ushort param_cout;

			internal void ApplyZeroes()
			{
				ret = (IntPtr)0;
				param_cout = 0;
			}
		}

		private struct MonoClass
		{
			public unsafe MonoClass* element_class;

			public unsafe MonoClass* cast_class;

			public unsafe MonoClass** supertypes;

			public ushort idepth;

			public byte rank;

			public byte class_kind;

			public int instance_size;

			public uint bitfield1;

			public byte min_align;

			public uint bitfield2;

			private byte exception_type;

			public unsafe MonoClass* parent;

			public unsafe MonoClass* nested_in;

			public IntPtr nested_in_0x04;

			public IntPtr nested_in_0x08;

			public IntPtr nested_in_0x0C;

			public IntPtr nested_in_0x10;

			internal unsafe void applyZeroes()
			{
				element_class = null;
				cast_class = null;
				supertypes = null;
				idepth = 0;
				rank = 0;
				class_kind = 0;
				instance_size = 0;
				bitfield1 = 0u;
				min_align = 0;
				bitfield2 = 0u;
				exception_type = 0;
				parent = null;
				nested_in = null;
				nested_in_0x04 = (IntPtr)0;
				nested_in_0x08 = (IntPtr)0;
				nested_in_0x0C = (IntPtr)0;
				nested_in_0x10 = (IntPtr)0;
			}
		}

		private struct MonoType
		{
			public IntPtr data;

			public short attrs;

			public byte type;

			public byte bitflags;

			internal void applyZeroes()
			{
				data = (IntPtr)0;
				attrs = 0;
				type = 0;
				bitflags = 0;
			}
		}

		private static readonly IntPtr domain;

		private static readonly List<InternalAssembly> assemblies;

		private static readonly uint monoClassOffset;

		unsafe static UnityInternals()
		{
			assemblies = new List<InternalAssembly>();
			monoClassOffset = 0u;
			if (MelonUtils.IsGameIl2Cpp())
			{
				domain = il2cpp_domain_get();
				uint size = 0u;
				IntPtr* ptr = il2cpp_domain_get_assemblies(domain, ref size);
				for (int i = 0; i < size; i++)
				{
					assemblies.Add(new InternalAssembly(il2cpp_assembly_get_image(ptr[i])));
				}
				return;
			}
			domain = mono_domain_get();
			MonoClass* ptr2 = (MonoClass*)(void*)Marshal.AllocHGlobal(sizeof(MonoClass));
			ptr2->applyZeroes();
			ptr2->nested_in_0x04 = (IntPtr)4660;
			ptr2->nested_in_0x08 = (IntPtr)22136;
			ptr2->nested_in_0x0C = (IntPtr)36882;
			long num = (long)mono_class_get_name((IntPtr)ptr2);
			MelonDebug.Msg($"returnedName {num:X}");
			Marshal.FreeHGlobal((IntPtr)ptr2);
			switch (num)
			{
			case 4660L:
				monoClassOffset = 0u;
				break;
			case 22136L:
				monoClassOffset = (uint)IntPtr.Size;
				break;
			case 36882L:
				monoClassOffset = (uint)(IntPtr.Size * 2);
				break;
			default:
				throw new Exception("Failed to find MonoClass name offset");
			}
			MelonDebug.Msg("monoClassOffset? " + monoClassOffset);
		}

		internal unsafe static IntPtr GetClass(string assemblyname, string name_space, string classname)
		{
			MelonDebug.Msg("GetClass " + assemblyname + " " + name_space + " " + classname);
			if (MelonUtils.IsGameIl2Cpp())
			{
				IntPtr intPtr = il2cpp_class_from_name((assemblies.FirstOrDefault((InternalAssembly a) => a.name == assemblyname) ?? throw new Exception("Unable to find assembly " + assemblyname + " in il2cpp domain")).ptr, name_space, classname);
				MelonDebug.Msg($" > 0x{(long)intPtr:X}");
				return intPtr;
			}
			string text = (string.IsNullOrEmpty(name_space) ? "" : (name_space + "." + classname));
			System.Type type = (AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name + ".dll" == assemblyname) ?? throw new Exception("Unable to find assembly " + assemblyname + " in mono domain")).GetType(text);
			if ((object)type == null)
			{
				throw new Exception("Unable to find class " + text + " in assembly " + assemblyname);
			}
			MelonDebug.Msg($" > 0x{(long)(*(IntPtr*)(void*)type.TypeHandle.Value):X}");
			return *(IntPtr*)(void*)type.TypeHandle.Value;
		}

		public static IntPtr GetField(IntPtr clazz, string fieldName)
		{
			MelonDebug.Msg("GetField " + fieldName);
			if (clazz == IntPtr.Zero)
			{
				return IntPtr.Zero;
			}
			IntPtr intPtr = (MelonUtils.IsGameIl2Cpp() ? il2cpp_class_get_field_from_name(clazz, fieldName) : mono_class_get_field_from_name(clazz, fieldName));
			if (intPtr == IntPtr.Zero)
			{
				throw new Exception("Field " + fieldName + " was not found on class " + Marshal.PtrToStringAnsi(MelonUtils.IsGameIl2Cpp() ? il2cpp_class_get_name(clazz) : mono_class_get_name(clazz)));
			}
			MelonDebug.Msg($" > 0x{(long)intPtr:X}");
			return intPtr;
		}

		internal static IntPtr GetMethod(IntPtr clazz, string name, string returntype, params string[] parameters)
		{
			MelonDebug.Msg("GetMethod " + returntype + " " + name + "(" + string.Join(", ", parameters) + ")");
			if (MelonUtils.IsGameIl2Cpp())
			{
				IntPtr iter = IntPtr.Zero;
				IntPtr intPtr;
				while ((intPtr = il2cpp_class_get_methods(clazz, ref iter)) != IntPtr.Zero)
				{
					if (Marshal.PtrToStringAnsi(il2cpp_method_get_name(intPtr)) != name || Marshal.PtrToStringAnsi(il2cpp_type_get_name(il2cpp_method_get_return_type(intPtr))) != returntype || parameters.Length != il2cpp_method_get_param_count(intPtr))
					{
						continue;
					}
					bool flag = true;
					for (uint num = 0u; num < parameters.Length; num++)
					{
						if (Marshal.PtrToStringAnsi(il2cpp_type_get_name(il2cpp_method_get_param(intPtr, num))) != parameters[num])
						{
							flag = false;
							break;
						}
					}
					if (flag)
					{
						MelonDebug.Msg($" > 0x{(long)intPtr:X}");
						return intPtr;
					}
				}
			}
			else
			{
				IntPtr iter2 = IntPtr.Zero;
				IntPtr intPtr2;
				while ((intPtr2 = mono_class_get_methods(clazz, ref iter2)) != IntPtr.Zero)
				{
					if (Marshal.PtrToStringAnsi(mono_method_get_name(intPtr2)) != name)
					{
						continue;
					}
					IntPtr sig = mono_method_get_signature(intPtr2, IntPtr.Zero, 0u);
					if (Marshal.PtrToStringAnsi(mono_type_get_name(mono_signature_get_return_type(sig))) != returntype || parameters.Length != mono_signature_get_param_count(sig))
					{
						continue;
					}
					bool flag2 = true;
					IntPtr iter3 = IntPtr.Zero;
					int num2 = 0;
					IntPtr type;
					while ((type = mono_signature_get_params(sig, ref iter3)) != IntPtr.Zero)
					{
						if (Marshal.PtrToStringAnsi(mono_type_get_name(type)) != parameters[num2])
						{
							flag2 = false;
							break;
						}
						num2++;
					}
					if (flag2)
					{
						MelonDebug.Msg($" > 0x{(long)intPtr2:X}");
						return intPtr2;
					}
				}
			}
			throw new Exception("Unable to find method " + returntype + " " + name + "(" + string.Join(", ", parameters) + ")");
		}

		public static IntPtr ObjectBaseToPtr(InternalObjectBase obj)
		{
			return obj?.Pointer ?? IntPtr.Zero;
		}

		public static IntPtr ObjectBaseToPtrNotNull(InternalObjectBase obj)
		{
			if (obj == null)
			{
				throw new NullReferenceException();
			}
			return obj.Pointer;
		}

		public unsafe static IntPtr ManagedStringToInternal(string str)
		{
			if (str == null)
			{
				return IntPtr.Zero;
			}
			fixed (char* text = str)
			{
				if (!MelonUtils.IsGameIl2Cpp())
				{
					return mono_string_new_utf16(domain, text, str.Length);
				}
				return il2cpp_string_new_utf16(text, str.Length);
			}
		}

		public unsafe static IntPtr ResolveICall(string signature)
		{
			MelonDebug.Msg("Resolving ICall " + signature);
			IntPtr intPtr;
			if (MelonUtils.IsGameIl2Cpp())
			{
				intPtr = il2cpp_resolve_icall(signature);
			}
			else
			{
				MonoMethod* intPtr2 = IcallToFakeMonoMethod(signature);
				intPtr = mono_lookup_internal_call((IntPtr)intPtr2);
				DestroyFakeMonoMethod(intPtr2);
			}
			if (intPtr == IntPtr.Zero)
			{
				throw new Exception("ICall " + signature + " not resolved");
			}
			MelonDebug.Msg($" > 0x{(long)intPtr:X}");
			return intPtr;
		}

		public static T ResolveICall<T>(string signature) where T : Delegate
		{
			IntPtr intPtr = ResolveICall(signature);
			if (!(intPtr == IntPtr.Zero))
			{
				return (T)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(T));
			}
			return null;
		}

		private unsafe static MonoMethod* IcallToFakeMonoMethod(string icallName)
		{
			string[] array = icallName.Split(new string[1] { "::" }, StringSplitOptions.None);
			int num = array[1].IndexOf('(');
			if (num >= 0)
			{
				array[1] = array[1].Substring(0, num);
			}
			MonoMethod* ptr = (MonoMethod*)(void*)Marshal.AllocHGlobal(sizeof(MonoMethod) + 256);
			ptr->applyZeroes();
			ptr->klass = (MonoClass*)(void*)Marshal.AllocHGlobal(sizeof(MonoClass) + 256);
			ptr->klass->applyZeroes();
			ptr->name = (byte*)(void*)Marshal.StringToHGlobalAnsi(array[1]);
			int num2 = array[0].LastIndexOf('.');
			if (num2 < 0)
			{
				*(IntPtr*)((ulong)(&ptr->klass->nested_in_0x08) + (ulong)monoClassOffset) = Marshal.StringToHGlobalAnsi("");
				*(IntPtr*)((ulong)(&ptr->klass->nested_in_0x04) + (ulong)monoClassOffset) = Marshal.StringToHGlobalAnsi(array[0]);
			}
			else
			{
				string s = array[0].Substring(0, num2);
				string s2 = array[0].Substring(num2 + 1);
				*(IntPtr*)((ulong)(&ptr->klass->nested_in_0x08) + (ulong)monoClassOffset) = Marshal.StringToHGlobalAnsi(s);
				*(IntPtr*)((ulong)(&ptr->klass->nested_in_0x04) + (ulong)monoClassOffset) = Marshal.StringToHGlobalAnsi(s2);
			}
			MonoMethodSignature* ptr2 = (MonoMethodSignature*)(void*)Marshal.AllocHGlobal(sizeof(MonoMethodSignature));
			ptr2->ApplyZeroes();
			ptr->signature = ptr2;
			return ptr;
		}

		private unsafe static void DestroyFakeMonoMethod(MonoMethod* monoMethod)
		{
			Marshal.FreeHGlobal((IntPtr)monoMethod->signature);
			Marshal.FreeHGlobal(*(IntPtr*)((ulong)(&monoMethod->klass->nested_in_0x04) + (ulong)monoClassOffset));
			Marshal.FreeHGlobal(*(IntPtr*)((ulong)(&monoMethod->klass->nested_in_0x08) + (ulong)monoClassOffset));
			Marshal.FreeHGlobal((IntPtr)monoMethod->klass);
			Marshal.FreeHGlobal((IntPtr)monoMethod->name);
			Marshal.FreeHGlobal((IntPtr)monoMethod);
		}

		public static IntPtr class_get_type(IntPtr klass)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return mono_class_get_type(klass);
			}
			return il2cpp_class_get_type(klass);
		}

		public static void runtime_class_init(IntPtr klass)
		{
			if (klass == IntPtr.Zero)
			{
				throw new ArgumentException("Class to init is null");
			}
			if (MelonUtils.IsGameIl2Cpp())
			{
				il2cpp_runtime_class_init(klass);
			}
			else
			{
				mono_runtime_class_init(klass);
			}
		}

		public unsafe static IntPtr runtime_invoke(IntPtr method, IntPtr obj, void** param, ref IntPtr exc)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return mono_runtime_invoke(method, obj, param, ref exc);
			}
			return il2cpp_runtime_invoke(method, obj, param, ref exc);
		}

		public static IntPtr array_new(IntPtr elementTypeInfo, ulong length)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return mono_array_new(domain, elementTypeInfo, length);
			}
			return il2cpp_array_new(elementTypeInfo, length);
		}

		public unsafe static uint array_length(IntPtr array)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return *(uint*)((long)array + IntPtr.Size * 3);
			}
			return il2cpp_array_length(array);
		}

		public static uint field_get_offset(IntPtr field)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return mono_field_get_offset(field);
			}
			return il2cpp_field_get_offset(field);
		}

		public static IntPtr object_unbox(IntPtr obj)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return mono_object_unbox(obj);
			}
			return il2cpp_object_unbox(obj);
		}

		public static IntPtr object_new(IntPtr klass)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return mono_object_new(domain, klass);
			}
			return il2cpp_object_new(klass);
		}

		public static int class_value_size(IntPtr klass, ref uint align)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return mono_class_value_size(klass, ref align);
			}
			return il2cpp_class_value_size(klass, ref align);
		}

		public static uint gchandle_new(IntPtr obj, bool pinned)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return mono_gchandle_new(obj, pinned ? 1 : 0);
			}
			return il2cpp_gchandle_new(obj, pinned);
		}

		public static void gchandle_free(uint gchandle)
		{
			if (MelonUtils.IsGameIl2Cpp())
			{
				il2cpp_gchandle_free(gchandle);
			}
			else
			{
				mono_gchandle_free(gchandle);
			}
		}

		public static IntPtr gchandle_get_target(uint gchandle)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return mono_gchandle_get_target(gchandle);
			}
			return il2cpp_gchandle_get_target(gchandle);
		}

		public static IntPtr value_box(IntPtr klass, IntPtr val)
		{
			if (!MelonUtils.IsGameIl2Cpp())
			{
				return mono_value_box(domain, klass, val);
			}
			return il2cpp_value_box(klass, val);
		}

		public unsafe static void format_exception(IntPtr ex, void* message, int message_size)
		{
			if (MelonUtils.IsGameIl2Cpp())
			{
				il2cpp_format_exception(ex, message, message_size);
			}
		}

		public unsafe static void format_stack_trace(IntPtr ex, void* output, int output_size)
		{
			if (MelonUtils.IsGameIl2Cpp())
			{
				il2cpp_format_stack_trace(ex, output, output_size);
			}
		}

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_domain_get();

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern void mono_assembly_foreach(delegate_gfunc_mono_assembly_foreach func, IntPtr user_data);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_assembly_get_image(IntPtr assembly);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_image_get_filename(IntPtr image);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern uint mono_image_get_class_count(IntPtr image);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_image_get_class(IntPtr image, uint index);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_class_get_name(IntPtr klass);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_class_get_namespace(IntPtr klass);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_lookup_internal_call(IntPtr method);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		public static extern IntPtr mono_class_get_type(IntPtr klass);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private unsafe static extern IntPtr mono_runtime_invoke(IntPtr method, IntPtr obj, void** param, ref IntPtr exc);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern void mono_runtime_class_init(IntPtr klass);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_array_new(IntPtr domain, IntPtr eclass, ulong n);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern uint mono_field_get_offset(IntPtr field);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_object_unbox(IntPtr obj);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_object_new(IntPtr domain, IntPtr klass);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern int mono_class_value_size(IntPtr klass, ref uint align);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern uint mono_gchandle_new(IntPtr obj, int pinned);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern void mono_gchandle_free(uint gchandle);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_gchandle_get_target(uint gchandle);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_class_get_field_from_name(IntPtr klass, [MarshalAs(UnmanagedType.LPStr)] string name);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_value_box(IntPtr domain, IntPtr klass, IntPtr data);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_class_get_methods(IntPtr klass, ref IntPtr iter);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		public static extern IntPtr mono_method_get_name(IntPtr method);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_type_get_name(IntPtr type);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_image_get_table_info(IntPtr image, int table_id);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern int mono_table_info_get_rows(IntPtr table);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern void mono_metadata_decode_row(IntPtr t, int idx, uint[] res, int res_size);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_metadata_string_heap(IntPtr meta, uint index);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_class_from_name(IntPtr image, string name_space, string name);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_domain_try_type_resolve(IntPtr domain, string name, IntPtr typebuilder_raw);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_method_get_signature(IntPtr method, IntPtr image, uint token);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_signature_get_return_type(IntPtr sig);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern uint mono_signature_get_param_count(IntPtr sig);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr mono_signature_get_params(IntPtr sig, ref IntPtr iter);

		[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private unsafe static extern IntPtr mono_string_new_utf16(IntPtr domain, char* text, int len);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_domain_get();

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_resolve_icall([MarshalAs(UnmanagedType.LPStr)] string name);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern uint il2cpp_array_length(IntPtr array);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_array_new(IntPtr elementTypeInfo, ulong length);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_assembly_get_image(IntPtr assembly);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_class_get_field_from_name(IntPtr klass, [MarshalAs(UnmanagedType.LPStr)] string name);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_class_get_methods(IntPtr klass, ref IntPtr iter);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_class_get_name(IntPtr klass);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_class_get_namespace(IntPtr klass);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		public static extern IntPtr il2cpp_class_get_type(IntPtr klass);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern int il2cpp_class_value_size(IntPtr klass, ref uint align);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private unsafe static extern IntPtr* il2cpp_domain_get_assemblies(IntPtr domain, ref uint size);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private unsafe static extern void il2cpp_format_exception(IntPtr ex, void* message, int message_size);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private unsafe static extern void il2cpp_format_stack_trace(IntPtr ex, void* output, int output_size);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern uint il2cpp_field_get_offset(IntPtr field);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern uint il2cpp_gchandle_new(IntPtr obj, bool pinned);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_gchandle_get_target(uint gchandle);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern void il2cpp_gchandle_free(uint gchandle);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_method_get_return_type(IntPtr method);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern uint il2cpp_method_get_param_count(IntPtr method);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_method_get_param(IntPtr method, uint index);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		public static extern IntPtr il2cpp_method_get_name(IntPtr method);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_object_new(IntPtr klass);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_object_unbox(IntPtr obj);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_value_box(IntPtr klass, IntPtr data);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private unsafe static extern IntPtr il2cpp_runtime_invoke(IntPtr method, IntPtr obj, void** param, ref IntPtr exc);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern void il2cpp_runtime_class_init(IntPtr klass);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private unsafe static extern IntPtr il2cpp_string_new_utf16(char* text, int len);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_type_get_name(IntPtr type);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_image_get_filename(IntPtr image);

		[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
		private static extern IntPtr il2cpp_class_from_name(IntPtr image, string namespaze, string name);
	}
}
namespace mgGif
{
	internal class Decoder : IDisposable
	{
		private enum ImageFlag
		{
			Interlaced = 64,
			ColourTable = 128,
			TableSizeMask = 7,
			BitDepthMask = 112
		}

		private enum Block
		{
			Image = 44,
			Extension = 33,
			End = 59
		}

		private enum Extension
		{
			GraphicControl = 249,
			Comments = 254,
			PlainText = 1,
			ApplicationData = 255
		}

		private enum Disposal
		{
			None = 0,
			DoNotDispose = 4,
			RestoreBackground = 8,
			ReturnToPrevious = 12
		}

		private enum ControlFlags
		{
			HasTransparency = 1,
			DisposalMask = 12
		}

		public string Version;

		public ushort Width;

		public ushort Height;

		public Color32 BackgroundColour;

		private const uint NoCode = 65535u;

		private const ushort NoTransparency = ushort.MaxValue;

		private byte[] Input;

		private int D;

		private Color32[] GlobalColourTable;

		private Color32[] LocalColourTable;

		private Color32[] ActiveColourTable;

		private ushort TransparentIndex;

		private Image Image = new Image();

		private ushort ImageLeft;

		private ushort ImageTop;

		private ushort ImageWidth;

		private ushort ImageHeight;

		private Color32[] Output;

		private Color32[] PreviousImage;

		private readonly int[] Pow2 = new int[13]
		{
			1, 2, 4, 8, 16, 32, 64, 128, 256, 512,
			1024, 2048, 4096
		};

		private int[] Indices = new int[4096];

		private ushort[] Codes = new ushort[131072];

		private uint[] CurBlock = new uint[64];

		public Decoder(byte[] data)
			: this()
		{
			Load(data);
		}

		public Decoder Load(byte[] data)
		{
			Input = data;
			D = 0;
			GlobalColourTable = new Color32[256];
			LocalColourTable = new Color32[256];
			TransparentIndex = ushort.MaxValue;
			Output = null;
			PreviousImage = null;
			Image.Delay = 0;
			return this;
		}

		private byte ReadByte()
		{
			return Input[D++];
		}

		private ushort ReadUInt16()
		{
			return (ushort)(Input[D++] | (Input[D++] << 8));
		}

		private void ReadHeader()
		{
			if (Input == null || Input.Length <= 12)
			{
				throw new Exception("Invalid data");
			}
			Version = Encoding.ASCII.GetString(Input, 0, 6);
			D = 6;
			if (Version != "GIF87a" && Version != "GIF89a")
			{
				throw new Exception("Unsupported GIF version");
			}
			Width = ReadUInt16();
			Height = ReadUInt16();
			Image.Width = Width;
			Image.Height = Height;
			ImageFlag imageFlag = (ImageFlag)ReadByte();
			byte b = ReadByte();
			ReadByte();
			if (EnumExtensions.HasFlag((Enum)imageFlag, (Enum)ImageFlag.ColourTable))
			{
				ReadColourTable(GlobalColourTable, imageFlag);
			}
			BackgroundColour = GlobalColourTable[b];
		}

		public Image NextImage()
		{
			if (D == 0)
			{
				ReadHeader();
			}
			while (true)
			{
				switch ((Block)ReadByte())
				{
				case Block.Image:
				{
					Image image = ReadImageBlock();
					if (image != null)
					{
						return image;
					}
					break;
				}
				case Block.Extension:
					if (ReadByte() == 249)
					{
						ReadControlBlock();
					}
					else
					{
						SkipBlocks();
					}
					break;
				case Block.End:
					return null;
				default:
					throw new Exception("Unexpected block type");
				}
			}
		}

		private Color32[] ReadColourTable(Color32[] colourTable, ImageFlag flags)
		{
			int num = Pow2[(int)((flags & ImageFlag.TableSizeMask) + 1)];
			for (int i = 0; i < num; i++)
			{
				colourTable[i] = new Color32(Input[D++], Input[D++], Input[D++], byte.MaxValue);
			}
			return colourTable;
		}

		private void SkipBlocks()
		{
			for (byte b = Input[D++]; b != 0; b = Input[D++])
			{
				D += b;
			}
		}

		private void ReadControlBlock()
		{
			ReadByte();
			byte num = ReadByte();
			Image.Delay = ReadUInt16() * 10;
			byte transparentIndex = ReadByte();
			ReadByte();
			if (EnumExtensions.HasFlag((Enum)(ControlFlags)num, (Enum)ControlFlags.HasTransparency))
			{
				TransparentIndex = transparentIndex;
			}
			else
			{
				TransparentIndex = ushort.MaxValue;
			}
			switch ((Disposal)(num & 0xC))
			{
			default:
				PreviousImage = Output;
				break;
			case Disposal.RestoreBackground:
				Output = new Color32[Width * Height];
				break;
			case Disposal.ReturnToPrevious:
				Output = new Color32[Width * Height];
				if (PreviousImage != null)
				{
					Array.Copy(PreviousImage, Output, Output.Length);
				}
				break;
			}
		}

		private Image ReadImageBlock()
		{
			ImageLeft = ReadUInt16();
			ImageTop = ReadUInt16();
			ImageWidth = ReadUInt16();
			ImageHeight = ReadUInt16();
			ImageFlag imageFlag = (ImageFlag)ReadByte();
			if (ImageWidth == 0 || ImageHeight == 0)
			{
				return null;
	

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/Mono.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using MelonLoader;
using MelonLoader.Support.Preferences;
using Tomlet;
using Tomlet.Models;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("MelonLoader")]
[assembly: AssemblyDescription("MelonLoader")]
[assembly: AssemblyCompany("discord.gg/2Wn3N2P")]
[assembly: AssemblyProduct("MelonLoader")]
[assembly: AssemblyCopyright("Created by Lava Gang")]
[assembly: AssemblyTrademark("discord.gg/2Wn3N2P")]
[assembly: Guid("EE48CA52-CCD3-48A5-B507-91773672E216")]
[assembly: AssemblyFileVersion("0.5.7")]
[assembly: PatchShield]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.5.7.0")]
[module: UnverifiableCode]
namespace MelonLoader.Support
{
	internal static class Main
	{
		internal static ISupportModule_From Interface;

		internal static GameObject obj;

		internal static SM_Component component;

		private static ISupportModule_To Initialize(ISupportModule_From interface_from)
		{
			Interface = interface_from;
			UnityMappers.RegisterMappers();
			if (IsUnity53OrLower())
			{
				SM_Component.Create();
			}
			else
			{
				SceneHandler.Init();
			}
			return (ISupportModule_To)(object)new SupportModule_To();
		}

		private static bool IsUnity53OrLower()
		{
			try
			{
				Assembly assembly = Assembly.Load("UnityEngine");
				if ((object)assembly == null)
				{
					return true;
				}
				Type type = assembly.GetType("UnityEngine.SceneManagement.SceneManager");
				if ((object)type == null)
				{
					return true;
				}
				if ((object)type.GetEvent("sceneLoaded") == null)
				{
					return true;
				}
				return false;
			}
			catch
			{
				return true;
			}
		}
	}
	internal class SM_Component : MonoBehaviour
	{
		private bool isQuitting;

		private static MethodInfo SetAsLastSiblingMethod;

		static SM_Component()
		{
			try
			{
				SetAsLastSiblingMethod = typeof(Transform).GetMethod("SetAsLastSibling", BindingFlags.Instance | BindingFlags.Public);
			}
			catch (Exception arg)
			{
				MelonLogger.Warning($"Exception while Getting Transform.SetAsLastSibling: {arg}");
			}
		}

		internal static void Create()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			if (!((Object)(object)Main.component != (Object)null))
			{
				Main.obj = new GameObject();
				Object.DontDestroyOnLoad((Object)(object)Main.obj);
				((Object)Main.obj).hideFlags = (HideFlags)52;
				Main.component = (SM_Component)(object)Main.obj.AddComponent(typeof(SM_Component));
				Main.component.SiblingFix();
			}
		}

		private void SiblingFix()
		{
			SetAsLastSiblingMethod?.Invoke(((Component)this).gameObject.transform, new object[0]);
			SetAsLastSiblingMethod?.Invoke(((Component)this).transform, new object[0]);
		}

		internal void Destroy()
		{
			Object.Destroy((Object)(object)((Component)this).gameObject);
		}

		private void Start()
		{
			if (!((Object)(object)Main.component != (Object)null) || !((Object)(object)Main.component != (Object)(object)this))
			{
				SiblingFix();
				Main.Interface.OnApplicationLateStart();
			}
		}

		private void Awake()
		{
			if ((Object)(object)Main.component != (Object)null && (Object)(object)Main.component != (Object)(object)this)
			{
				return;
			}
			foreach (IEnumerator queuedCoroutine in SupportModule_To.QueuedCoroutines)
			{
				((MonoBehaviour)this).StartCoroutine(queuedCoroutine);
			}
			SupportModule_To.QueuedCoroutines.Clear();
		}

		private void Update()
		{
			if (!((Object)(object)Main.component != (Object)null) || !((Object)(object)Main.component != (Object)(object)this))
			{
				isQuitting = false;
				SiblingFix();
				SceneHandler.OnUpdate();
				Main.Interface.Update();
			}
		}

		private void OnDestroy()
		{
			if (!((Object)(object)Main.component != (Object)null) || !((Object)(object)Main.component != (Object)(object)this))
			{
				if (!isQuitting)
				{
					Create();
				}
				else
				{
					OnApplicationDefiniteQuit();
				}
			}
		}

		private void OnApplicationQuit()
		{
			if (!((Object)(object)Main.component != (Object)null) || !((Object)(object)Main.component != (Object)(object)this))
			{
				isQuitting = true;
				Main.Interface.Quit();
			}
		}

		private void OnApplicationDefiniteQuit()
		{
			Main.Interface.DefiniteQuit();
		}

		private void FixedUpdate()
		{
			if (!((Object)(object)Main.component != (Object)null) || !((Object)(object)Main.component != (Object)(object)this))
			{
				Main.Interface.FixedUpdate();
			}
		}

		private void LateUpdate()
		{
			if (!((Object)(object)Main.component != (Object)null) || !((Object)(object)Main.component != (Object)(object)this))
			{
				Main.Interface.LateUpdate();
			}
		}

		private void OnGUI()
		{
			if (!((Object)(object)Main.component != (Object)null) || !((Object)(object)Main.component != (Object)(object)this))
			{
				Main.Interface.OnGUI();
			}
		}
	}
	internal class SupportModule_To : ISupportModule_To
	{
		internal static readonly List<IEnumerator> QueuedCoroutines = new List<IEnumerator>();

		public object StartCoroutine(IEnumerator coroutine)
		{
			if ((Object)(object)Main.component != (Object)null)
			{
				return ((MonoBehaviour)Main.component).StartCoroutine(coroutine);
			}
			QueuedCoroutines.Add(coroutine);
			return coroutine;
		}

		public void StopCoroutine(object coroutineToken)
		{
			if ((Object)(object)Main.component == (Object)null)
			{
				QueuedCoroutines.Remove(coroutineToken as IEnumerator);
			}
			else
			{
				((MonoBehaviour)Main.component).StopCoroutine((Coroutine)((coroutineToken is Coroutine) ? coroutineToken : null));
			}
		}

		public void UnityDebugLog(string msg)
		{
			Debug.Log((object)msg);
		}
	}
	internal static class SceneHandler
	{
		internal class SceneInitEvent
		{
			internal int buildIndex;

			internal string name;

			internal bool wasLoadedThisTick;
		}

		private static Queue<SceneInitEvent> scenesLoaded = new Queue<SceneInitEvent>();

		internal static void Init()
		{
			try
			{
				SceneManager.sceneLoaded += OnSceneLoad;
			}
			catch (Exception arg)
			{
				MelonLogger.Error($"SceneManager.sceneLoaded override failed: {arg}");
			}
			try
			{
				SceneManager.sceneUnloaded += OnSceneUnload;
			}
			catch (Exception arg2)
			{
				MelonLogger.Error($"SceneManager.sceneUnloaded override failed: {arg2}");
			}
		}

		private static void OnSceneLoad(Scene scene, LoadSceneMode mode)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Main.obj == (Object)null)
			{
				SM_Component.Create();
			}
			if ((object)scene != null)
			{
				Main.Interface.OnSceneWasLoaded(((Scene)(ref scene)).buildIndex, ((Scene)(ref scene)).name);
				scenesLoaded.Enqueue(new SceneInitEvent
				{
					buildIndex = ((Scene)(ref scene)).buildIndex,
					name = ((Scene)(ref scene)).name
				});
			}
		}

		private static void OnSceneUnload(Scene scene)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if ((object)scene != null)
			{
				Main.Interface.OnSceneWasUnloaded(((Scene)(ref scene)).buildIndex, ((Scene)(ref scene)).name);
			}
		}

		internal static void OnUpdate()
		{
			if (scenesLoaded.Count <= 0)
			{
				return;
			}
			Queue<SceneInitEvent> queue = new Queue<SceneInitEvent>();
			SceneInitEvent sceneInitEvent = null;
			while (scenesLoaded.Count > 0 && (sceneInitEvent = scenesLoaded.Dequeue()) != null)
			{
				if (sceneInitEvent.wasLoadedThisTick)
				{
					Main.Interface.OnSceneWasInitialized(sceneInitEvent.buildIndex, sceneInitEvent.name);
					continue;
				}
				sceneInitEvent.wasLoadedThisTick = true;
				queue.Enqueue(sceneInitEvent);
			}
			while (queue.Count > 0 && (sceneInitEvent = queue.Dequeue()) != null)
			{
				scenesLoaded.Enqueue(sceneInitEvent);
			}
		}
	}
}
namespace MelonLoader.Support.Preferences
{
	internal static class UnityMappers
	{
		internal static void RegisterMappers()
		{
			TomletMain.RegisterMapper<Color>((Serialize<Color>)WriteColor, (Deserialize<Color>)ReadColor);
			TomletMain.RegisterMapper<Color32>((Serialize<Color32>)WriteColor32, (Deserialize<Color32>)ReadColor32);
			TomletMain.RegisterMapper<Vector2>((Serialize<Vector2>)WriteVector2, (Deserialize<Vector2>)ReadVector2);
			TomletMain.RegisterMapper<Vector3>((Serialize<Vector3>)WriteVector3, (Deserialize<Vector3>)ReadVector3);
			TomletMain.RegisterMapper<Vector4>((Serialize<Vector4>)WriteVector4, (Deserialize<Vector4>)ReadVector4);
			TomletMain.RegisterMapper<Quaternion>((Serialize<Quaternion>)WriteQuaternion, (Deserialize<Quaternion>)ReadQuaternion);
		}

		private static Color ReadColor(TomlValue value)
		{
			//IL_0017: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			float[] array = MelonPreferences.Mapper.ReadArray<float>(value);
			if (array == null || array.Length != 4)
			{
				return default(Color);
			}
			return new Color(array[0] / 255f, array[1] / 255f, array[2] / 255f, array[3] / 255f);
		}

		private static TomlValue WriteColor(Color value)
		{
			//IL_0008: 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_0026: 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)
			float[] array = new float[4]
			{
				value.r * 255f,
				value.g * 255f,
				value.b * 255f,
				value.a * 255f
			};
			return (TomlValue)(object)MelonPreferences.Mapper.WriteArray<float>(array);
		}

		private static Color32 ReadColor32(TomlValue value)
		{
			//IL_0017: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = MelonPreferences.Mapper.ReadArray<byte>(value);
			if (array == null || array.Length != 4)
			{
				return default(Color32);
			}
			return new Color32(array[0], array[1], array[2], array[3]);
		}

		private static TomlValue WriteColor32(Color32 value)
		{
			//IL_0008: 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_001a: 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)
			byte[] array = new byte[4] { value.r, value.g, value.b, value.a };
			return (TomlValue)(object)MelonPreferences.Mapper.WriteArray<byte>(array);
		}

		private static Vector2 ReadVector2(TomlValue value)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			float[] array = MelonPreferences.Mapper.ReadArray<float>(value);
			if (array == null || array.Length != 2)
			{
				return default(Vector2);
			}
			return new Vector2(array[0], array[1]);
		}

		private static TomlValue WriteVector2(Vector2 value)
		{
			//IL_0008: 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)
			float[] array = new float[2] { value.x, value.y };
			return (TomlValue)(object)MelonPreferences.Mapper.WriteArray<float>(array);
		}

		private static Vector3 ReadVector3(TomlValue value)
		{
			//IL_0017: 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: Unknown result type (might be due to invalid IL or missing references)
			float[] array = MelonPreferences.Mapper.ReadArray<float>(value);
			if (array == null || array.Length != 3)
			{
				return default(Vector3);
			}
			return new Vector3(array[0], array[1], array[2]);
		}

		private static TomlValue WriteVector3(Vector3 value)
		{
			//IL_0008: 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_001a: Unknown result type (might be due to invalid IL or missing references)
			float[] array = new float[3] { value.x, value.y, value.z };
			return (TomlValue)(object)MelonPreferences.Mapper.WriteArray<float>(array);
		}

		private static Vector4 ReadVector4(TomlValue value)
		{
			//IL_0017: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			float[] array = MelonPreferences.Mapper.ReadArray<float>(value);
			if (array == null || array.Length != 4)
			{
				return default(Vector4);
			}
			return new Vector4(array[0], array[1], array[2], array[3]);
		}

		private static TomlValue WriteVector4(Vector4 value)
		{
			//IL_0008: 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_001a: 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)
			float[] array = new float[4] { value.x, value.y, value.z, value.w };
			return (TomlValue)(object)MelonPreferences.Mapper.WriteArray<float>(array);
		}

		private static Quaternion ReadQuaternion(TomlValue value)
		{
			//IL_0017: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			float[] array = MelonPreferences.Mapper.ReadArray<float>(value);
			if (array == null || array.Length != 4)
			{
				return default(Quaternion);
			}
			return new Quaternion(array[0], array[1], array[2], array[3]);
		}

		private static TomlValue WriteQuaternion(Quaternion value)
		{
			//IL_0008: 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_001a: 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)
			float[] array = new float[4] { value.x, value.y, value.z, value.w };
			return (TomlValue)(object)MelonPreferences.Mapper.WriteArray<float>(array);
		}
	}
}

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/Muse_Dash_Mono.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using MelonLoader;
using MelonLoader.Modules;
using MelonLoader.MonoInternals;
using ModHelper;
using ModLoader;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("MelonLoader")]
[assembly: AssemblyDescription("MelonLoader")]
[assembly: AssemblyCompany("discord.gg/2Wn3N2P")]
[assembly: AssemblyProduct("MelonLoader")]
[assembly: AssemblyCopyright("Created by Lava Gang")]
[assembly: AssemblyTrademark("discord.gg/2Wn3N2P")]
[assembly: Guid("C268E68B-3DF1-4EE3-A49F-750A8F55B799")]
[assembly: AssemblyFileVersion("0.5.7")]
[assembly: PatchShield]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.5.7.0")]
[module: UnverifiableCode]
namespace ModLoader
{
	public class ModLoader
	{
		internal static List<IMod> mods = new List<IMod>();

		internal static Dictionary<string, Assembly> depends = new Dictionary<string, Assembly>();

		public static void LoadDependency(Assembly assembly)
		{
			string[] manifestResourceNames = assembly.GetManifestResourceNames();
			foreach (string text in manifestResourceNames)
			{
				string text2 = assembly.GetName().Name + ".Depends.";
				if (!text.StartsWith(text2) || !text.EndsWith(".dll"))
				{
					continue;
				}
				string text3 = text.Remove(text.LastIndexOf(".dll")).Remove(0, text2.Length);
				if (depends.ContainsKey(text3))
				{
					MelonLogger.Error("Dependency conflict: " + text3 + " First at: " + depends[text3].GetName().Name);
					continue;
				}
				Assembly value;
				using (Stream stream = assembly.GetManifestResourceStream(text))
				{
					byte[] array = new byte[stream.Length];
					stream.Read(array, 0, array.Length);
					value = Assembly.Load(array);
				}
				depends.Add(text3, value);
			}
		}
	}
}
namespace ModHelper
{
	public interface IMod
	{
		string Name { get; }

		string Description { get; }

		string Author { get; }

		string HomePage { get; }

		void DoPatching();
	}
	public static class ModLogger
	{
		public static void Debug(object obj)
		{
			StackFrame? frame = new StackTrace().GetFrame(1);
			string name = frame.GetMethod().ReflectedType.Name;
			string name2 = frame.GetMethod().Name;
			AddLog(name, name2, obj);
		}

		public static void AddLog(string className, string methodName, object obj)
		{
			MelonLogger.Msg($"[{className}:{methodName}]: {obj}");
		}
	}
}
namespace MelonLoader
{
	internal class MuseDashModWrapper : MelonMod
	{
		internal IMod modInstance;

		public override void OnInitializeMelon()
		{
			modInstance.DoPatching();
		}
	}
}
namespace MelonLoader.CompatibilityLayers
{
	internal class Muse_Dash_Mono_Module : MelonModule
	{
		public override void OnInitialize()
		{
			string[] obj = new string[2] { "ModHelper", "ModLoader" };
			Assembly assembly = typeof(Muse_Dash_Mono_Module).Assembly;
			string[] array = obj;
			for (int i = 0; i < array.Length; i++)
			{
				MonoResolveManager.GetAssemblyResolveInfo(array[i]).Override = assembly;
			}
			MelonAssembly.CustomMelonResolvers += Resolve;
		}

		private ResolvedMelons Resolve(Assembly asm)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			IEnumerable<Type> validTypes = MelonUtils.GetValidTypes(asm, (LemonFunc<Type, bool>)delegate(Type x)
			{
				Type[] interfaces = x.GetInterfaces();
				return interfaces != null && interfaces.Any() && interfaces.Contains(typeof(IMod));
			});
			if (validTypes != null && validTypes.Any())
			{
				List<MelonBase> list = new List<MelonBase>();
				List<RottenMelon> list2 = new List<RottenMelon>();
				foreach (Type item in validTypes)
				{
					RottenMelon rottenMelon;
					MelonBase val = LoadMod(asm, item, out rottenMelon);
					if (val != null)
					{
						list.Add(val);
					}
					else
					{
						list2.Add(rottenMelon);
					}
				}
				return new ResolvedMelons(list.ToArray(), list2.ToArray());
			}
			return new ResolvedMelons((MelonBase[])null, (RottenMelon[])null);
		}

		private MelonBase LoadMod(Assembly asm, Type modType, out RottenMelon rottenMelon)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			rottenMelon = null;
			IMod mod;
			try
			{
				mod = Activator.CreateInstance(modType) as IMod;
			}
			catch (Exception ex)
			{
				rottenMelon = new RottenMelon(modType, "Failed to create an instance of the MMDL Mod.", ex);
				return null;
			}
			string text = mod.Name;
			if (string.IsNullOrEmpty(text))
			{
				text = modType.FullName;
			}
			string text2 = asm.GetName().Version.ToString();
			if (string.IsNullOrEmpty(text2) || text2.Equals("0.0.0.0"))
			{
				text2 = "1.0.0.0";
			}
			MuseDashModWrapper museDashModWrapper = MelonBase.CreateWrapper<MuseDashModWrapper>(text, (string)null, text2, (MelonGameAttribute[])null, (MelonProcessAttribute[])null, 0, (ConsoleColor?)null, (ConsoleColor?)null, (string)null);
			museDashModWrapper.modInstance = mod;
			global::ModLoader.ModLoader.mods.Add(mod);
			global::ModLoader.ModLoader.LoadDependency(asm);
			return (MelonBase)(object)museDashModWrapper;
		}
	}
}

BooBoo Building/BepInEx/plugins/BepInEx-BepInEx_MLLoader/Preload.dll

Decompiled 9 months ago
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using MelonLoader.Support.Properties;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("MelonLoader")]
[assembly: AssemblyDescription("MelonLoader")]
[assembly: AssemblyCompany("discord.gg/2Wn3N2P")]
[assembly: AssemblyProduct("MelonLoader")]
[assembly: AssemblyCopyright("Created by Lava Gang")]
[assembly: AssemblyTrademark("discord.gg/2Wn3N2P")]
[assembly: Guid("08BE056B-C854-4F88-92E8-F3B39187B6AF")]
[assembly: AssemblyFileVersion("0.5.7")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.5.7.0")]
[module: UnverifiableCode]
namespace MelonLoader
{
	public static class BuildInfo
	{
		public const string Name = "MelonLoader";

		public const string Description = "MelonLoader";

		public const string Author = "Lava Gang";

		public const string Company = "discord.gg/2Wn3N2P";

		public const string Version = "0.5.7";
	}
}
namespace MelonLoader.Support
{
	internal static class Preload
	{
		private static void Initialize()
		{
			string path = string.Copy(GetManagedDirectory());
			string path2 = Path.Combine(path, "System.dll");
			if (!File.Exists(path2))
			{
				File.WriteAllBytes(path2, Resources.System);
			}
			string path3 = Path.Combine(path, "System.Core.dll");
			if (!File.Exists(path3))
			{
				File.WriteAllBytes(path3, Resources.System_Core);
			}
		}

		[MethodImpl(MethodImplOptions.InternalCall)]
		[return: MarshalAs(UnmanagedType.LPStr)]
		private static extern string GetManagedDirectory();
	}
}
namespace MelonLoader.Support.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

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

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

		internal static byte[] System => (byte[])ResourceManager.GetObject("System", resourceCulture);

		internal static byte[] System_Core => (byte[])ResourceManager.GetObject("System_Core", resourceCulture);

		internal Resources()
		{
		}
	}
}

BooBoo Building/BepInEx/plugins/bizzlemip-BiggerLobby/BiggerLobby.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.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BiggerLobby.Models;
using BiggerLobby.Patches;
using BiggerLobby.UI;
using Dissonance.Audio.Playback;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.BundleAPI;
using LC_API.ServerAPI;
using Microsoft.CodeAnalysis;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BiggerLobby")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Increase the max players to 50 in Lethal Company")]
[assembly: AssemblyFileVersion("2.6.0.0")]
[assembly: AssemblyInformationalVersion("2.6.0")]
[assembly: AssemblyProduct("BiggerLobby")]
[assembly: AssemblyTitle("BiggerLobby")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.6.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BiggerLobby
{
	public static class Helper
	{
		public static T[] ResizeArray<T>(T[] oldArray, int newSize)
		{
			if (oldArray.Length >= newSize)
			{
				return oldArray;
			}
			T[] array = new T[newSize];
			oldArray.CopyTo(array, 0);
			return array;
		}

		public static void ResizeList<T>(this List<T> list, int size, T element = default(T))
		{
			int count = list.Count;
			if (size < count)
			{
				list.RemoveRange(size, count - size);
			}
			else if (size > count)
			{
				if (size > list.Capacity)
				{
					list.Capacity = size;
				}
				list.AddRange(Enumerable.Repeat(element, size - count));
			}
		}
	}
	[BepInPlugin("BiggerLobby", "BiggerLobby", "2.6.0")]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin Instance;

		public static bool oldhastime;

		public static int MaxPlayers = 16;

		public static bool instantiating;

		public static NetworkObject[] PlayerObjects = (NetworkObject[])(object)new NetworkObject[0];

		public static Harmony _harmony;

		public static Harmony _harmony2;

		public static ConfigEntry<int>? _LoudnessMultiplier;

		public static bool Initialized = false;

		public static IDictionary<uint, NetworkObject> CustomNetObjects = new Dictionary<uint, NetworkObject>();

		private void Awake()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			Instance = this;
			_LoudnessMultiplier = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Player loudness", 1, "Default player loudness");
			_harmony = new Harmony("BiggerLobby");
			_harmony2 = new Harmony("BiggerLobbyA");
			_harmony.PatchAll(typeof(NonGamePatches));
			_harmony.PatchAll(typeof(NonGamePatches.InternalPatches));
			_harmony.PatchAll(typeof(NonGamePatches.InternalPatches2));
			CustomNetObjects.Clear();
			_harmony2.PatchAll(typeof(InternalPatch3));
			_harmony2.PatchAll(typeof(ListSizeTranspilers));
			_harmony2.PatchAll(typeof(PlayerObjects));
			((BaseUnityPlugin)this).Logger.LogInfo((object)"BiggerLobby loaded");
			BundleLoader.OnLoadedAssets = (OnLoadedAssetsDelegate)Delegate.Combine((Delegate?)(object)BundleLoader.OnLoadedAssets, (Delegate?)new OnLoadedAssetsDelegate(OnLoaded));
		}

		private void Start()
		{
			Initialize();
		}

		private void OnDestroy()
		{
			Initialize();
		}

		private void Initialize()
		{
			if (!Initialized)
			{
				Initialized = true;
				ModdedServer.SetServerModdedOnly();
			}
		}

		private void OnLoaded()
		{
			Object.op_Implicit((Object)(object)BundleLoader.GetLoadedAsset<AudioMixer>("assets/diagetic.mixer"));
		}

		public static int GetPlayerCount()
		{
			return MaxPlayers;
		}

		public static int GetPlayerCountMinusOne()
		{
			return MaxPlayers - 1;
		}

		public static PlayerControllerB[] GetRealPlayerScripts(StartOfRound startOfRound)
		{
			if ((Object)(object)startOfRound == (Object)null || startOfRound.allPlayerScripts == null)
			{
				return (PlayerControllerB[])(object)new PlayerControllerB[0];
			}
			return startOfRound.allPlayerScripts.Where((PlayerControllerB x) => x.isPlayerDead || x.isPlayerControlled).ToArray();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "BiggerLobby";

		public const string PLUGIN_NAME = "BiggerLobby";

		public const string PLUGIN_VERSION = "2.6.0";
	}
}
namespace BiggerLobby.UI
{
	public class ExpandedStatsUI : MonoBehaviour
	{
		private bool _initialized;

		private bool _debugStatsUI;

		private static StatsUIReferences? _statsUIReferences;

		private PlayerStatsList _fourPlayersList;

		private PlayerStatsList _eightPlayersList;

		private PlayerStatsList _moreThanEightPlayersList;

		private List<GameObject> _moreThanEightPlayersPages = new List<GameObject>();

		public int UpperPlayerLimit = 40;

		public float SecondsPanelVisible = 8.5f;

		private Sprite FourPlayerStatBoxes;

		private Sprite EightPlayerStatBoxes;

		private void Start()
		{
			if (!_initialized)
			{
				if (_debugStatsUI)
				{
					DebugStats();
				}
				SetupFourPlayerSlots();
				SetupEightPlayerSlots();
				SetupMoreThanEightPlayersSlots();
				EightPlayerStatBoxes = _statsUIReferences.StatsBoxesThin;
				FourPlayerStatBoxes = ((Component)((Component)this).transform.GetChild(1)).GetComponent<Image>().sprite;
				((Component)this).transform.GetChild(2).Find("AllDead").SetAsLastSibling();
				_initialized = true;
			}
		}

		private void DebugStats()
		{
			((Behaviour)((Component)this).gameObject.GetComponent<Animator>()).enabled = false;
			((Component)((Component)this).transform.GetChild(0)).GetComponent<CanvasGroup>().alpha = 1f;
			((Component)((Component)this).transform.GetChild(1)).GetComponent<CanvasGroup>().alpha = 1f;
			((Component)((Component)this).transform.GetChild(2)).GetComponent<CanvasGroup>().alpha = 1f;
			((Component)((Component)this).transform.GetChild(2).Find("AllDead")).gameObject.SetActive(false);
		}

		private void SetupFourPlayerSlots()
		{
			_fourPlayersList = new PlayerStatsList(CreateTransformAtParentOrigin("FourPlayersList", ((Component)this).transform.GetChild(2)));
			for (int i = 0; i < 4; i++)
			{
				Transform val = ((Component)this).transform.GetChild(2).Find($"PlayerSlot{i + 1}");
				val.SetParent(_fourPlayersList.transform);
				_fourPlayersList.AddPlayerSlotTransform(val);
			}
		}

		private void SetupEightPlayerSlots()
		{
			_eightPlayersList = new PlayerStatsList(CreateTransformAtParentOrigin("EightPlayersList", ((Component)this).transform.GetChild(2)));
			List<Transform> playerSlots = SetupEightPlayerPage(_eightPlayersList.transform);
			_eightPlayersList.AddPlayerSlotTransforms(playerSlots);
		}

		private void SetupMoreThanEightPlayersSlots()
		{
			_moreThanEightPlayersList = new PlayerStatsList(CreateTransformAtParentOrigin("MoreThanEightPlayersList", ((Component)this).transform.GetChild(2)));
			int num = (int)Math.Ceiling((float)UpperPlayerLimit / 8f);
			for (int i = 0; i < num; i++)
			{
				Transform val = CreateTransformAtParentOrigin($"Page{i}", _moreThanEightPlayersList.transform);
				_moreThanEightPlayersPages.Add(((Component)val).gameObject);
				List<Transform> playerSlots = SetupEightPlayerPage(val);
				_moreThanEightPlayersList.AddPlayerSlotTransforms(playerSlots);
				if (i != 0)
				{
					((Component)val).gameObject.SetActive(false);
				}
			}
		}

		private List<Transform> SetupEightPlayerPage(Transform parent)
		{
			//IL_002c: 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_0049: Unknown result type (might be due to invalid IL or missing references)
			List<Transform> list = new List<Transform>();
			for (int i = 0; i < 8; i++)
			{
				Transform val = Object.Instantiate<Transform>(_fourPlayersList.transform.GetChild(0), parent, true);
				SetupPlayerSlot(val);
				val.localPosition = new Vector3(val.localPosition.x, -26.1f * (float)i, val.localPosition.z);
				list.Add(val);
			}
			return list;
		}

		private void SetupPlayerSlot(Transform playerSlot)
		{
			//IL_005a: 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_0074: 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_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: 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)
			TextMeshProUGUI component = ((Component)playerSlot.Find("Notes")).GetComponent<TextMeshProUGUI>();
			TextMeshProUGUI component2 = ((Component)playerSlot.GetChild(0)).GetComponent<TextMeshProUGUI>();
			RectTransform component3 = ((Component)component2).GetComponent<RectTransform>();
			Image component4 = ((Component)playerSlot.GetChild(1)).GetComponent<Image>();
			RectTransform component5 = ((Component)component4).GetComponent<RectTransform>();
			((TMP_Text)component).text = "* Most lazy employee\n* Most paranoid employee\n* Sustained the most injuries";
			((TMP_Text)component).fontSize = 9f;
			((TMP_Text)component2).text = "CrazyDude12WW";
			((Transform)component3).localPosition = new Vector3(((Transform)component3).localPosition.x, 101.5f, ((Transform)component3).localPosition.z);
			component4.sprite = _statsUIReferences.CheckmarkThin;
			component5.sizeDelta = new Vector2(component5.sizeDelta.x, 31.235f);
			((Transform)component5).localPosition = new Vector3(((Transform)component5).localPosition.x, 101.5f, ((Transform)component5).localPosition.z);
		}

		private Transform CreateTransformAtParentOrigin(string name, Transform parent)
		{
			//IL_0001: 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_001e: 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)
			Transform transform = new GameObject(name).transform;
			transform.SetParent(parent);
			transform.localPosition = Vector3.zero;
			transform.localRotation = Quaternion.identity;
			transform.localScale = Vector3.one;
			return transform;
		}

		public void LoadStatsUIBundle()
		{
			AssetBundle obj = AssetBundle.LoadFromFile(Path.Join((ReadOnlySpan<char>)Path.GetDirectoryName(((BaseUnityPlugin)Plugin.Instance).Info.Location), (ReadOnlySpan<char>)"statsuireferences"));
			_statsUIReferences = obj.LoadAsset<GameObject>("assets/prefabs/statsuireferences.prefab").GetComponent<StatsUIReferences>();
			obj.Unload(false);
		}

		public PlayerStatsList GetStatsListFromPlayerCount(int playerCount)
		{
			_fourPlayersList.gameObject.SetActive(false);
			_eightPlayersList.gameObject.SetActive(false);
			_moreThanEightPlayersList.gameObject.SetActive(false);
			PlayerStatsList playerStatsList = _fourPlayersList;
			if (playerCount > 8)
			{
				playerStatsList = _moreThanEightPlayersList;
			}
			else if (playerCount > 4)
			{
				playerStatsList = _eightPlayersList;
			}
			SetupStatsList(playerStatsList, playerCount);
			return playerStatsList;
		}

		private void SetupStatsList(PlayerStatsList playerStatsList, int playerCount)
		{
			playerStatsList.gameObject.SetActive(true);
			((Component)((Component)this).transform.GetChild(1)).GetComponent<Image>().sprite = ((playerCount <= 4) ? FourPlayerStatBoxes : EightPlayerStatBoxes);
			if (playerCount > 8)
			{
				((MonoBehaviour)this).StartCoroutine(PaginatePlayers(playerCount));
			}
			for (int i = 0; i < playerStatsList.Names.Count; i++)
			{
				((TMP_Text)playerStatsList.Names[i]).text = "";
				((TMP_Text)playerStatsList.Notes[i]).text = "";
				((Behaviour)playerStatsList.States[i]).enabled = false;
			}
		}

		private IEnumerator PaginatePlayers(int playerCount)
		{
			int maxPageCount = (int)Math.Ceiling((float)playerCount / 8f);
			float pageDuration = SecondsPanelVisible / (float)maxPageCount;
			foreach (GameObject moreThanEightPlayersPage in _moreThanEightPlayersPages)
			{
				moreThanEightPlayersPage.SetActive(false);
			}
			for (int i = 0; i < maxPageCount; i++)
			{
				_moreThanEightPlayersPages[i].SetActive(true);
				if (i > 0)
				{
					_moreThanEightPlayersPages[i - 1].SetActive(false);
				}
				yield return (object)new WaitForSeconds(pageDuration);
			}
		}

		public static ExpandedStatsUI GetFromAnimator(Animator endgameStatsAnimator)
		{
			ExpandedStatsUI result = default(ExpandedStatsUI);
			if (((Component)endgameStatsAnimator).TryGetComponent<ExpandedStatsUI>(ref result))
			{
				return result;
			}
			ExpandedStatsUI expandedStatsUI = ((Component)endgameStatsAnimator).gameObject.AddComponent<ExpandedStatsUI>();
			if ((Object)(object)_statsUIReferences == (Object)null)
			{
				expandedStatsUI.LoadStatsUIBundle();
			}
			return expandedStatsUI;
		}

		public static Sprite? GetReplacementCheckmark()
		{
			return _statsUIReferences?.CheckmarkThin;
		}
	}
}
namespace BiggerLobby.Patches
{
	[HarmonyPatch(typeof(HUDManager))]
	internal class InternalPatch3
	{
		private static MethodInfo TargetMethod()
		{
			return typeof(HUDManager).GetMethod("AddChatMessage", BindingFlags.Instance | BindingFlags.NonPublic);
		}

		[HarmonyPrefix]
		private static void Prefix(HUDManager __instance, string chatMessage, string nameOfUserWhoTyped = "")
		{
			if (!(__instance.lastChatMessage == chatMessage))
			{
				__instance.lastChatMessage = chatMessage;
				__instance.PingHUDElement(__instance.Chat, 4f, 1f, 0.2f);
				if (__instance.ChatMessageHistory.Count >= 4)
				{
					((TMP_Text)__instance.chatText).text.Remove(0, __instance.ChatMessageHistory[0].Length);
					__instance.ChatMessageHistory.Remove(__instance.ChatMessageHistory[0]);
				}
				StringBuilder stringBuilder = new StringBuilder(chatMessage);
				for (int i = 1; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
				{
					stringBuilder.Replace("[playerNum" + i + "]", StartOfRound.Instance.allPlayerScripts[i].playerUsername);
				}
				stringBuilder.Replace("bizzlemip", "<color=#008282>bizzlemip</color>");
				chatMessage = stringBuilder.ToString();
				nameOfUserWhoTyped = nameOfUserWhoTyped.Replace("bizzlemip", "<color=#008282>bizzlemip</color>");
				string item = ((!string.IsNullOrEmpty(nameOfUserWhoTyped)) ? ("<color=#FF0000>" + nameOfUserWhoTyped + "</color>: <color=#FFFF00>'" + chatMessage + "'</color>") : ("<color=#7069ff>" + chatMessage + "</color>"));
				__instance.ChatMessageHistory.Add(item);
				((TMP_Text)__instance.chatText).text = "";
				for (int j = 0; j < __instance.ChatMessageHistory.Count; j++)
				{
					TextMeshProUGUI chatText = __instance.chatText;
					((TMP_Text)chatText).text = ((TMP_Text)chatText).text + "\n" + __instance.ChatMessageHistory[j];
				}
			}
		}
	}
	[HarmonyPatch]
	public class ListSizeTranspilers
	{
		private static MethodInfo _playerCountMethod = AccessTools.Method(typeof(Plugin), "GetPlayerCount", (Type[])null, (Type[])null);

		private static MethodInfo _playerCountMinusOneMethod = AccessTools.Method(typeof(Plugin), "GetPlayerCountMinusOne", (Type[])null, (Type[])null);

		private static MethodInfo _realPlayerScriptsMethod = AccessTools.Method(typeof(Plugin), "GetRealPlayerScripts", (Type[])null, (Type[])null);

		private static void CheckAndReplace(List<CodeInstruction> codes, int index)
		{
			if (codes[index].opcode == OpCodes.Ldc_I4_4)
			{
				codes[index].opcode = OpCodes.Call;
				codes[index].operand = _playerCountMethod;
			}
		}

		[HarmonyPatch(typeof(HUDManager), "SyncAllPlayerLevelsServerRpc", new Type[] { })]
		[HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")]
		[HarmonyPatch(typeof(CrawlerAI), "Start")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> SyncLevelsRpc(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Newarr)
				{
					CheckAndReplace(list, i - 1);
				}
			}
			return list.AsEnumerable();
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesServerRpc")]
		[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")]
		[HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")]
		[HarmonyPatch(typeof(EnemyAI), "GetClosestPlayer")]
		[HarmonyPatch(typeof(SpringManAI), "DoAIInterval")]
		[HarmonyPatch(typeof(SpringManAI), "Update")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> SendNewPlayerValuesServerRpc(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Blt)
				{
					CheckAndReplace(list, i - 1);
				}
			}
			return list.AsEnumerable();
		}

		[HarmonyPatch(typeof(QuickMenuManager), "ConfirmKickUserFromServer")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> ConfirmKickUserFromServer(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldc_I4_3)
				{
					list[i].opcode = OpCodes.Call;
					list[i].operand = _playerCountMinusOneMethod;
					Debug.Log((object)"Kick Fix Applied");
					break;
				}
			}
			return list.AsEnumerable();
		}

		[HarmonyPatch(typeof(HUDManager), "FillEndGameStats")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> FillEndGameStatsPatch(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldfld && list[i].operand is FieldInfo fieldInfo && fieldInfo.Name == "allPlayerScripts")
				{
					list[i].opcode = OpCodes.Call;
					list[i].operand = _realPlayerScriptsMethod;
				}
			}
			return list.Where((CodeInstruction x) => x.opcode != OpCodes.Nop).AsEnumerable();
		}

		[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesServerRpc")]
		[HarmonyPatch(typeof(StartOfRound), "OnClientConnect")]
		[HarmonyPatch(typeof(PlayerControllerB), "SpectateNextPlayer")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> SyncShipUnlockablesServerRpc(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldc_I4_4)
				{
					list[i].opcode = OpCodes.Call;
					list[i].operand = _playerCountMethod;
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch]
	public class NonGamePatches
	{
		[HarmonyPatch(typeof(GameNetworkManager))]
		internal class InternalPatches
		{
			private static MethodInfo TargetMethod()
			{
				return typeof(GameNetworkManager).GetMethod("ConnectionApproval", BindingFlags.Instance | BindingFlags.NonPublic);
			}

			[HarmonyPrefix]
			private static bool PostFix(GameNetworkManager __instance, ConnectionApprovalRequest request, ConnectionApprovalResponse response)
			{
				//IL_000a: 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_004d: 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)
				Debug.Log((object)("Connection approval callback! Game version of client request: " + Encoding.ASCII.GetString(request.Payload).ToString()));
				Debug.Log((object)$"Joining client id: {request.ClientNetworkId}; Local/host client id: {NetworkManager.Singleton.LocalClientId}");
				if (request.ClientNetworkId == NetworkManager.Singleton.LocalClientId)
				{
					Debug.Log((object)"Stopped connection approval callback, as the client in question was the host!");
					return false;
				}
				bool flag = !__instance.disallowConnection;
				if (flag)
				{
					string @string = Encoding.ASCII.GetString(request.Payload);
					string[] array = @string.Split(",");
					if (string.IsNullOrEmpty(@string))
					{
						response.Reason = "Unknown; please verify your game files.";
						flag = false;
					}
					else if (__instance.gameHasStarted)
					{
						response.Reason = "Game has already started!";
						flag = false;
					}
					else if (__instance.gameVersionNum.ToString() != array[0])
					{
						response.Reason = $"Game version mismatch! Their version: {__instance.gameVersionNum}. Your version: {array[0]}";
						flag = false;
					}
					else if (!__instance.disableSteam && ((Object)(object)StartOfRound.Instance == (Object)null || array.Length < 2 || StartOfRound.Instance.KickedClientIds.Contains((ulong)Convert.ToInt64(array[1]))))
					{
						response.Reason = "You cannot rejoin after being kicked.";
						flag = false;
					}
					else if (!@string.Contains("BiggerLobbyVersion2.5.0"))
					{
						response.Reason = "You need to have <color=#008282>BiggerLobby V2.5.0</color> to join this server!";
						flag = false;
					}
				}
				else
				{
					response.Reason = "The host was not accepting connections.";
				}
				Debug.Log((object)$"Approved connection?: {flag}. Connected players #: {__instance.connectedPlayers}");
				Debug.Log((object)("Disapproval reason: " + response.Reason));
				response.CreatePlayerObject = false;
				response.Approved = flag;
				response.Pending = false;
				return false;
			}
		}

		[HarmonyPatch(typeof(GameNetworkManager))]
		internal class InternalPatches2
		{
			private static MethodInfo TargetMethod()
			{
				return typeof(GameNetworkManager).GetMethod("SteamMatchmaking_OnLobbyCreated", BindingFlags.Instance | BindingFlags.NonPublic);
			}

			[HarmonyPostfix]
			private static void PostFix(GameNetworkManager __instance, Result result, Lobby lobby)
			{
				((Lobby)(ref lobby)).SetData("name", "[BiggerLobby]" + ((Lobby)(ref lobby)).GetData("name"));
			}
		}

		private static PropertyInfo _playbackVolumeProperty = typeof(VoicePlayback).GetInterface("IVoicePlaybackInternal").GetProperty("PlaybackVolume");

		private static FieldInfo _lobbyListField = AccessTools.Field(typeof(SteamLobbyManager), "currentLobbyList");

		[HarmonyPatch(typeof(StartOfRound), "UpdatePlayerVoiceEffects")]
		[HarmonyPrefix]
		public static void UpdatePlayerVoiceEffects(StartOfRound __instance)
		{
			if ((Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null)
			{
				return;
			}
			typeof(StartOfRound).GetField("updatePlayerVoiceInterval", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(__instance, 2f);
			PlayerControllerB val = ((!GameNetworkManager.Instance.localPlayerController.isPlayerDead || !((Object)(object)GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript != (Object)null)) ? GameNetworkManager.Instance.localPlayerController : GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript);
			for (int i = 0; i < __instance.allPlayerScripts.Length; i++)
			{
				PlayerControllerB val2 = __instance.allPlayerScripts[i];
				if ((!val2.isPlayerControlled && !val2.isPlayerDead) || (Object)(object)val2 == (Object)(object)GameNetworkManager.Instance.localPlayerController)
				{
					continue;
				}
				if (val2.voicePlayerState == null || val2.currentVoiceChatIngameSettings._playerState == null || (Object)(object)val2.currentVoiceChatAudioSource == (Object)null)
				{
					__instance.RefreshPlayerVoicePlaybackObjects();
					if (val2.voicePlayerState == null || (Object)(object)val2.currentVoiceChatAudioSource == (Object)null)
					{
						Debug.Log((object)$"Was not able to access voice chat object for player #{i}; {val2.voicePlayerState == null}; {(Object)(object)val2.currentVoiceChatAudioSource == (Object)null}");
						continue;
					}
				}
				AudioSource currentVoiceChatAudioSource = __instance.allPlayerScripts[i].currentVoiceChatAudioSource;
				bool flag = val2.speakingToWalkieTalkie && val.holdingWalkieTalkie && (Object)(object)val2 != (Object)(object)val;
				if (val2.isPlayerDead)
				{
					((Behaviour)((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>()).enabled = false;
					((Behaviour)((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>()).enabled = false;
					currentVoiceChatAudioSource.panStereo = 0f;
					SoundManager.Instance.playerVoicePitchTargets[val2.playerClientId] = 1f;
					SoundManager.Instance.SetPlayerPitch(1f, (int)val2.playerClientId);
					if (GameNetworkManager.Instance.localPlayerController.isPlayerDead)
					{
						currentVoiceChatAudioSource.spatialBlend = 0f;
						val2.currentVoiceChatIngameSettings.set2D = true;
						if ((Object)(object)val2.currentVoiceChatIngameSettings != (Object)null && (Object)(object)val2.currentVoiceChatIngameSettings._playbackComponent != (Object)null)
						{
							_playbackVolumeProperty.SetValue(val2.currentVoiceChatIngameSettings._playbackComponent, Mathf.Clamp((SoundManager.Instance.playerVoiceVolumes[i] + 1f) * (float)(2 * Plugin._LoudnessMultiplier.Value), 0f, 1f));
						}
					}
					else
					{
						currentVoiceChatAudioSource.spatialBlend = 1f;
						val2.currentVoiceChatIngameSettings.set2D = false;
						if ((Object)(object)val2.currentVoiceChatIngameSettings != (Object)null && (Object)(object)val2.currentVoiceChatIngameSettings._playbackComponent != (Object)null)
						{
							_playbackVolumeProperty.SetValue(val2.currentVoiceChatIngameSettings._playbackComponent, 0);
						}
					}
					continue;
				}
				AudioLowPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>();
				OccludeAudio component2 = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>();
				((Behaviour)component).enabled = true;
				component2.overridingLowPass = flag || __instance.allPlayerScripts[i].voiceMuffledByEnemy;
				((Behaviour)((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>()).enabled = flag;
				if (!flag)
				{
					currentVoiceChatAudioSource.spatialBlend = 1f;
					val2.currentVoiceChatIngameSettings.set2D = false;
					currentVoiceChatAudioSource.bypassListenerEffects = false;
					currentVoiceChatAudioSource.bypassEffects = false;
					currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[val2.playerClientId];
					component.lowpassResonanceQ = 1f;
				}
				else
				{
					currentVoiceChatAudioSource.spatialBlend = 0f;
					val2.currentVoiceChatIngameSettings.set2D = true;
					if (GameNetworkManager.Instance.localPlayerController.isPlayerDead)
					{
						currentVoiceChatAudioSource.panStereo = 0f;
						currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[val2.playerClientId];
						currentVoiceChatAudioSource.bypassListenerEffects = false;
						currentVoiceChatAudioSource.bypassEffects = false;
					}
					else
					{
						currentVoiceChatAudioSource.panStereo = 0.4f;
						currentVoiceChatAudioSource.bypassListenerEffects = false;
						currentVoiceChatAudioSource.bypassEffects = false;
						currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[val2.playerClientId];
					}
					component2.lowPassOverride = 4000f;
					component.lowpassResonanceQ = 3f;
				}
				if ((Object)(object)val2.currentVoiceChatIngameSettings != (Object)null && (Object)(object)val2.currentVoiceChatIngameSettings._playbackComponent != (Object)null)
				{
					_playbackVolumeProperty.SetValue(val2.currentVoiceChatIngameSettings._playbackComponent, Mathf.Clamp((SoundManager.Instance.playerVoiceVolumes[i] + 1f) * (float)(2 * Plugin._LoudnessMultiplier.Value), 0f, 1f));
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		public static void ResizeLists(ref StartOfRound __instance)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			__instance.allPlayerObjects = Helper.ResizeArray(__instance.allPlayerObjects, Plugin.MaxPlayers);
			__instance.allPlayerScripts = Helper.ResizeArray(__instance.allPlayerScripts, Plugin.MaxPlayers);
			__instance.gameStats.allPlayerStats = Helper.ResizeArray(__instance.gameStats.allPlayerStats, Plugin.MaxPlayers);
			__instance.playerSpawnPositions = Helper.ResizeArray(__instance.playerSpawnPositions, Plugin.MaxPlayers);
			for (int i = 4; i < Plugin.MaxPlayers; i++)
			{
				__instance.gameStats.allPlayerStats[i] = new PlayerStats();
				__instance.playerSpawnPositions[i] = __instance.playerSpawnPositions[0];
			}
		}

		[HarmonyPatch(typeof(HUDManager), "Awake")]
		[HarmonyPrefix]
		public static void ResizeHUD(ref HUDManager __instance)
		{
			ExpandedStatsUI.GetFromAnimator(__instance.endgameStatsAnimator);
		}

		[HarmonyPatch(typeof(SoundManager), "SetPlayerVoiceFilters")]
		[HarmonyPrefix]
		public static bool SetPlayerVoiceFilters(ref SoundManager __instance)
		{
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				if (!StartOfRound.Instance.allPlayerScripts[i].isPlayerControlled && !StartOfRound.Instance.allPlayerScripts[i].isPlayerDead)
				{
					__instance.playerVoicePitches[i] = 1f;
					__instance.playerVoiceVolumes[i] = 1f;
					continue;
				}
				if (StartOfRound.Instance.allPlayerScripts[i].voicePlayerState != null)
				{
					typeof(VoicePlayback).GetProperty("Dissonance.Audio.Playback.IVoicePlaybackInternal.PlaybackVolume", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(StartOfRound.Instance.allPlayerScripts[i].currentVoiceChatIngameSettings._playbackComponent, Mathf.Clamp((SoundManager.Instance.playerVoiceVolumes[i] + 1f) * (float)(2 * Plugin._LoudnessMultiplier.Value), 0f, 1f));
				}
				if (Mathf.Abs(__instance.playerVoicePitches[i] - __instance.playerVoicePitchTargets[i]) > 0.025f)
				{
					__instance.playerVoicePitches[i] = Mathf.Lerp(__instance.playerVoicePitches[i], __instance.playerVoicePitchTargets[i], 3f * Time.deltaTime);
				}
				else if (__instance.playerVoicePitches[i] != __instance.playerVoicePitchTargets[i])
				{
					__instance.playerVoicePitches[i] = __instance.playerVoicePitchTargets[i];
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(MenuManager), "OnEnable")]
		[HarmonyPostfix]
		public static void CustomMenu(ref MenuManager __instance)
		{
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: 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_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: 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_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			GameObject p2;
			RectTransform rt9 = default(RectTransform);
			if (!__instance.isInitScene)
			{
				GameObject gameObject = ((Component)__instance.HostSettingsOptionsNormal.transform.parent.parent).gameObject;
				Component component = gameObject.GetComponent(typeof(RectTransform));
				RectTransform val = (RectTransform)(object)((component is RectTransform) ? component : null);
				p2 = ((Component)gameObject.transform.Find("PrivatePublicDescription")).gameObject;
				Component component2 = p2.GetComponent(typeof(RectTransform));
				RectTransform val2 = (RectTransform)(object)((component2 is RectTransform) ? component2 : null);
				Component component3 = ((Component)__instance.HostSettingsOptionsNormal.transform.Find("EnterAName")).gameObject.GetComponent(typeof(RectTransform));
				RectTransform val3 = (RectTransform)(object)((component3 is RectTransform) ? component3 : null);
				GameObject gameObject2 = ((Component)__instance.HostSettingsOptionsNormal.transform.Find("ServerNameField")).gameObject;
				Component component4 = gameObject2.GetComponent(typeof(RectTransform));
				RectTransform val4 = (RectTransform)(object)((component4 is RectTransform) ? component4 : null);
				Component component5 = ((Component)gameObject.transform.Find("Confirm")).gameObject.GetComponent(typeof(RectTransform));
				RectTransform val5 = (RectTransform)(object)((component5 is RectTransform) ? component5 : null);
				Component component6 = ((Component)gameObject.transform.Find("Back")).gameObject.GetComponent(typeof(RectTransform));
				RectTransform val6 = (RectTransform)(object)((component6 is RectTransform) ? component6 : null);
				Component component7 = ((Component)__instance.HostSettingsOptionsNormal.transform.Find("Public")).gameObject.GetComponent(typeof(RectTransform));
				RectTransform val7 = (RectTransform)(object)((component7 is RectTransform) ? component7 : null);
				Component component8 = ((Component)__instance.HostSettingsOptionsNormal.transform.Find("Private")).gameObject.GetComponent(typeof(RectTransform));
				Component obj = ((component8 is RectTransform) ? component8 : null);
				GameObject val8 = Object.Instantiate<GameObject>(gameObject2, gameObject2.transform.parent);
				ref RectTransform reference = ref rt9;
				Component component9 = val8.GetComponent(typeof(RectTransform));
				reference = (RectTransform)(object)((component9 is RectTransform) ? component9 : null);
				val.sizeDelta = new Vector2(val.sizeDelta.x, 200f);
				val2.anchoredPosition = new Vector2(val2.anchoredPosition.x, -50f);
				val3.anchoredPosition = new Vector2(val3.anchoredPosition.x, 40f);
				val4.anchoredPosition = new Vector2(val4.anchoredPosition.x, 55f);
				val5.anchoredPosition = new Vector2(val5.anchoredPosition.x, -60f);
				val6.anchoredPosition = new Vector2(val6.anchoredPosition.x, -85f);
				val7.anchoredPosition = new Vector2(val7.anchoredPosition.x, -23f);
				((RectTransform)obj).anchoredPosition = new Vector2(((RectTransform)obj).anchoredPosition.x, -23f);
				rt9.anchoredPosition = new Vector2(rt9.anchoredPosition.x, 21f);
				((Object)rt9).name = "ServerPlayersField";
				((Component)rt9).GetComponent<TMP_InputField>().contentType = (ContentType)2;
				((TMP_Text)((Component)((Component)rt9).transform.Find("Text Area").Find("Placeholder")).gameObject.GetComponent<TextMeshProUGUI>()).text = "Max players (16)...";
				((Component)rt9).transform.parent = __instance.HostSettingsOptionsNormal.transform;
				((UnityEvent<string>)(object)((Component)rt9).GetComponent<TMP_InputField>().onValueChanged).AddListener((UnityAction<string>)delegate
				{
					OnChange();
				});
			}
			void OnChange()
			{
				string text = Regex.Replace(((Component)rt9).GetComponent<TMP_InputField>().text, "[^0-9]", "");
				Debug.Log((object)text);
				if (!int.TryParse(text, out var result))
				{
					result = 16;
				}
				result = Math.Min(Math.Max(result, 4), 40);
				Debug.Log((object)result);
				if (result > 16)
				{
					((TMP_Text)p2.GetComponent<TextMeshProUGUI>()).text = "Notice: High max player counts\nmay cause lag.";
				}
				else if (((TMP_Text)p2.GetComponent<TextMeshProUGUI>()).text == "Notice: High max player counts\nmay cause lag.")
				{
					((TMP_Text)p2.GetComponent<TextMeshProUGUI>()).text = "yeah you should be good now lol";
				}
			}
		}

		[HarmonyPatch(typeof(MenuManager), "StartHosting")]
		[HarmonyPrefix]
		public static bool StartHost(MenuManager __instance)
		{
			//IL_008f: 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)
			if (!GameNetworkManager.Instance.currentLobby.HasValue)
			{
				return true;
			}
			if (!int.TryParse(Regex.Replace(((TMP_Text)((Component)((Component)__instance.HostSettingsOptionsNormal.transform.Find("ServerPlayersField")).gameObject.transform.Find("Text Area").Find("Text")).gameObject.GetComponent<TextMeshProUGUI>()).text, "[^0-9]", ""), out var result))
			{
				result = 16;
			}
			result = Math.Min(Math.Max(result, 4), 40);
			Lobby valueOrDefault = GameNetworkManager.Instance.currentLobby.GetValueOrDefault();
			((Lobby)(ref valueOrDefault)).SetData("MaxPlayers", result.ToString());
			Debug.Log((object)$"SETTING MAX PLAYERS TO {result}!");
			Plugin.MaxPlayers = result;
			if ((Object)(object)GameNetworkManager.Instance != (Object)null)
			{
				GameNetworkManager.Instance.maxAllowedPlayers = Plugin.MaxPlayers;
			}
			return true;
		}

		[HarmonyPatch(typeof(HUDManager), "FillEndGameStats")]
		[HarmonyPrefix]
		public static void FillEndGameStats(HUDManager __instance)
		{
			ExpandedStatsUI fromAnimator = ExpandedStatsUI.GetFromAnimator(__instance.endgameStatsAnimator);
			if (!((Object)(object)fromAnimator == (Object)null) && !((Object)(object)StartOfRound.Instance == (Object)null))
			{
				PlayerStatsList statsListFromPlayerCount = fromAnimator.GetStatsListFromPlayerCount(Plugin.GetRealPlayerScripts(StartOfRound.Instance).Length);
				__instance.statsUIElements.playerNamesText = statsListFromPlayerCount.Names.ToArray();
				__instance.statsUIElements.playerStates = statsListFromPlayerCount.States.ToArray();
				__instance.statsUIElements.playerNotesText = statsListFromPlayerCount.Notes.ToArray();
				Debug.Log((object)"Adding EXPANDED stats!");
			}
		}

		[HarmonyPatch(typeof(HUDManager), "FillEndGameStats")]
		[HarmonyPostfix]
		public static void FillEndGameStatsPostfix(HUDManager __instance)
		{
			if ((Object)(object)StartOfRound.Instance == (Object)null || Plugin.GetRealPlayerScripts(StartOfRound.Instance).Length <= 4)
			{
				return;
			}
			TextMeshProUGUI[] playerNotesText = __instance.statsUIElements.playerNotesText;
			foreach (TextMeshProUGUI val in playerNotesText)
			{
				if (!(((TMP_Text)val).text == ""))
				{
					((TMP_Text)val).text = ((TMP_Text)val).text.Replace("Notes:", "").Trim();
				}
			}
			Sprite replacementCheckmark = ExpandedStatsUI.GetReplacementCheckmark();
			if ((Object)(object)replacementCheckmark == (Object)null)
			{
				return;
			}
			Image[] playerStates = __instance.statsUIElements.playerStates;
			foreach (Image val2 in playerStates)
			{
				if (!((Object)(object)val2.sprite != (Object)(object)__instance.statsUIElements.aliveIcon))
				{
					val2.sprite = replacementCheckmark;
				}
			}
		}

		[HarmonyPatch(typeof(GameNetworkManager), "StartHost")]
		[HarmonyPrefix]
		public static bool DoTheThe()
		{
			Plugin.CustomNetObjects.Clear();
			return true;
		}

		[HarmonyPatch(typeof(GameNetworkManager), "StartClient")]
		[HarmonyPrefix]
		public static bool StartClient(GameNetworkManager __instance)
		{
			Plugin.CustomNetObjects.Clear();
			return true;
		}

		[HarmonyPatch(typeof(MenuManager), "StartAClient")]
		[HarmonyPrefix]
		public static bool StartAClient()
		{
			Plugin.CustomNetObjects.Clear();
			Debug.Log((object)"LanRunningggg!");
			return true;
		}

		[HarmonyPatch(typeof(SteamLobbyManager), "loadLobbyListAndFilter")]
		[HarmonyPostfix]
		public static IEnumerator LoadLobbyListAndFilter(IEnumerator result, SteamLobbyManager __instance)
		{
			while (result.MoveNext())
			{
				yield return result.Current;
			}
			Debug.Log((object)"Injecting BL playercounts into lobby list.");
			LobbySlot[] componentsInChildren = ((Component)__instance.levelListContainer).GetComponentsInChildren<LobbySlot>(true);
			foreach (LobbySlot val in componentsInChildren)
			{
				try
				{
					((TMP_Text)val.LobbyName).text = ((TMP_Text)val.LobbyName).text.Replace("[BiggerLobby]", "[BL]");
					if (!int.TryParse(((Lobby)(ref val.thisLobby)).GetData("MaxPlayers"), out var result2))
					{
						result2 = 4;
					}
					((TMP_Text)val.playerCount).text = ((TMP_Text)val.playerCount).text.Replace("/ 4", $"/ {result2}");
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)"Exception while injecting BL lobby metadata:");
					Debug.LogWarning((object)ex);
				}
			}
		}

		[HarmonyPatch(typeof(SteamMatchmaking), "CreateLobbyAsync")]
		[HarmonyPrefix]
		public static void SetMaxMembers(ref int maxMembers)
		{
			maxMembers = Plugin.MaxPlayers;
		}

		[HarmonyPatch(typeof(GameNetworkManager), "SetConnectionDataBeforeConnecting")]
		[HarmonyPrefix]
		public static bool SetConnectionDataBeforeConnecting(GameNetworkManager __instance)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			__instance.localClientWaitingForApproval = true;
			Debug.Log((object)("Game version: " + __instance.gameVersionNum));
			if (__instance.disableSteam)
			{
				NetworkManager.Singleton.NetworkConfig.ConnectionData = Encoding.ASCII.GetBytes(__instance.gameVersionNum + ",BiggerLobbyVersion2.5.0");
			}
			else
			{
				NetworkManager.Singleton.NetworkConfig.ConnectionData = Encoding.ASCII.GetBytes(__instance.gameVersionNum + "," + SteamId.op_Implicit(SteamClient.SteamId) + ",BiggerLobbyVersion2.5.0");
			}
			return false;
		}

		[HarmonyPatch(typeof(GameNetworkManager), "LobbyDataIsJoinable")]
		[HarmonyPrefix]
		public static bool SkipLobbySizeCheck(ref GameNetworkManager __instance, ref bool __result, Lobby lobby)
		{
			//IL_004f: 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)
			string data = ((Lobby)(ref lobby)).GetData("vers");
			if (!int.TryParse(((Lobby)(ref lobby)).GetData("MaxPlayers"), out var result))
			{
				result = 16;
			}
			result = Math.Min(Math.Max(result, 4), 40);
			if (((Lobby)(ref lobby)).MemberCount >= result || ((Lobby)(ref lobby)).MemberCount < 1)
			{
				Debug.Log((object)$"Lobby join denied! Too many members in lobby! {((Lobby)(ref lobby)).Id}");
				Object.FindObjectOfType<MenuManager>().SetLoadingScreen(false, (RoomEnter)4, "The server is full!");
				__result = false;
				return false;
			}
			if (data != __instance.gameVersionNum.ToString())
			{
				Debug.Log((object)$"Lobby join denied! Attempted to join vers.{data} lobby id: {((Lobby)(ref lobby)).Id}");
				Object.FindObjectOfType<MenuManager>().SetLoadingScreen(false, (RoomEnter)2, $"The server host is playing on version {data} while you are on version {__instance.gameVersionNum}.");
				__result = false;
				return false;
			}
			if (((Lobby)(ref lobby)).GetData("joinable") == "false")
			{
				Debug.Log((object)"Lobby join denied! Host lobby is not joinable");
				Object.FindObjectOfType<MenuManager>().SetLoadingScreen(false, (RoomEnter)2, "The server host has already landed their ship, or they are still loading in.");
				__result = false;
				return false;
			}
			Plugin.MaxPlayers = result;
			Debug.Log((object)$"SETTING MAX PLAYERS TO {result}!");
			if ((Object)(object)__instance != (Object)null)
			{
				__instance.maxAllowedPlayers = Plugin.MaxPlayers;
			}
			__result = true;
			return false;
		}
	}
	[HarmonyPatch]
	internal class PlayerObjects
	{
		private static StartOfRound startOfRound;

		private static bool instantiating;

		private static int nextClientId;

		private static PlayerControllerB referencePlayer;

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		public static void ResizeLists(ref StartOfRound __instance)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			__instance.allPlayerObjects = Helper.ResizeArray(__instance.allPlayerObjects, Plugin.MaxPlayers);
			__instance.allPlayerScripts = Helper.ResizeArray(__instance.allPlayerScripts, Plugin.MaxPlayers);
			__instance.gameStats.allPlayerStats = Helper.ResizeArray(__instance.gameStats.allPlayerStats, Plugin.MaxPlayers);
			__instance.playerSpawnPositions = Helper.ResizeArray(__instance.playerSpawnPositions, Plugin.MaxPlayers);
			for (int i = 4; i < Plugin.MaxPlayers; i++)
			{
				__instance.gameStats.allPlayerStats[i] = new PlayerStats();
				__instance.playerSpawnPositions[i] = __instance.playerSpawnPositions[0];
			}
		}

		[HarmonyPatch(typeof(ForestGiantAI), "Start")]
		[HarmonyPrefix]
		public static bool ResizeLists2(ref ForestGiantAI __instance)
		{
			__instance.playerStealthMeters = Helper.ResizeArray(__instance.playerStealthMeters, Plugin.MaxPlayers);
			return true;
		}

		[HarmonyPatch(typeof(HUDManager), "Awake")]
		[HarmonyPostfix]
		public static void ResizeLists2(ref HUDManager __instance)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			__instance.playerLevels = Helper.ResizeArray(__instance.playerLevels, Plugin.MaxPlayers + 1);
			for (int i = 4; i < Plugin.MaxPlayers; i++)
			{
				__instance.playerLevels[i] = new PlayerLevel();
			}
		}

		[HarmonyPatch(typeof(SoundManager), "Awake")]
		[HarmonyPostfix]
		public static void SoundWake(ref SoundManager __instance)
		{
			__instance.playerVoiceMixers = Helper.ResizeArray(__instance.playerVoiceMixers, Plugin.MaxPlayers);
			for (int i = 0; i < Plugin.MaxPlayers; i++)
			{
				__instance.playerVoiceMixers[i] = __instance.diageticMixer.outputAudioMixerGroup;
			}
		}

		[HarmonyPatch(typeof(SoundManager), "Start")]
		[HarmonyPostfix]
		public static void ResizeSoundManagerLists(ref SoundManager __instance)
		{
			__instance.playerVoicePitchLerpSpeed = new float[Plugin.MaxPlayers + 1];
			__instance.playerVoicePitchTargets = new float[Plugin.MaxPlayers + 1];
			__instance.playerVoiceVolumes = new float[Plugin.MaxPlayers + 1];
			__instance.playerVoicePitches = new float[Plugin.MaxPlayers + 1];
			for (int i = 1; i < Plugin.MaxPlayers + 1; i++)
			{
				__instance.playerVoicePitchLerpSpeed[i] = 3f;
				__instance.playerVoicePitchTargets[i] = 1f;
				__instance.playerVoicePitches[i] = 1f;
				__instance.playerVoiceVolumes[i] = 1f;
			}
		}

		[HarmonyPatch(typeof(EnemyAI), "EnableEnemyMesh")]
		[HarmonyPrefix]
		public static bool EnableEnemyMesh(EnemyAI __instance, bool enable, bool overrideDoNotSet = false)
		{
			int layer = ((!enable) ? 23 : 19);
			for (int i = 0; i < __instance.skinnedMeshRenderers.Length; i++)
			{
				if (Object.op_Implicit((Object)(object)__instance.skinnedMeshRenderers[i]) && (!((Component)__instance.skinnedMeshRenderers[i]).CompareTag("DoNotSet") || overrideDoNotSet))
				{
					((Component)__instance.skinnedMeshRenderers[i]).gameObject.layer = layer;
				}
			}
			for (int j = 0; j < __instance.meshRenderers.Length; j++)
			{
				if (Object.op_Implicit((Object)(object)__instance.meshRenderers[j]) && (!((Component)__instance.meshRenderers[j]).CompareTag("DoNotSet") || overrideDoNotSet))
				{
					((Component)__instance.meshRenderers[j]).gameObject.layer = layer;
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(ShipTeleporter), "Awake")]
		[HarmonyPrefix]
		public static bool Awake2(ShipTeleporter __instance)
		{
			int[] array = new int[Plugin.MaxPlayers];
			for (int i = 0; i < Plugin.MaxPlayers; i++)
			{
				array[i] = -1;
			}
			typeof(ShipTeleporter).GetField("playersBeingTeleported", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(__instance, array);
			__instance.buttonTrigger.interactable = false;
			typeof(ShipTeleporter).GetField("cooldownTime", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(__instance, __instance.cooldownAmount);
			return false;
		}

		[HarmonyPatch(typeof(NetworkSceneManager), "PopulateScenePlacedObjects")]
		[HarmonyPrefix]
		public static bool AddPlayers(NetworkSceneManager __instance)
		{
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			startOfRound = StartOfRound.Instance;
			if ((Object)(object)startOfRound.allPlayerObjects[Plugin.MaxPlayers - 1] != (Object)null)
			{
				return true;
			}
			referencePlayer = startOfRound.allPlayerObjects[0].GetComponent<PlayerControllerB>();
			GameObject playerPrefab = startOfRound.playerPrefab;
			Transform transform = ((Component)startOfRound.playersContainer).transform;
			FieldInfo field = typeof(NetworkObject).GetField("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.NonPublic);
			PropertyInfo property = typeof(NetworkObject).GetProperty("NetworkObjectId", BindingFlags.Instance | BindingFlags.Public);
			typeof(NetworkSceneManager).GetField("ScenePlacedObjects", BindingFlags.Instance | BindingFlags.NonPublic);
			instantiating = true;
			typeof(NetworkSpawnManager).GetMethod("SpawnNetworkObjectLocally", BindingFlags.Instance | BindingFlags.NonPublic, null, CallingConventions.Any, new Type[6]
			{
				typeof(NetworkObject),
				typeof(ulong),
				typeof(bool),
				typeof(bool),
				typeof(ulong),
				typeof(bool)
			}, null);
			for (int i = 4; i < Plugin.MaxPlayers; i++)
			{
				nextClientId = i;
				GameObject val = Object.Instantiate<GameObject>(playerPrefab, transform);
				PlayerControllerB component = val.GetComponent<PlayerControllerB>();
				NetworkObject component2 = val.GetComponent<NetworkObject>();
				NetworkObject component3 = ((Component)val.transform.Find("PlayerPhysicsBox")).gameObject.GetComponent<NetworkObject>();
				NetworkObject component4 = ((Component)val.transform.Find("ScavengerModel/metarig/ScavengerModelArmsOnly/metarig/spine.003/shoulder.R/arm.R_upper/arm.R_lower/hand.R/LocalItemHolder")).gameObject.GetComponent<NetworkObject>();
				NetworkObject component5 = ((Component)val.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/shoulder.R/arm.R_upper/arm.R_lower/hand.R/ServerItemHolder")).gameObject.GetComponent<NetworkObject>();
				component.TeleportPlayer(StartOfRound.Instance.notSpawnedPosition.position, false, 0f, false, true);
				startOfRound.allPlayerObjects[i] = val;
				startOfRound.allPlayerScripts[i] = component;
				uint num = (uint)(6942069 + i);
				ulong num2 = 6942069uL + (ulong)i;
				uint num3 = (uint)(123456789 + i);
				uint num4 = (uint)(987654321 + i);
				uint num5 = (uint)(124585949 + i);
				ulong num6 = 123456789uL + (ulong)i;
				ulong num7 = 987654321uL + (ulong)i;
				ulong num8 = 124585949uL + (ulong)i;
				Scene scene = ((Component)component2).gameObject.scene;
				_ = ((Scene)(ref scene)).handle;
				field.SetValue(component2, num);
				property.SetValue(component2, num2);
				field.SetValue(component3, num3);
				property.SetValue(component3, num6);
				field.SetValue(component4, num4);
				property.SetValue(component4, num7);
				field.SetValue(component5, num5);
				property.SetValue(component5, num8);
				ManualCameraRenderer[] array = Object.FindObjectsByType<ManualCameraRenderer>((FindObjectsInactive)1, (FindObjectsSortMode)0);
				for (int j = 0; j < array.Length; j++)
				{
					array[j].AddTransformAsTargetToRadar(((Component)component).transform, "Player #" + j, false);
				}
			}
			instantiating = false;
			return true;
		}

		[HarmonyPatch(typeof(QuickMenuManager), "AddUserToPlayerList")]
		[HarmonyPrefix]
		public static bool AddUserToPlayerList(QuickMenuManager __instance, ulong steamId, string playerName, int playerObjectId)
		{
			if (playerObjectId >= 0 && playerObjectId <= Plugin.MaxPlayers)
			{
				__instance.playerListSlots[playerObjectId].KickUserButton.SetActive(((NetworkBehaviour)StartOfRound.Instance).IsServer);
				__instance.playerListSlots[playerObjectId].slotContainer.SetActive(true);
				__instance.playerListSlots[playerObjectId].isConnected = true;
				__instance.playerListSlots[playerObjectId].playerSteamId = steamId;
				((TMP_Text)__instance.playerListSlots[playerObjectId].usernameHeader).text = playerName.Replace("bizzlemip", "<color=#008282>bizzlemip</color>");
				if ((Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null)
				{
					__instance.playerListSlots[playerObjectId].volumeSliderContainer.SetActive(playerObjectId != (int)GameNetworkManager.Instance.localPlayerController.playerClientId);
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(QuickMenuManager), "Update")]
		[HarmonyPrefix]
		private static bool Update(QuickMenuManager __instance)
		{
			for (int i = 0; i < __instance.playerListSlots.Length; i++)
			{
				if (__instance.playerListSlots[i].isConnected)
				{
					float num = __instance.playerListSlots[i].volumeSlider.value / __instance.playerListSlots[i].volumeSlider.maxValue;
					if (num == -1f)
					{
						SoundManager.Instance.playerVoiceVolumes[i] = -1f;
					}
					else
					{
						SoundManager.Instance.playerVoiceVolumes[i] = num;
					}
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(QuickMenuManager), "Start")]
		[HarmonyPrefix]
		public static bool FixPlayerList(ref QuickMenuManager __instance)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			//IL_00c5: 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_00e6: 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_011f: 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_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: 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_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Expected O, but got Unknown
			//IL_032b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0335: Expected O, but got Unknown
			GameObject val = null;
			GameObject gameObject = ((Component)__instance.playerListPanel.transform.Find("Image")).gameObject;
			if (Object.op_Implicit((Object)(object)gameObject.transform.Find("Mask")))
			{
				val = ((Component)gameObject.transform.Find("Mask")).gameObject;
			}
			GameObject val2 = new GameObject("Mask");
			GameObject val3 = new GameObject("ScrollViewport");
			GameObject val4 = new GameObject("BGCollision");
			GameObject val5 = new GameObject("ScrollContent");
			val2.transform.SetParent(gameObject.transform);
			val3.transform.SetParent(val2.transform);
			val4.transform.SetParent(val3.transform);
			val5.transform.SetParent(val3.transform);
			val2.transform.localScale = Vector3.one;
			val3.transform.localScale = Vector3.one;
			val5.transform.localScale = Vector3.one;
			val2.AddComponent<RectTransform>().sizeDelta = new Vector2(300f, 280f);
			val2.transform.localPosition = new Vector3(-10f, 110f, 0f);
			val3.transform.localPosition = new Vector3(0f, -10f, 0f);
			val5.AddComponent<RectTransform>().pivot = new Vector2(0.5f, 1f);
			val2.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 1f);
			val2.transform.localPosition = new Vector3(-10f, 110f, 0f);
			val2.AddComponent<RectMask2D>();
			VerticalLayoutGroup val6 = val5.AddComponent<VerticalLayoutGroup>();
			ContentSizeFitter obj = val5.AddComponent<ContentSizeFitter>();
			ScrollRect obj2 = val3.AddComponent<ScrollRect>();
			obj2.viewport = val3.AddComponent<RectTransform>();
			obj2.content = val5.GetComponent<RectTransform>();
			obj2.horizontal = false;
			Image val7 = val4.AddComponent<Image>();
			val4.GetComponent<RectTransform>().anchorMin = new Vector2(0f, 0f);
			val4.GetComponent<RectTransform>().anchorMax = new Vector2(1f, 1f);
			((Graphic)val7).color = new Color(255f, 255f, 255f, 0f);
			((HorizontalOrVerticalLayoutGroup)val6).spacing = 50f;
			obj.horizontalFit = (FitMode)0;
			obj.verticalFit = (FitMode)2;
			__instance.playerListSlots = Helper.ResizeArray(__instance.playerListSlots, Plugin.MaxPlayers);
			for (int i = 0; i < Plugin.MaxPlayers; i++)
			{
				if (i < 4)
				{
					__instance.playerListSlots[i].slotContainer.transform.SetParent(val5.transform);
					continue;
				}
				PlayerListSlot val8 = new PlayerListSlot();
				GameObject val9 = (val8.slotContainer = Object.Instantiate<GameObject>(__instance.playerListSlots[0].slotContainer));
				val8.volumeSliderContainer = ((Component)val9.transform.Find("VoiceVolumeSlider")).gameObject;
				val8.KickUserButton = ((Component)val9.transform.Find("KickButton")).gameObject;
				QuickMenuManager yeahoriginal = __instance;
				int localI = i;
				((UnityEvent)val8.KickUserButton.GetComponent<Button>().onClick).AddListener((UnityAction)delegate
				{
					yeahoriginal.KickUserFromServer(localI);
				});
				val8.isConnected = false;
				val8.usernameHeader = ((Component)val9.transform.Find("PlayerNameButton").Find("PName")).gameObject.GetComponent<TextMeshProUGUI>();
				val8.volumeSlider = ((Component)val9.transform.Find("VoiceVolumeSlider").Find("Slider")).gameObject.GetComponent<Slider>();
				val8.playerSteamId = __instance.playerListSlots[0].playerSteamId;
				val9.transform.SetParent(val5.transform, false);
				__instance.playerListSlots[i] = val8;
			}
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)val);
			}
			return true;
		}

		[HarmonyPatch(typeof(ManualCameraRenderer), "Awake")]
		[HarmonyPrefix]
		public static bool Mawake(ref ManualCameraRenderer __instance)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			for (int i = 0; i < 4; i++)
			{
				__instance.radarTargets.Add(new TransformAndName(((Component)StartOfRound.Instance.allPlayerScripts[i]).transform, StartOfRound.Instance.allPlayerScripts[i].playerUsername, false));
			}
			__instance.targetTransformIndex = 0;
			__instance.targetedPlayer = StartOfRound.Instance.allPlayerScripts[0];
			return false;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Awake")]
		[HarmonyPrefix]
		public static bool FixPlayerObject(ref PlayerControllerB __instance)
		{
			if (!instantiating)
			{
				return true;
			}
			((Object)((Component)__instance).gameObject).name = $"ExtraPlayer{nextClientId}";
			__instance.playerClientId = (ulong)nextClientId;
			__instance.actualClientId = (ulong)nextClientId;
			StartOfRound.Instance.allPlayerObjects[nextClientId] = ((Component)((Component)__instance).transform.parent).gameObject;
			StartOfRound.Instance.allPlayerScripts[nextClientId] = __instance;
			FieldInfo[] fields = typeof(PlayerControllerB).GetFields();
			foreach (FieldInfo fieldInfo in fields)
			{
				object value = fieldInfo.GetValue(__instance);
				object value2 = fieldInfo.GetValue(referencePlayer);
				if (value == null && value2 != null)
				{
					fieldInfo.SetValue(__instance, value2);
				}
			}
			((Behaviour)__instance).enabled = true;
			return true;
		}

		[HarmonyPatch(typeof(StartOfRound), "GetPlayerSpawnPosition")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> GetPlayerSpawnPosition(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			list[0].opcode = OpCodes.Ldc_I4_1;
			return list.AsEnumerable();
		}
	}
}
namespace BiggerLobby.Models
{
	public class PlayerStatsList
	{
		public Transform transform;

		public List<TextMeshProUGUI> Names = new List<TextMeshProUGUI>();

		public List<Image> States = new List<Image>();

		public List<TextMeshProUGUI> Notes = new List<TextMeshProUGUI>();

		public GameObject gameObject => ((Component)transform).gameObject;

		public PlayerStatsList(Transform transform)
		{
			this.transform = transform;
		}

		public void AddPlayerSlotTransform(Transform playerSlot)
		{
			TextMeshProUGUI component = ((Component)playerSlot.GetChild(0)).GetComponent<TextMeshProUGUI>();
			Image component2 = ((Component)playerSlot.GetChild(1)).GetComponent<Image>();
			TextMeshProUGUI component3 = ((Component)playerSlot.Find("Notes")).GetComponent<TextMeshProUGUI>();
			Names.Add(component);
			States.Add(component2);
			Notes.Add(component3);
		}

		public void AddPlayerSlotTransforms(List<Transform> playerSlots)
		{
			foreach (Transform playerSlot in playerSlots)
			{
				AddPlayerSlotTransform(playerSlot);
			}
		}
	}
	public enum StatsScreenType
	{
		FourPlayers,
		EightPlayers,
		MoreThanEightPlayers
	}
	public class StatsUIReferences : MonoBehaviour
	{
		public Sprite StatsBoxesThin;

		public Sprite StatsBoxesGradeOnly;

		public Sprite CheckmarkThin;

		public ScrollRect ThinScrollRect;
	}
}

BooBoo Building/BepInEx/plugins/BzzzThe18th-CommandLib/CommandLib.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
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 = "")]
[assembly: AssemblyCompany("CommandLib")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Template mod for lethal company")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("CommandLib")]
[assembly: AssemblyTitle("CommandLib")]
[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 CommandLib
{
	public class ModInfo
	{
		public const string name = "Command Library";

		public const string guid = "buzzbb.cmdlib";

		public const string version = "1.0.0";
	}
	[BepInPlugin("buzzbb.cmdlib", "Command Library", "1.0.0")]
	public class Commands : BaseUnityPlugin
	{
		private Harmony harmonyInstance = new Harmony("buzzbb.cmdlib");

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Reached awake point for Command [email protected], applying patches");
			harmonyInstance.PatchAll(Assembly.GetExecutingAssembly());
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Applied patches");
		}

		public static void RegisterCommand(string word, string returnText, string eventName, Terminal terminal)
		{
			TerminalKeyword val = MakeKeyword(word.ToLower());
			TerminalNode specialKeywordResult = MakeNode(returnText, eventName);
			val.specialKeywordResult = specialKeywordResult;
			RegisterKeyword(val, terminal);
		}

		public static TerminalKeyword MakeKeyword(string word)
		{
			TerminalKeyword val = ScriptableObject.CreateInstance<TerminalKeyword>();
			val.word = word;
			return val;
		}

		public static TerminalNode MakeNode(string returnText, string associatedEvent)
		{
			TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
			val.displayText = returnText;
			val.clearPreviousText = true;
			val.terminalEvent = associatedEvent;
			return val;
		}

		public static void RegisterKeyword(TerminalKeyword keyword, Terminal terminal)
		{
			if ((Object)(object)terminal != (Object)null)
			{
				terminal.terminalNodes.allKeywords = CollectionExtensions.AddToArray<TerminalKeyword>(terminal.terminalNodes.allKeywords, keyword);
			}
			else
			{
				Debug.LogError((object)"Tried to register keyword with null terminal");
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/Clementinise-CustomSounds/CustomSounds.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.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CustomSounds.Networking;
using CustomSounds.Patches;
using GameNetcodeStuff;
using HarmonyLib;
using LCSoundTool;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("CustomSounds")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomSounds")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9e086160-a7fd-4721-ba09-3e8534cb7011")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace CustomSounds
{
	[BepInPlugin("CustomSounds", "Custom Sounds", "2.2.0")]
	public class Plugin : BaseUnityPlugin
	{
		private const string PLUGIN_GUID = "CustomSounds";

		private const string PLUGIN_NAME = "Custom Sounds";

		private const string PLUGIN_VERSION = "2.2.0";

		public static Plugin Instance;

		internal ManualLogSource logger;

		private Harmony harmony;

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

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

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

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

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

		public static ConfigEntry<KeyboardShortcut> AcceptSyncKey;

		public ConfigEntry<bool> configUseNetworking;

		private Dictionary<string, string> customSoundNames = new Dictionary<string, string>();

		public static bool Initialized { get; private set; }

		private void Awake()
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			if (!((Object)(object)Instance == (Object)null))
			{
				return;
			}
			Instance = this;
			logger = Logger.CreateLogSource("CustomSounds");
			configUseNetworking = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "EnableNetworking", true, "Whether or not to use the networking built into this plugin. If set to true everyone in the lobby needs CustomSounds to join and also \"EnableNetworking\" set to true.");
			AcceptSyncKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Experimental", "AcceptSyncKey", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Key to accept audio sync.");
			harmony = new Harmony("CustomSounds");
			harmony.PatchAll(typeof(TerminalParsePlayerSentencePatch));
			harmony.PatchAll(typeof(RemapKeyPatch));
			if (configUseNetworking.Value)
			{
				harmony.PatchAll(typeof(NetworkObjectManager));
			}
			modifiedSounds = new HashSet<string>();
			string customSoundsFolderPath = GetCustomSoundsFolderPath();
			if (!Directory.Exists(customSoundsFolderPath))
			{
				logger.LogInfo((object)"\"CustomSounds\" folder not found. Creating it now.");
				Directory.CreateDirectory(customSoundsFolderPath);
			}
			string path = Path.Combine(Paths.BepInExConfigPath);
			try
			{
				List<string> list = File.ReadAllLines(path).ToList();
				int num = list.FindIndex((string line) => line.StartsWith("HideManagerGameObject"));
				if (num != -1)
				{
					logger.LogInfo((object)"\"hideManagerGameObject\" value not correctly set. Fixing it now.");
					list[num] = "HideManagerGameObject = true";
				}
				File.WriteAllLines(path, list);
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Error modifying config file: " + ex.Message));
			}
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			logger.LogInfo((object)"Plugin CustomSounds is loaded!");
		}

		internal void Start()
		{
			Initialize();
		}

		internal void OnDestroy()
		{
			Initialize();
		}

		internal void Initialize()
		{
			if (!Initialized)
			{
				Initialized = true;
				DeleteTempFolder();
				ReloadSounds(serverSync: false, isTemporarySync: false);
			}
		}

		private void OnApplicationQuit()
		{
			DeleteTempFolder();
		}

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

		public void DeleteTempFolder()
		{
			string customSoundsTempFolderPath = GetCustomSoundsTempFolderPath();
			if (Directory.Exists(customSoundsTempFolderPath))
			{
				try
				{
					Directory.Delete(customSoundsTempFolderPath, recursive: true);
					logger.LogInfo((object)"Temporary-Sync folder deleted successfully.");
				}
				catch (Exception ex)
				{
					logger.LogError((object)("Error deleting Temporary-Sync folder: " + ex.Message));
				}
			}
		}

		public string GetCustomSoundsFolderPath()
		{
			return Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)Instance).Info.Location), "CustomSounds");
		}

		public string GetCustomSoundsTempFolderPath()
		{
			return Path.Combine(GetCustomSoundsFolderPath(), "Temporary-Sync");
		}

		public static byte[] SerializeWavToBytes(string filePath)
		{
			try
			{
				return File.ReadAllBytes(filePath);
			}
			catch (Exception ex)
			{
				Console.WriteLine("An error occurred: " + ex.Message);
				return null;
			}
		}

		public static string SerializeWavToBase64(string filePath)
		{
			try
			{
				byte[] inArray = File.ReadAllBytes(filePath);
				return Convert.ToBase64String(inArray);
			}
			catch (Exception ex)
			{
				Console.WriteLine("An error occurred: " + ex.Message);
				return null;
			}
		}

		public static void DeserializeBytesToWav(byte[] byteArray, string audioFileName)
		{
			try
			{
				string customSoundsTempFolderPath = Instance.GetCustomSoundsTempFolderPath();
				if (!Directory.Exists(customSoundsTempFolderPath))
				{
					Instance.logger.LogInfo((object)"\"Temporary-Sync\" folder not found. Creating it now.");
					Directory.CreateDirectory(customSoundsTempFolderPath);
				}
				File.WriteAllBytes(Path.Combine(customSoundsTempFolderPath, audioFileName), byteArray);
				Console.WriteLine("WAV file \"" + audioFileName + "\" created!");
			}
			catch (Exception ex)
			{
				Console.WriteLine("An error occurred: " + ex.Message);
			}
		}

		public static List<byte[]> SplitAudioData(byte[] audioData, int maxSegmentSize = 62000)
		{
			List<byte[]> list = new List<byte[]>();
			for (int i = 0; i < audioData.Length; i += maxSegmentSize)
			{
				int num = Mathf.Min(maxSegmentSize, audioData.Length - i);
				byte[] array = new byte[num];
				Array.Copy(audioData, i, array, 0, num);
				list.Add(array);
			}
			return list;
		}

		public static byte[] CombineAudioSegments(List<byte[]> segments)
		{
			List<byte> list = new List<byte>();
			foreach (byte[] segment in segments)
			{
				list.AddRange(segment);
			}
			return list.ToArray();
		}

		public void ShowCustomTip(string header, string body, bool isWarning)
		{
			HUDManager.Instance.DisplayTip(header, body, isWarning, false, "LC_Tip1");
		}

		public void ForceUnsync()
		{
			DeleteTempFolder();
			ReloadSounds(serverSync: false, isTemporarySync: false);
		}

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

		public static string CalculateMD5(string filename)
		{
			using MD5 mD = MD5.Create();
			using FileStream inputStream = File.OpenRead(filename);
			byte[] array = mD.ComputeHash(inputStream);
			return BitConverter.ToString(array).Replace("-", "").ToLowerInvariant();
		}

		public void ReloadSounds(bool serverSync, bool isTemporarySync)
		{
			oldSounds = new HashSet<string>(currentSounds);
			modifiedSounds.Clear();
			string directoryName = Path.GetDirectoryName(Paths.PluginPath);
			currentSounds.Clear();
			customSoundNames.Clear();
			string customSoundsTempFolderPath = GetCustomSoundsTempFolderPath();
			if (isTemporarySync)
			{
				logger.LogInfo((object)("Temporary folder: " + customSoundsTempFolderPath));
				if (Directory.Exists(customSoundsTempFolderPath))
				{
					ProcessDirectory(customSoundsTempFolderPath, serverSync, isTemporarySync: true);
				}
			}
			ProcessDirectory(directoryName, serverSync, isTemporarySync: false);
		}

		private void ProcessDirectory(string directoryPath, bool serverSync, bool isTemporarySync)
		{
			string[] directories = Directory.GetDirectories(directoryPath, "CustomSounds", SearchOption.AllDirectories);
			foreach (string text in directories)
			{
				string fileName = Path.GetFileName(Path.GetDirectoryName(text));
				ProcessSoundFiles(text, fileName, serverSync, isTemporarySync);
				string[] directories2 = Directory.GetDirectories(text);
				foreach (string text2 in directories2)
				{
					string fileName2 = Path.GetFileName(text2);
					ProcessSoundFiles(text2, fileName2, serverSync, isTemporarySync);
				}
			}
		}

		private (string soundName, int? percentage, string customName) ParseSoundFileName(string fullSoundName)
		{
			string[] array = fullSoundName.Split(new char[1] { '-' });
			string s = array[^1].Replace(".wav", "");
			if (int.TryParse(s, out var result))
			{
				string item = array[0];
				string item2 = string.Join(" ", array.Skip(1).Take(array.Length - 2));
				return (item, result, item2);
			}
			return (array[0], null, string.Join(" ", array.Skip(1)).Replace(".wav", ""));
		}

		private void ProcessSoundFiles(string directoryPath, string packName, bool serverSync, bool isTemporarySync)
		{
			string[] files = Directory.GetFiles(directoryPath, "*.wav");
			foreach (string text in files)
			{
				string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
				(string soundName, int? percentage, string customName) tuple = ParseSoundFileName(fileNameWithoutExtension);
				string item = tuple.soundName;
				int? item2 = tuple.percentage;
				string item3 = tuple.customName;
				string text2 = (item2.HasValue ? $"{item}-{item3}-{item2.Value}" : (item + "-" + item3));
				string text3 = CalculateMD5(text);
				if (isTemporarySync || !currentSounds.Contains(text2))
				{
					if (soundHashes.TryGetValue(text2, out var value) && value != text3)
					{
						modifiedSounds.Add(text2);
					}
					AudioClip audioClip = SoundTool.GetAudioClip(directoryPath, "", text);
					SoundTool.ReplaceAudioClip(item, audioClip);
					soundHashes[text2] = text3;
					currentSounds.Add(text2);
					soundPacks[item] = packName;
					string text4 = "[" + packName + "] " + item + " sound replaced!";
					if (item2 > 0)
					{
						text4 += $" (Random chance: {item2}%)";
					}
					logger.LogInfo((object)text4);
					string key = item + (item2.HasValue ? $"-{item2.Value}-{item3}" : ("-" + item3));
					if (!string.IsNullOrEmpty(item3))
					{
						customSoundNames[key] = item3;
					}
					if (serverSync)
					{
						string text5 = Path.Combine(directoryPath, fileNameWithoutExtension + ".wav");
						logger.LogInfo((object)("[" + text5 + "] " + fileNameWithoutExtension + ".wav!"));
						AudioNetworkHandler.Instance.QueueAudioData(SerializeWavToBytes(text5), fileNameWithoutExtension + ".wav");
					}
				}
			}
		}

		public string ListAllSounds(bool isListing)
		{
			StringBuilder stringBuilder = new StringBuilder(isListing ? "Listing all currently loaded custom sounds:\n\n" : "Customsounds reloaded.\n\n");
			Dictionary<string, List<string>> soundsByPack = new Dictionary<string, List<string>>();
			Action<HashSet<string>, string> action = delegate(HashSet<string> soundsSet, string status)
			{
				foreach (string item5 in soundsSet)
				{
					(string soundName, int? percentage, string customName) tuple = ParseSoundFileName(item5);
					string item = tuple.soundName;
					int? item2 = tuple.percentage;
					string item3 = tuple.customName;
					string text = (item2.HasValue ? $" (Random: {item2.Value}%)" : "");
					string text2 = "";
					string key = item + (item2.HasValue ? $"-{item2.Value}-{item3}" : ("-" + item3));
					if (customSoundNames.TryGetValue(key, out var value))
					{
						text2 = " [" + value + "]";
					}
					string key2 = (soundPacks.ContainsKey(item) ? soundPacks[item] : "Unknown");
					if (!soundsByPack.ContainsKey(key2))
					{
						soundsByPack[key2] = new List<string>();
					}
					string item4 = (isListing ? (item + text + text2) : (item + " (" + status + ")" + text + text2));
					soundsByPack[key2].Add(item4);
				}
			};
			if (!isListing)
			{
				action(new HashSet<string>(currentSounds.Except(oldSounds)), "N¹");
				action(new HashSet<string>(oldSounds.Except(currentSounds)), "D²");
				action(new HashSet<string>(oldSounds.Intersect(currentSounds).Except(modifiedSounds)), "A.E³");
				action(new HashSet<string>(modifiedSounds), "M⁴");
			}
			else
			{
				action(new HashSet<string>(currentSounds), "N¹");
			}
			foreach (string key3 in soundsByPack.Keys)
			{
				stringBuilder.AppendLine(key3 + " :");
				foreach (string item6 in soundsByPack[key3])
				{
					stringBuilder.AppendLine("- " + item6);
				}
				stringBuilder.AppendLine();
			}
			if (!isListing)
			{
				stringBuilder.AppendLine("Footnotes:");
				stringBuilder.AppendLine("¹ N = New");
				stringBuilder.AppendLine("² D = Deleted");
				stringBuilder.AppendLine("³ A.E = Already Existed");
				stringBuilder.AppendLine("⁴ M = Modified");
				stringBuilder.AppendLine();
			}
			return stringBuilder.ToString();
		}
	}
}
namespace CustomSounds.Patches
{
	[HarmonyPatch]
	public class NetworkObjectManager
	{
		private static GameObject networkPrefab;

		private static GameObject networkHandlerHost;

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

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		private static void SpawnNetworkHandler()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					Plugin.Instance.logger.LogInfo((object)"Spawning network handler");
					networkHandlerHost = Object.Instantiate<GameObject>(networkPrefab, Vector3.zero, Quaternion.identity);
					if (networkHandlerHost.GetComponent<NetworkObject>().IsSpawned)
					{
						Debug.Log((object)"NetworkObject is spawned and active.");
					}
					else
					{
						Debug.Log((object)"Failed to spawn NetworkObject.");
					}
					networkHandlerHost.GetComponent<NetworkObject>().Spawn(true);
					if ((Object)(object)AudioNetworkHandler.Instance != (Object)null)
					{
						Debug.Log((object)"Successfully accessed AudioNetworkHandler instance.");
					}
					else
					{
						Debug.Log((object)"AudioNetworkHandler instance is null.");
					}
				}
			}
			catch
			{
				Plugin.Instance.logger.LogError((object)"Failed to spawned network handler");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		private static void DestroyNetworkHandler()
		{
			try
			{
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					Plugin.Instance.logger.LogInfo((object)"Destroying network handler");
					Object.Destroy((Object)(object)networkHandlerHost);
					networkHandlerHost = null;
				}
			}
			catch
			{
				Plugin.Instance.logger.LogError((object)"Failed to destroy network handler");
			}
		}
	}
	[HarmonyPatch]
	public class RemapKeyPatch
	{
		public Harmony _harmony;

		public static InputActionAsset asset;

		private static string defaultKey;

		private static string path;

		public static string actionName;

		public static void UpdateInputActionAsset(string thing)
		{
			asset = InputActionAsset.FromJson("\r\n            {\r\n                \"maps\" : [\r\n                    {\r\n                        \"name\" : \"CustomSounds\",\r\n                        \"actions\": [\r\n                            {\"name\": \"" + actionName + "\", \"type\" : \"button\"}\r\n                        ],\r\n                        \"bindings\" : [\r\n                            {\"path\" : \"" + thing + "\", \"action\": \"" + actionName + "\"}\r\n                        ]\r\n                    }\r\n                ]\r\n            }");
		}

		[HarmonyPatch(typeof(KepRemapPanel), "LoadKeybindsUI")]
		[HarmonyPrefix]
		public static void AddRemappableKey(KepRemapPanel __instance)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			Debug.Log((object)("[CustomSounds] Default key for sync is " + defaultKey));
			for (int i = 0; i < __instance.remappableKeys.Count; i++)
			{
				if (__instance.remappableKeys[i].ControlName == "Accept Sync")
				{
					return;
				}
			}
			RemappableKey val = new RemappableKey();
			UpdateInputActionAsset(defaultKey);
			if ((Object)(object)asset == (Object)null)
			{
				Debug.LogError((object)"InputActionAsset is null.");
				return;
			}
			InputAction val2 = asset.FindAction("CustomSounds/" + actionName, false);
			if (val2 == null)
			{
				Debug.LogError((object)"Action 'CustomSounds/AcceptSyncAction' not found.");
				return;
			}
			InputActionReference currentInput = InputActionReference.Create(asset.FindAction("CustomSounds/" + actionName, false));
			val.ControlName = "Accept Sync";
			val.currentInput = currentInput;
			__instance.remappableKeys.Add(val);
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		public static void ReadInput(PlayerControllerB __instance)
		{
			if (((((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject)) || __instance.isTestingPlayer) && Application.isFocused)
			{
				if (!Object.op_Implicit((Object)(object)asset) || !asset.enabled)
				{
					UpdateInputActionAsset(defaultKey);
					asset.Enable();
				}
				InputAction val = asset.FindAction("CustomSounds/" + actionName, false);
				if (val != null && val.WasPressedThisFrame() && AudioNetworkHandler.isRequestingSync)
				{
					Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Sync request accepted successfully!", isWarning: false);
					AudioNetworkHandler.hasAcceptedSync = true;
					AudioNetworkHandler.isRequestingSync = false;
				}
			}
		}

		[HarmonyPatch(typeof(IngamePlayerSettings), "CompleteRebind")]
		[HarmonyPrefix]
		public static void SavingActionRebind(IngamePlayerSettings __instance)
		{
			//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_0083: 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)
			if (!(__instance.rebindingOperation.action.name != actionName))
			{
				string text = ((object)__instance.rebindingOperation.action).ToString();
				string text2 = text.Split('[', ']')[1];
				string value = text2.Replace("/Keyboard/", "");
				defaultKey = text2;
				try
				{
					KeyCode val = (KeyCode)Enum.Parse(typeof(KeyCode), value, ignoreCase: true);
					Plugin.AcceptSyncKey.Value = new KeyboardShortcut(val, Array.Empty<KeyCode>());
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("Erreur lors de la conversion de la chaîne en KeyCode: " + ex.Message));
				}
				UpdateInputActionAsset(defaultKey);
			}
		}

		[HarmonyPatch(typeof(KepRemapPanel), "ResetKeybindsUI")]
		[HarmonyPrefix]
		public static void ResetAcceptAction(KepRemapPanel __instance)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Plugin.AcceptSyncKey.Value = new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>());
			defaultKey = "<Keyboard>/f8";
			UpdateInputActionAsset(defaultKey);
			bool flag = UpdateAcceptSyncKeybind(__instance, "<Keyboard>/f8");
		}

		private static bool UpdateAcceptSyncKeybind(KepRemapPanel panel, string defaultBinding)
		{
			foreach (RemappableKey remappableKey in panel.remappableKeys)
			{
				if (remappableKey.ControlName == "Accept Sync")
				{
					remappableKey.currentInput = InputActionReference.Create(asset.FindAction("CustomSounds/AcceptSyncAction", false));
					Debug.Log((object)"[CustomSounds] Found and updated 'Accept Sync' keybinding");
					return true;
				}
			}
			Debug.Log((object)"[CustomSounds] 'Accept Sync' keybinding not found");
			return false;
		}

		static RemapKeyPatch()
		{
			//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)
			KeyboardShortcut value = Plugin.AcceptSyncKey.Value;
			defaultKey = "<Keyboard>/" + ((object)(KeyboardShortcut)(ref value)).ToString();
			path = Application.persistentDataPath + "/AcceptSyncButton.txt";
			actionName = "AcceptSyncAction";
		}
	}
	[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
	public static class TerminalParsePlayerSentencePatch
	{
		public static bool Prefix(Terminal __instance, ref TerminalNode __result)
		{
			string[] array = __instance.screenText.text.Split(new char[1] { '\n' });
			if (array.Length == 0)
			{
				return true;
			}
			string[] array2 = array.Last().Trim().ToLower()
				.Split(new char[1] { ' ' });
			if (array2.Length == 0 || (array2[0] != "customsounds" && array2[0] != "cs"))
			{
				return true;
			}
			Plugin.Instance.logger.LogInfo((object)("Received terminal command: " + string.Join(" ", array2)));
			if (array2.Length > 1 && (array2[0] == "customsounds" || array2[0] == "cs"))
			{
				switch (array2[1])
				{
				case "reload":
				case "rl":
					Plugin.Instance.RevertSounds();
					Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: false);
					__result = CreateTerminalNode(Plugin.Instance.ListAllSounds(isListing: false));
					return false;
				case "revert":
				case "rv":
					Plugin.Instance.RevertSounds();
					__result = CreateTerminalNode("Game sounds reverted to original.\n\n");
					return false;
				case "list":
				case "l":
					__result = CreateTerminalNode(Plugin.Instance.ListAllSounds(isListing: true));
					return false;
				case "help":
				case "h":
					if (NetworkManager.Singleton.IsHost)
					{
						__result = CreateTerminalNode("CustomSounds commands \n(Can also be used with 'CS' as an alias).\n\n>CUSTOMSOUNDS LIST/L\nTo display all currently loaded sounds\n\n>CUSTOMSOUNDS RELOAD/RL\nTo reload and apply sounds from the 'CustomSounds' folder and its subfolders.\n\n>CUSTOMSOUNDS REVERT/RV\nTo unload all custom sounds and restore original game sounds\n\n>CUSTOMSOUNDS SYNC/S\nTo start the sync of custom sounds with clients\n\n>CUSTOMSOUNDS FORCE-UNSYNC/FU\nTo force the unsync process for all clients\n\n");
					}
					else
					{
						__result = CreateTerminalNode("CustomSounds commands \n(Can also be used with 'CS' as an alias).\n\n>CUSTOMSOUNDS LIST/L\nTo display all currently loaded sounds\n\n>CUSTOMSOUNDS RELOAD/RL\nTo reload and apply sounds from the 'CustomSounds' folder and its subfolders.\n\n>CUSTOMSOUNDS REVERT/RV\nTo unload all custom sounds and restore original game sounds\n\n>CUSTOMSOUNDS UNSYNC/U\nUnsyncs sounds sent by the host.\n\n");
					}
					return false;
				case "sync":
				case "s":
					if (NetworkManager.Singleton.IsHost)
					{
						if (Plugin.Instance.configUseNetworking.Value)
						{
							__result = CreateTerminalNode("Custom sound sync initiated. \nSyncing sounds with clients...\n\n");
							Plugin.Instance.ReloadSounds(serverSync: true, isTemporarySync: false);
						}
						else
						{
							__result = CreateTerminalNode("Custom sound sync is currently disabled. \nPlease enable network support in the plugin config to use this feature.\n\n");
						}
					}
					else
					{
						__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command can only be used by the host!\n\n");
					}
					return false;
				case "unsync":
				case "u":
					if (!NetworkManager.Singleton.IsHost)
					{
						__result = CreateTerminalNode("Unsyncing custom sounds. \nTemporary files deleted and original sounds reloaded.\n\n");
						Plugin.Instance.DeleteTempFolder();
						Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: false);
					}
					else
					{
						__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command cannot be used by the host!\n\n");
					}
					return false;
				case "fu":
				case "force-unsync":
					if (NetworkManager.Singleton.IsHost)
					{
						__result = CreateTerminalNode("Forcing unsync for all clients. \nAll client-side temporary synced files have been deleted, and original sounds reloaded.\n\n");
						AudioNetworkHandler.Instance.ForceUnsync();
					}
					else
					{
						__result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command can only be used by the host!\n\n");
					}
					return false;
				default:
					__result = CreateTerminalNode("Unknown customsounds command.\n\n");
					return false;
				}
			}
			return true;
		}

		private static TerminalNode CreateTerminalNode(string message)
		{
			TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
			val.displayText = message;
			val.clearPreviousText = true;
			return val;
		}
	}
}
namespace CustomSounds.Networking
{
	public class AudioNetworkHandler : NetworkBehaviour
	{
		private struct AudioData
		{
			public List<byte[]> Segments;

			public string FileName;

			public AudioData(List<byte[]> segments, string fileName)
			{
				Segments = segments;
				FileName = fileName;
			}
		}

		private List<byte[]> receivedAudioSegments = new List<byte[]>();

		private string audioFileName;

		private int totalAudioFiles;

		private int processedAudioFiles;

		private int totalSegments;

		private int processedSegments;

		public static bool isRequestingSync;

		private float[] progressThresholds = new float[4] { 0.25f, 0.5f, 0.75f, 1f };

		private int lastThresholdIndex = -1;

		public static bool hasAcceptedSync;

		private Queue<AudioData> audioQueue = new Queue<AudioData>();

		private bool isSendingAudio = false;

		public static AudioNetworkHandler Instance { get; private set; }

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
				Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
				Debug.Log((object)"AudioNetworkHandler instance created.");
			}
			else
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
				Debug.Log((object)"Extra AudioNetworkHandler instance destroyed.");
			}
		}

		public void QueueAudioData(byte[] audioData, string audioName)
		{
			List<byte[]> list = Plugin.SplitAudioData(audioData);
			totalSegments += list.Count;
			audioQueue.Enqueue(new AudioData(list, audioName));
			if (!isSendingAudio)
			{
				totalAudioFiles = audioQueue.Count;
				processedAudioFiles = 0;
				((MonoBehaviour)this).StartCoroutine(SendAudioDataQueue());
			}
		}

		private IEnumerator SendAudioDataQueue()
		{
			isSendingAudio = true;
			totalSegments = 0;
			processedSegments = 0;
			lastThresholdIndex = -1;
			RequestSyncWithClients();
			yield return (object)new WaitForSeconds(6f);
			isRequestingSync = false;
			DisplayStartingSyncMessageClientRpc();
			yield return (object)new WaitForSeconds(2f);
			while (audioQueue.Count > 0)
			{
				AudioData audioData = audioQueue.Dequeue();
				yield return ((MonoBehaviour)this).StartCoroutine(SendAudioDataCoroutine(audioData.Segments, audioData.FileName));
				processedAudioFiles++;
				UpdateProgress();
			}
			NotifyClientsQueueCompletedServerRpc();
			isSendingAudio = false;
		}

		private void RequestSyncWithClients()
		{
			foreach (NetworkClient connectedClients in NetworkManager.Singleton.ConnectedClientsList)
			{
				RequestSyncClientRpc(connectedClients.ClientId);
			}
		}

		[ClientRpc]
		private void RequestSyncClientRpc(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_00e9: 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(3186703908u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, clientId);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3186703908u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((NetworkBehaviour)this).IsServer)
				{
					Plugin.Instance.ShowCustomTip("CustomSounds Sync", $"Press {Plugin.AcceptSyncKey.Value} to accept the audio sync request.", isWarning: false);
					isRequestingSync = true;
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void NotifyClientsQueueCompletedServerRpc(ServerRpcParams rpcParams = 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_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))
				{
					FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(152710787u, rpcParams, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendServerRpc(ref val, 152710787u, rpcParams, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					ProcessLastAudioFileClientRpc();
				}
			}
		}

		public void ForceUnsync()
		{
			ForceUnsyncClientsClientRpc();
		}

		[ClientRpc]
		private void ForceUnsyncClientsClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3960362720u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3960362720u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).IsServer)
				{
					Debug.Log((object)"Forcing all clients to delete Temporary-Sync folder.");
					return;
				}
				Plugin.Instance.ShowCustomTip("CustomSounds Sync", "The CustomSounds sync has been reset by the host.\nTemporary files deleted and original sounds reloaded", isWarning: false);
				Plugin.Instance.DeleteTempFolder();
				Plugin.Instance.RevertSounds();
				Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: false);
			}
		}

		[ClientRpc]
		private void ProcessLastAudioFileClientRpc()
		{
			//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(234624598u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 234624598u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && hasAcceptedSync)
				{
					hasAcceptedSync = false;
					ProcessLastAudioFile();
					Debug.Log((object)"Reverting all sounds.");
					Plugin.Instance.RevertSounds();
					Debug.Log((object)"All sounds reverted!");
					Debug.Log((object)"Reloading all sounds.");
					Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: true);
					Debug.Log((object)"All sounds reloaded!");
				}
			}
		}

		private void ProcessLastAudioFile()
		{
			if (receivedAudioSegments.Count > 0 && !string.IsNullOrEmpty(audioFileName))
			{
				byte[] byteArray = Plugin.CombineAudioSegments(receivedAudioSegments);
				Plugin.DeserializeBytesToWav(byteArray, audioFileName);
				receivedAudioSegments.Clear();
				audioFileName = null;
			}
		}

		public void SendAudioData(byte[] audioData, string audioName)
		{
			List<byte[]> list = Plugin.SplitAudioData(audioData);
			audioFileName = audioName;
			SendAudioMetaDataToClientsServerRpc(list.Count, audioName);
			((MonoBehaviour)this).StartCoroutine(SendAudioDataCoroutine(list, audioName));
		}

		[ServerRpc]
		public void SendAudioMetaDataToClientsServerRpc(int totalSegments, string fileName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: 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_00b7: 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_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3991320206u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, totalSegments);
				bool flag = fileName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(fileName, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3991320206u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				Debug.Log((object)$"Sending metadata to clients: {totalSegments} segments, file name: {fileName}");
				ReceiveAudioMetaDataClientRpc(totalSegments, fileName);
			}
		}

		private IEnumerator SendAudioDataCoroutine(List<byte[]> audioSegments, string audioName)
		{
			foreach (byte[] segment in audioSegments)
			{
				SendBytesToServerRpc(segment, audioName);
				processedSegments++;
				UpdateProgress();
				yield return (object)new WaitForSeconds(0.2f);
			}
		}

		[ServerRpc]
		public void SendBytesToServerRpc(byte[] audioSegment, string audioName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: 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_00ce: 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_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: 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_014b: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId)
				{
					if ((int)networkManager.LogLevel <= 1)
					{
						Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!");
					}
					return;
				}
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3131260794u, val, (RpcDelivery)0);
				bool flag = audioSegment != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioSegment, default(ForPrimitives));
				}
				bool flag2 = audioName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(audioName, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3131260794u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				Debug.Log((object)("Sending segment to server: " + audioName));
				ReceiveBytesClientRpc(audioSegment, audioName);
			}
		}

		[ClientRpc]
		public void ReceiveAudioMetaDataClientRpc(int totalSegments, string fileName)
		{
			//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_0071: 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_009b: 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 = ((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(1027341762u, val, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, totalSegments);
				bool flag = fileName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(fileName, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1027341762u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				Debug.Log((object)$"Received metadata on client: {totalSegments} segments expected, file name: {fileName}");
				audioFileName = fileName;
				receivedAudioSegments.Clear();
			}
		}

		[ClientRpc]
		public void ReceiveBytesClientRpc(byte[] audioSegment, string audioName)
		{
			//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_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_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 != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2945580654u, val, (RpcDelivery)0);
				bool flag = audioSegment != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioSegment, default(ForPrimitives));
				}
				bool flag2 = audioName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(audioName, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2945580654u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((NetworkBehaviour)this).IsServer && hasAcceptedSync)
			{
				if (!string.IsNullOrEmpty(audioName) && audioFileName != audioName)
				{
					ProcessLastAudioFile();
					audioFileName = audioName;
				}
				receivedAudioSegments.Add(audioSegment);
			}
		}

		[ClientRpc]
		private void DisplayStartingSyncMessageClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3964799390u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3964799390u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				if (hasAcceptedSync)
				{
					Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Starting audio synchronization. Please wait...", isWarning: false);
					Plugin.Instance.DeleteTempFolder();
				}
				else if (((NetworkBehaviour)this).IsServer)
				{
					Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Initiating audio synchronization. Sending files to clients...", isWarning: false);
				}
			}
		}

		private void UpdateProgress()
		{
			float progress = (float)processedSegments / (float)totalSegments;
			int currentThresholdIndex = GetCurrentThresholdIndex(progress);
			if (currentThresholdIndex > lastThresholdIndex)
			{
				lastThresholdIndex = currentThresholdIndex;
				UpdateProgressClientRpc(progress);
			}
		}

		private int GetCurrentThresholdIndex(float progress)
		{
			for (int num = progressThresholds.Length - 1; num >= 0; num--)
			{
				if (progress >= progressThresholds[num])
				{
					return num;
				}
			}
			return -1;
		}

		[ClientRpc]
		private void UpdateProgressClientRpc(float progress)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3902617409u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref progress, default(ForPrimitives));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3902617409u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost) || (!((NetworkBehaviour)this).IsServer && !hasAcceptedSync))
			{
				return;
			}
			string text = GenerateProgressBar(progress);
			if (progress < 1f)
			{
				if (!((NetworkBehaviour)this).IsServer)
				{
					Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Sounds transfer progression:\n" + text, isWarning: false);
				}
			}
			else if (((NetworkBehaviour)this).IsServer)
			{
				Plugin.Instance.ShowCustomTip("CustomSounds Sync", "All sounds have been successfully sent!", isWarning: false);
			}
			else
			{
				Plugin.Instance.ShowCustomTip("CustomSounds Sync", "All sounds have been successfully received!", isWarning: false);
			}
		}

		private string GenerateProgressBar(float progress)
		{
			int num = 26;
			progress = Mathf.Clamp(progress, 0f, 1f);
			int num2 = (int)(progress * (float)num);
			return "[" + new string('#', num2) + new string('-', num - num2) + "] " + (int)(progress * 100f) + "%";
		}

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

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_AudioNetworkHandler()
		{
			//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
			NetworkManager.__rpc_func_table.Add(3186703908u, new RpcReceiveHandler(__rpc_handler_3186703908));
			NetworkManager.__rpc_func_table.Add(152710787u, new RpcReceiveHandler(__rpc_handler_152710787));
			NetworkManager.__rpc_func_table.Add(3960362720u, new RpcReceiveHandler(__rpc_handler_3960362720));
			NetworkManager.__rpc_func_table.Add(234624598u, new RpcReceiveHandler(__rpc_handler_234624598));
			NetworkManager.__rpc_func_table.Add(3991320206u, new RpcReceiveHandler(__rpc_handler_3991320206));
			NetworkManager.__rpc_func_table.Add(3131260794u, new RpcReceiveHandler(__rpc_handler_3131260794));
			NetworkManager.__rpc_func_table.Add(1027341762u, new RpcReceiveHandler(__rpc_handler_1027341762));
			NetworkManager.__rpc_func_table.Add(2945580654u, new RpcReceiveHandler(__rpc_handler_2945580654));
			NetworkManager.__rpc_func_table.Add(3964799390u, new RpcReceiveHandler(__rpc_handler_3964799390));
			NetworkManager.__rpc_func_table.Add(3902617409u, new RpcReceiveHandler(__rpc_handler_3902617409));
		}

		private static void __rpc_handler_3186703908(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;
				((AudioNetworkHandler)(object)target).RequestSyncClientRpc(clientId);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_152710787(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_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				ServerRpcParams server = rpcParams.Server;
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((AudioNetworkHandler)(object)target).NotifyClientsQueueCompletedServerRpc(server);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3960362720(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;
				((AudioNetworkHandler)(object)target).ForceUnsyncClientsClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_234624598(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;
				((AudioNetworkHandler)(object)target).ProcessLastAudioFileClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3991320206(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_0070: 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_008f: 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
			//IL_00bb: 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)
			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!");
				}
				return;
			}
			int num = default(int);
			ByteUnpacker.ReadValueBitPacked(reader, ref num);
			bool flag = default(bool);
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
			string fileName = null;
			if (flag)
			{
				((FastBufferReader)(ref reader)).ReadValueSafe(ref fileName, false);
			}
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((AudioNetworkHandler)(object)target).SendAudioMetaDataToClientsServerRpc(num, fileName);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}

		private static void __rpc_handler_3131260794(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Invalid comparison between Unknown and I4
			//IL_00c1: 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_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: 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)
			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!");
				}
				return;
			}
			bool flag = default(bool);
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
			byte[] audioSegment = null;
			if (flag)
			{
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioSegment, default(ForPrimitives));
			}
			bool flag2 = default(bool);
			((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
			string audioName = null;
			if (flag2)
			{
				((FastBufferReader)(ref reader)).ReadValueSafe(ref audioName, false);
			}
			target.__rpc_exec_stage = (__RpcExecStage)1;
			((AudioNetworkHandler)(object)target).SendBytesToServerRpc(audioSegment, audioName);
			target.__rpc_exec_stage = (__RpcExecStage)0;
		}

		private static void __rpc_handler_1027341762(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_006e: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int num = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref num);
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string fileName = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref fileName, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((AudioNetworkHandler)(object)target).ReceiveAudioMetaDataClientRpc(num, fileName);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2945580654(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_00a6: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				byte[] audioSegment = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioSegment, default(ForPrimitives));
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				string audioName = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref audioName, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((AudioNetworkHandler)(object)target).ReceiveBytesClientRpc(audioSegment, audioName);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3964799390(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;
				((AudioNetworkHandler)(object)target).DisplayStartingSyncMessageClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3902617409(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 progress = default(float);
				((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref progress, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((AudioNetworkHandler)(object)target).UpdateProgressClientRpc(progress);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

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

BooBoo Building/BepInEx/plugins/Drakorle-MoreItems/MoreItems.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MoreItems.Patches;

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

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MoreItems is loaded!");
			harmony.PatchAll(typeof(StartOfRoundPatch));
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "MoreItems";

		public const string PLUGIN_NAME = "MoreItems";

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

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void IncreaseShipItemCapacity(ref int ___maxShipItemCapacity)
		{
			___maxShipItemCapacity = 999;
			Logger.CreateLogSource("MoreItems").LogInfo((object)$"Maximum amount of items that can be saved set to {999}.");
		}
	}
}

BooBoo Building/BepInEx/plugins/EliteMasterEric-SlimeTamingFix/SlimeTamingFix.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("EliteMasterEric")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Fixes a bug that made Hygroderes unable to be tamed with Boomboxes.")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2+38f01b21fff41249851eaa3d5a7686cfd554bb79")]
[assembly: AssemblyProduct("SlimeTamingFix")]
[assembly: AssemblyTitle("SlimeTamingFix")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SlimeTamingFix
{
	public static class PluginInfo
	{
		public const string PLUGIN_ID = "SlimeTamingFix";

		public const string PLUGIN_NAME = "SlimeTamingFix";

		public const string PLUGIN_VERSION = "1.0.2";

		public const string PLUGIN_GUID = "com.elitemastereric.slimetamingfix";
	}
	[BepInPlugin("com.elitemastereric.slimetamingfix", "SlimeTamingFix", "1.0.2")]
	public class Plugin : BaseUnityPlugin
	{
		public ManualLogSource PluginLogger;

		public static Plugin Instance { get; private set; }

		private void Awake()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			Instance = this;
			PluginLogger = ((BaseUnityPlugin)this).Logger;
			Harmony val = new Harmony("com.elitemastereric.slimetamingfix");
			val.PatchAll();
			PluginLogger.LogInfo((object)"Plugin SlimeTamingFix (com.elitemastereric.slimetamingfix) is loaded!");
		}
	}
}
namespace SlimeTamingFix.Patch
{
	[HarmonyPatch(typeof(BlobAI))]
	[HarmonyPatch("OnCollideWithPlayer")]
	internal class BlobAIOnCollideWithPlayerPatch
	{
		public static bool Prefix(BlobAI __instance)
		{
			float value = Traverse.Create((object)__instance).Field("tamedTimer").GetValue<float>();
			float value2 = Traverse.Create((object)__instance).Field("angeredTimer").GetValue<float>();
			if (value > 0f && value2 <= 0f)
			{
				return false;
			}
			return true;
		}
	}
}

BooBoo Building/BepInEx/plugins/FlipMods-LetMeLookDown/LetMeLookDown.dll

Decompiled 9 months ago
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using GameNetcodeStuff;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("LetMeLookDown")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LetMeLookDown")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("a9c88d54-8f01-44a7-be0d-bd61d38aadcb")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace LetMeLookDown
{
	[BepInPlugin("FlipMods.LetMeLookDown", "LetMeLookDown", "1.0.1")]
	public class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		private static Plugin instance;

		public static float maxAngle = 80f;

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

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

		public const string PLUGIN_NAME = "LetMeLookDown";

		public const string PLUGIN_VERSION = "1.0.1";
	}
}
namespace LetMeLookDown.Patches
{
	[HarmonyPatch]
	internal class AdjustSmoothLookingPatcher
	{
		[HarmonyPatch(typeof(PlayerControllerB), "CalculateSmoothLookingInput")]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 60f)
				{
					list[i].operand = Plugin.maxAngle;
					break;
				}
			}
			return list.AsEnumerable();
		}
	}
	[HarmonyPatch]
	internal class AdjustNormalLookingPatcher
	{
		[HarmonyPatch(typeof(PlayerControllerB), "CalculateNormalLookingInput")]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 60f)
				{
					list[i].operand = Plugin.maxAngle;
					break;
				}
			}
			return list.AsEnumerable();
		}
	}
}

BooBoo Building/BepInEx/plugins/FlipMods-ObjectVolumeController/ObjectVolumeController.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using GameNetcodeStuff;
using HarmonyLib;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ObjectVolumeController")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ObjectVolumeController")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("49ff2710-6c88-48c4-989a-32b79f0ddd6a")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ObjectVolumeController
{
	[BepInPlugin("FlipMods.ObjectVolumeController", "ObjectVolumeController", "1.0.3")]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		private Harmony _harmony;

		public static Key volumeUpKey = (Key)14;

		public static Key volumeDownKey = (Key)13;

		public static string volumeHoverTip = "Volume up:   [+]\nVolume down: [-]";

		public static float volumeIncrement = 0.1f;

		public static float maxDisplayedVolume = 1.5f;

		public static float defaultVolume = 1f;

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

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

		public const string PLUGIN_NAME = "ObjectVolumeController";

		public const string PLUGIN_VERSION = "1.0.3";
	}
}
namespace ObjectVolumeController.Patcher
{
	[HarmonyPatch]
	internal class ChangeVolumePatcher
	{
		private static AudioPlayerItemType boomboxItems = new AudioPlayerItemType("Boomboxes", "Grab boombox: [E]");

		private static AudioPlayerPlaceableType recordPlayers = new AudioPlayerPlaceableType("Record players", "Record player: [E]");

		private static AudioPlayerPlaceableType televisions = new AudioPlayerPlaceableType("Televisions", "Television: [E]");

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPrefix]
		public static void GetObjectLookingAt(PlayerControllerB __instance)
		{
			boomboxItems.lookingAtDeviceType = false;
			recordPlayers.lookingAtDeviceType = false;
			televisions.lookingAtDeviceType = false;
			if (!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || __instance.inTerminalMenu || __instance.isTypingChat || __instance.isPlayerDead)
			{
				return;
			}
			InteractTrigger hoveringOverTrigger = __instance.hoveringOverTrigger;
			object obj;
			if (hoveringOverTrigger == null)
			{
				obj = null;
			}
			else
			{
				Transform parent = ((Component)hoveringOverTrigger).transform.parent;
				obj = ((parent != null) ? ((Component)parent).gameObject : null);
			}
			GameObject val = (GameObject)obj;
			if ((Object)(object)val != (Object)null)
			{
				if (((Object)val).name.Contains("RecordPlayer"))
				{
					recordPlayers.lookingAtDeviceType = true;
				}
				else if (((Object)val).name.Contains("Television"))
				{
					televisions.lookingAtDeviceType = true;
				}
			}
			if (!recordPlayers.lookingAtDeviceType && !televisions.lookingAtDeviceType)
			{
				if ((Object)(object)__instance.cursorTip != (Object)null && ((TMP_Text)__instance.cursorTip).text.Contains(boomboxItems.originalHoverTip))
				{
					boomboxItems.lookingAtDeviceType = true;
				}
				else if ((Object)(object)__instance.currentlyHeldObjectServer != (Object)null && __instance.currentlyHeldObjectServer is BoomboxItem)
				{
					boomboxItems.lookingAtDeviceType = true;
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		public static void GetVolumeInput(PlayerControllerB __instance)
		{
			if (!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || __instance.inTerminalMenu || __instance.isTypingChat || __instance.isPlayerDead || (!boomboxItems.lookingAtDeviceType && !recordPlayers.lookingAtDeviceType && !televisions.lookingAtDeviceType))
			{
				return;
			}
			float num = 0f;
			if (((ButtonControl)Keyboard.current.minusKey).wasPressedThisFrame)
			{
				num = 0f - Plugin.volumeIncrement;
			}
			if (((ButtonControl)Keyboard.current.equalsKey).wasPressedThisFrame)
			{
				num = Plugin.volumeIncrement;
			}
			if (num != 0f)
			{
				Plugin.Log("AdjustVolume: " + num);
				AudioPlayerTypeBase audioPlayerTypeBase = null;
				if (boomboxItems.lookingAtDeviceType)
				{
					audioPlayerTypeBase = boomboxItems;
				}
				else if (recordPlayers.lookingAtDeviceType)
				{
					audioPlayerTypeBase = recordPlayers;
				}
				else if (televisions.lookingAtDeviceType)
				{
					audioPlayerTypeBase = televisions;
				}
				if (audioPlayerTypeBase != null)
				{
					audioPlayerTypeBase.currentVolume = Mathf.Clamp(audioPlayerTypeBase.currentVolume + num, 0f, Plugin.maxDisplayedVolume);
					audioPlayerTypeBase.UpdateVolumes();
					audioPlayerTypeBase.UpdateTooltips();
					Plugin.Log($"[{audioPlayerTypeBase.name}] Updating volume to: {audioPlayerTypeBase.currentVolume}%");
				}
			}
		}

		[HarmonyPatch(typeof(BoomboxItem), "Start")]
		[HarmonyPostfix]
		public static void SetBoomboxHoverTip(BoomboxItem __instance)
		{
			boomboxItems.audioSources.Add(__instance.boomboxAudio);
			boomboxItems.items.Add((GrabbableObject)(object)__instance);
			((GrabbableObject)__instance).itemProperties.canBeGrabbedBeforeGameStart = true;
			if (boomboxItems.defaultVolume == 0f)
			{
				boomboxItems.defaultVolume = __instance.boomboxAudio.volume;
				Plugin.Log("Boombox volume: " + boomboxItems.defaultVolume);
			}
			if (boomboxItems.controlTooltips == null)
			{
				boomboxItems.controlTooltips = new List<string>(((GrabbableObject)__instance).itemProperties.toolTips);
				boomboxItems.controlTooltips.Add("");
			}
			boomboxItems.UpdateTooltips();
			boomboxItems.UpdateVolumes();
		}

		[HarmonyPatch(typeof(AutoParentToShip), "Awake")]
		[HarmonyPostfix]
		public static void SetRecordPlayerHoverTip(AutoParentToShip __instance)
		{
			if (((Object)__instance).name.Contains("RecordPlayerContainer"))
			{
				AudioSource val = ((Component)__instance).GetComponentInChildren<AnimatedObjectTrigger>()?.thisAudioSource;
				if ((Object)(object)val != (Object)null)
				{
					recordPlayers.audioSources.Add(val);
				}
				InteractTrigger componentInChildren = ((Component)__instance).GetComponentInChildren<InteractTrigger>();
				if (recordPlayers.defaultVolume == 0f)
				{
					recordPlayers.defaultVolume = val.volume;
					Plugin.Log("RecordPlayer Volume: " + recordPlayers.defaultVolume);
				}
				if ((Object)(object)componentInChildren == (Object)null)
				{
					Plugin.Log("Record player trigger missing!");
					return;
				}
				recordPlayers.triggers.Add(componentInChildren);
				recordPlayers.UpdateTooltips();
				recordPlayers.UpdateVolumes();
			}
		}

		[HarmonyPatch(typeof(TVScript), "__initializeVariables")]
		[HarmonyPostfix]
		public static void SetTelevisionHoverTip(TVScript __instance)
		{
			televisions.audioSources.Add(__instance.tvSFX);
			Transform parent = ((Component)__instance).transform.parent;
			InteractTrigger val = ((parent != null) ? ((Component)parent).GetComponentInChildren<InteractTrigger>() : null);
			if (televisions.defaultVolume == 0f)
			{
				televisions.defaultVolume = __instance.tvSFX.volume;
				Plugin.Log("Television volume: " + televisions.defaultVolume);
			}
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log("Television trigger missing!");
				return;
			}
			televisions.triggers.Add(val);
			televisions.UpdateTooltips();
			televisions.UpdateVolumes();
		}
	}
	internal abstract class AudioPlayerTypeBase
	{
		public string name;

		public List<AudioSource> audioSources;

		public string originalHoverTip;

		public float defaultVolume;

		public float currentVolume;

		public bool lookingAtDeviceType;

		public Type objectType;

		public AudioPlayerTypeBase(string name, string originalHoverTip = "", float defaultVolume = 0f)
		{
			this.name = name;
			audioSources = new List<AudioSource>();
			this.originalHoverTip = originalHoverTip;
			this.defaultVolume = defaultVolume;
			currentVolume = Plugin.defaultVolume;
			lookingAtDeviceType = false;
		}

		public void UpdateVolumes()
		{
			for (int i = 0; i < audioSources.Count; i++)
			{
				if ((Object)(object)audioSources[i] != (Object)null)
				{
					audioSources[i].volume = currentVolume / Plugin.maxDisplayedVolume;
				}
			}
		}

		public abstract void UpdateTooltips();
	}
	internal class AudioPlayerItemType : AudioPlayerTypeBase
	{
		public List<GrabbableObject> items;

		public List<string> controlTooltips;

		public AudioPlayerItemType(string name, string originalHoverTip = "", float defaultVolume = 0f)
			: base(name, originalHoverTip, defaultVolume)
		{
			items = new List<GrabbableObject>();
		}

		public override void UpdateTooltips()
		{
			for (int i = 0; i < items.Count; i++)
			{
				if ((Object)(object)items[i] != (Object)null)
				{
					items[i].customGrabTooltip = $"{originalHoverTip}\n{Mathf.RoundToInt(currentVolume * 10f) * 10}% volume\n{Plugin.volumeHoverTip}";
					controlTooltips[controlTooltips.Count - 1] = items[i].customGrabTooltip.Replace(originalHoverTip + "\n", "");
					items[i].itemProperties.toolTips = controlTooltips.ToArray();
				}
			}
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if ((Object)(object)localPlayerController != (Object)null && (Object)(object)localPlayerController.currentlyHeldObjectServer != (Object)null && items.Contains(localPlayerController.currentlyHeldObjectServer))
			{
				localPlayerController.currentlyHeldObjectServer.EquipItem();
			}
		}
	}
	internal class AudioPlayerPlaceableType : AudioPlayerTypeBase
	{
		public List<InteractTrigger> triggers;

		public AudioPlayerPlaceableType(string name, string originalHoverTip = "", float defaultVolume = 0f)
			: base(name, originalHoverTip, defaultVolume)
		{
			triggers = new List<InteractTrigger>();
		}

		public override void UpdateTooltips()
		{
			for (int i = 0; i < triggers.Count; i++)
			{
				if ((Object)(object)triggers[i] != (Object)null)
				{
					triggers[i].hoverTip = $"{originalHoverTip}\n{Mathf.RoundToInt(currentVolume * 10f) * 10}% volume\n{Plugin.volumeHoverTip}";
				}
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/FlipMods-ReservedFlashlightSlot/ReservedFlashlightSlot.dll

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

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

		public static ConfigEntry<bool> hideFlashlightMeshShoulder;

		public static string activateFlashlightDisplayName;

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

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			activateFlashlightKey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedFlashlightSlot", "ActivateFlashlightKey", "<Keyboard>/f", "Activate flashlight keybind.");
			hideFlashlightMeshShoulder = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedFlashlightSlot", "HideFlashlightOnShoulder", false, "Hides the flashlight mesh while on your shoulder. Only applies in scenarios where you can view your player in third person.");
			activateFlashlightDisplayName = GetDisplayName(activateFlashlightKey.Value);
			currentConfigEntries.Add(((ConfigEntryBase)activateFlashlightKey).Definition.Key, (ConfigEntryBase)(object)activateFlashlightKey);
			currentConfigEntries.Add(((ConfigEntryBase)hideFlashlightMeshShoulder).Definition.Key, (ConfigEntryBase)(object)hideFlashlightMeshShoulder);
			TryRemoveOldConfigSettings();
		}

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

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

		private static InputAction activateFlashlightAction;

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void OnLocalPlayerConnect(PlayerControllerB __instance)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			localPlayerController = __instance;
			activateFlashlightAction = new InputAction((string)null, (InputActionType)0, ConfigSettings.activateFlashlightKey.Value, "Press", (string)null, (string)null);
			if (((Component)localPlayerController).gameObject.activeSelf)
			{
				SubscribeToEvents();
			}
		}

		private static void SubscribeToEvents()
		{
			if (activateFlashlightAction != null)
			{
				activateFlashlightAction.Enable();
				activateFlashlightAction.performed += OnActivateFlashlightPerformed;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "OnEnable")]
		[HarmonyPostfix]
		public static void OnEnable(PlayerControllerB __instance)
		{
			if ((Object)(object)__instance == (Object)(object)localPlayerController)
			{
				SubscribeToEvents();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "OnDisable")]
		[HarmonyPostfix]
		public static void OnDisable(PlayerControllerB __instance)
		{
			if (activateFlashlightAction != null && !((Object)(object)__instance != (Object)(object)localPlayerController))
			{
				activateFlashlightAction.performed -= OnActivateFlashlightPerformed;
				activateFlashlightAction.Disable();
			}
		}

		private static void OnActivateFlashlightPerformed(CallbackContext context)
		{
			if ((Object)(object)localPlayerController == (Object)null || !localPlayerController.isPlayerControlled || localPlayerController.inTerminalMenu || (((NetworkBehaviour)localPlayerController).IsServer && !localPlayerController.isHostPlayerObject))
			{
				return;
			}
			FlashlightItem mainFlashlight = Patcher.GetMainFlashlight(localPlayerController);
			if (((CallbackContext)(ref context)).performed && !((Object)(object)mainFlashlight == (Object)null))
			{
				float num = (float)Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").GetValue();
				if (!(num < 0.075f))
				{
					((GrabbableObject)mainFlashlight).UseItemOnClient(!((GrabbableObject)mainFlashlight).isBeingUsed);
					Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0);
				}
			}
		}
	}
	[BepInPlugin("FlipMods.ReservedFlashlightSlot", "ReservedFlashlightSlot", "1.5.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		private Harmony _harmony;

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

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

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

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

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

		public const string PLUGIN_NAME = "ReservedFlashlightSlot";

		public const string PLUGIN_VERSION = "1.5.3";
	}
}
namespace ReservedFlashlightSlot.Patches
{
	[HarmonyPatch]
	internal static class Patcher
	{
		private static Vector3 playerShoulderPositionOffset = new Vector3(0.2f, 0.25f, 0f);

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

		private static string originalControlTooltip = "";

		public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController;

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

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

		public static FlashlightItem GetReservedFlashlight(PlayerControllerB playerController)
		{
			GrabbableObject obj = ((playerController != null) ? playerController.ItemSlots[Plugin.flashlightInfo.indexInInventory] : null);
			return (FlashlightItem)(object)((obj is FlashlightItem) ? obj : null);
		}

		public static FlashlightItem GetCurrentlySelectedFlashlight(PlayerControllerB playerController)
		{
			GrabbableObject obj = ((playerController != null) ? playerController.ItemSlots[playerController.currentItemSlot] : null);
			return (FlashlightItem)(object)((obj is FlashlightItem) ? obj : null);
		}

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

		[HarmonyPatch(typeof(FlashlightItem), "__initializeVariables")]
		[HarmonyPostfix]
		public static void EditTooltips(FlashlightItem __instance)
		{
			if (originalControlTooltip == "")
			{
				originalControlTooltip = ((GrabbableObject)__instance).itemProperties.toolTips[((GrabbableObject)__instance).itemProperties.toolTips.Length - 1];
			}
			((GrabbableObject)__instance).itemProperties.toolTips[((GrabbableObject)__instance).itemProperties.toolTips.Length - 1] = $"{originalControlTooltip}[{ConfigSettings.activateFlashlightDisplayName.ToUpper()}]";
		}

		[HarmonyPatch(typeof(MenuManager), "OnEnable")]
		[HarmonyPostfix]
		public static void ResetVariables()
		{
			Keybinds.localPlayerController = null;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_performed")]
		[HarmonyPrefix]
		public static bool PreventActivatingDuplicateItem(CallbackContext context, PlayerControllerB __instance)
		{
			FlashlightItem currentlySelectedFlashlight = GetCurrentlySelectedFlashlight(__instance);
			if ((Object)(object)__instance != (Object)(object)localPlayerController || (Object)(object)currentlySelectedFlashlight == (Object)null)
			{
				return true;
			}
			if (!((CallbackContext)(ref context)).performed)
			{
				return false;
			}
			return true;
		}

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

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

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

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

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

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

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

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

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

		private static void UpdateFlashlightState(FlashlightItem flashlightItem, bool active)
		{
			if (!((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)null))
			{
				PlayerControllerB playerHeldBy = ((GrabbableObject)flashlightItem).playerHeldBy;
				((GrabbableObject)flashlightItem).isBeingUsed = active;
				bool flag = (Object)(object)playerHeldBy != (Object)(object)localPlayerController || (Object)(object)playerHeldBy.ItemSlots[playerHeldBy.currentItemSlot] == (Object)(object)flashlightItem;
				((Behaviour)flashlightItem.flashlightBulb).enabled = active && flag;
				((Behaviour)flashlightItem.flashlightBulbGlow).enabled = active && flag;
				flashlightItem.usingPlayerHelmetLight = active && !flag;
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/FlipMods-ReservedItemSlotCore/ReservedItemSlotCore.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using ReservedItemSlotCore.Config;
using ReservedItemSlotCore.Networking;
using ReservedItemSlotCore.Patches;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ReservedItemSlotCore")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReservedItemSlotCore")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("238ce080-e339-46b6-9b08-992a950453a1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("ReservedFlashlightSlot")]
[assembly: InternalsVisibleTo("ReservedWalkieSlot")]
[assembly: InternalsVisibleTo("ReservedBoomboxSlot")]
[assembly: InternalsVisibleTo("ReservedSprayPaintSlot")]
[assembly: InternalsVisibleTo("ReservedWeaponSlot")]
[assembly: InternalsVisibleTo("ReservedUtilitySlot")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ReservedItemSlotCore
{
	internal class ReservedPlayerData
	{
		public ReservedItemInfo grabbingReservedItem = null;

		public int previousHotbarIndex = -1;

		public bool inReservedHotbarSlots = false;

		public int reservedHotbarStartIndex = 4;
	}
	[HarmonyPatch]
	internal static class SyncManager
	{
		public static PlayerControllerB localPlayerController;

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

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

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

		public static bool flashlightSlotLoaded;

		public static bool walkieSlotLoaded;

		public static bool weaponSlotLoaded;

		public static bool sprayPaintSlotLoaded;

		public static bool isSynced = false;

		public static int numReservedItemSlots => syncReservedItemSlotReps.Count;

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

		public static ReservedItemInfo GetReservedItemInfo(string itemName)
		{
			return IsReservedItem(itemName) ? syncReservedItemsDict[itemName] : null;
		}

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

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

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void Init(PlayerControllerB __instance)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: 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_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Expected O, but got Unknown
			localPlayerController = __instance;
			syncReservedItemsDict = ReservedItemInfo.reservedItemsDict;
			syncReservedItemsList = ReservedItemInfo.reservedItemsList;
			syncReservedItemSlotReps = ReservedItemInfo.reservedItemSlotReps;
			flashlightSlotLoaded = Plugin.reservedFlashlightSlotLoaded;
			walkieSlotLoaded = Plugin.reservedWalkieSlotLoaded;
			weaponSlotLoaded = Plugin.reservedWeaponSlotLoaded;
			sprayPaintSlotLoaded = Plugin.reservedSprayPaintSlotLoaded;
			NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-OnSwapHotbarClientRpc", new HandleNamedMessageDelegate(OnSwapHotbarClientRpc));
			if (NetworkManager.Singleton.IsServer)
			{
				isSynced = true;
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-OnSwapHotbarServerRpc", new HandleNamedMessageDelegate(OnSwapHotbarServerRpc));
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-RequestSyncServerRpc", new HandleNamedMessageDelegate(RequestSyncServerRpc));
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-RequestSyncClientRpc", new HandleNamedMessageDelegate(RequestSyncClientRpc));
				{
					foreach (ReservedItemInfo syncReservedItems in syncReservedItemsList)
					{
						ReservedItemInfo reservedItemInfo = ReservedItemInfo.reservedItemsDictDefault[syncReservedItems.itemName];
						syncReservedItems.hotbarSlotPriority = reservedItemInfo.hotbarSlotPriority;
						syncReservedItems.reservedItemIndex = reservedItemInfo.reservedItemIndex;
						syncReservedItems.forceUpdateCanBeGrabbedBeforeGameStart = reservedItemInfo.forceUpdateCanBeGrabbedBeforeGameStart;
						syncReservedItems.canBeGrabbedBeforeGameStart = reservedItemInfo.canBeGrabbedBeforeGameStart;
						syncReservedItems.forceUpdateRequiresBattery = reservedItemInfo.forceUpdateRequiresBattery;
						syncReservedItems.requiresBattery = reservedItemInfo.requiresBattery;
					}
					return;
				}
			}
			isSynced = false;
			NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-RequestSyncClientRpc", new HandleNamedMessageDelegate(RequestSyncClientRpc));
			RequestSyncWithServer();
		}

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

		private static void RequestSyncServerRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_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_00b3: 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_00ce: 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_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: 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_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: 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_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: 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_01d1: 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_01ea: 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_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer)
			{
				return;
			}
			Plugin.Log("Receiving sync request from client: " + clientId);
			int num = 8 * syncReservedItemsList.Count;
			foreach (ReservedItemInfo syncReservedItems in syncReservedItemsList)
			{
				num += 4 + 2 * syncReservedItems.itemName.Length;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(4 + num, (Allocator)2, -1);
			bool reservedFlashlightSlotLoaded = Plugin.reservedFlashlightSlotLoaded;
			((FastBufferWriter)(ref val)).WriteValue<bool>(ref reservedFlashlightSlotLoaded, default(ForPrimitives));
			reservedFlashlightSlotLoaded = Plugin.reservedWalkieSlotLoaded;
			((FastBufferWriter)(ref val)).WriteValue<bool>(ref reservedFlashlightSlotLoaded, default(ForPrimitives));
			reservedFlashlightSlotLoaded = Plugin.reservedWeaponSlotLoaded;
			((FastBufferWriter)(ref val)).WriteValue<bool>(ref reservedFlashlightSlotLoaded, default(ForPrimitives));
			reservedFlashlightSlotLoaded = Plugin.reservedSprayPaintSlotLoaded;
			((FastBufferWriter)(ref val)).WriteValue<bool>(ref reservedFlashlightSlotLoaded, default(ForPrimitives));
			int count = syncReservedItemsList.Count;
			((FastBufferWriter)(ref val)).WriteValue<int>(ref count, default(ForPrimitives));
			foreach (ReservedItemInfo syncReservedItems2 in syncReservedItemsList)
			{
				count = syncReservedItems2.itemName.Length;
				((FastBufferWriter)(ref val)).WriteValue<int>(ref count, default(ForPrimitives));
				string itemName = syncReservedItems2.itemName;
				for (int i = 0; i < itemName.Length; i++)
				{
					char c = itemName[i];
					((FastBufferWriter)(ref val)).WriteValue<char>(ref c, default(ForPrimitives));
				}
				((FastBufferWriter)(ref val)).WriteValue<int>(ref syncReservedItems2.hotbarSlotPriority, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValue<bool>(ref syncReservedItems2.forceUpdateCanBeGrabbedBeforeGameStart, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValue<bool>(ref syncReservedItems2.canBeGrabbedBeforeGameStart, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValue<bool>(ref syncReservedItems2.forceUpdateRequiresBattery, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValue<bool>(ref syncReservedItems2.requiresBattery, default(ForPrimitives));
			}
			Plugin.Log("Sent sync to client");
			NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("ReservedItemSlots-RequestSyncClientRpc", clientId, val, (NetworkDelivery)3);
		}

		private static void RequestSyncClientRpc(ulong clientId, FastBufferReader reader)
		{
			//IL_006b: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: 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_0128: 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_0144: 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_0170: 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_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: 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_0214: 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_022c: 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_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsClient || NetworkManager.Singleton.IsServer || !((FastBufferReader)(ref reader)).TryBeginRead(8))
			{
				return;
			}
			isSynced = true;
			syncReservedItemsDict = new Dictionary<string, ReservedItemInfo>();
			syncReservedItemsList = new List<ReservedItemInfo>();
			syncReservedItemSlotReps = new List<ReservedItemInfo>();
			Plugin.Log("Receiving sync from server.");
			((FastBufferReader)(ref reader)).ReadValue<bool>(ref flashlightSlotLoaded, default(ForPrimitives));
			((FastBufferReader)(ref reader)).ReadValue<bool>(ref walkieSlotLoaded, default(ForPrimitives));
			((FastBufferReader)(ref reader)).ReadValue<bool>(ref weaponSlotLoaded, default(ForPrimitives));
			((FastBufferReader)(ref reader)).ReadValue<bool>(ref sprayPaintSlotLoaded, default(ForPrimitives));
			Plugin.Log("FlashlightSlotLoaded: " + flashlightSlotLoaded);
			Plugin.Log("WalkieSlotLoaded: " + walkieSlotLoaded);
			Plugin.Log("WeaponSlotLoaded: " + weaponSlotLoaded);
			Plugin.Log("SprayPaintSlotLoaded: " + sprayPaintSlotLoaded);
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives));
			int num2 = default(int);
			char c = default(char);
			for (int i = 0; i < num; i++)
			{
				((FastBufferReader)(ref reader)).ReadValue<int>(ref num2, default(ForPrimitives));
				((FastBufferReader)(ref reader)).TryBeginRead(2 * num2);
				string text = "";
				for (int j = 0; j < num2; j++)
				{
					((FastBufferReader)(ref reader)).ReadValue<char>(ref c, default(ForPrimitives));
					text += c;
				}
				bool flag = ReservedItemInfo.reservedItemsDict.ContainsKey(text);
				ReservedItemInfo reservedItemInfo = (ReservedItemInfo.reservedItemsDict.ContainsKey(text) ? ReservedItemInfo.reservedItemsDict[text] : new ReservedItemInfo
				{
					itemName = text
				});
				((FastBufferReader)(ref reader)).ReadValue<int>(ref reservedItemInfo.hotbarSlotPriority, default(ForPrimitives));
				((FastBufferReader)(ref reader)).ReadValue<bool>(ref reservedItemInfo.forceUpdateCanBeGrabbedBeforeGameStart, default(ForPrimitives));
				((FastBufferReader)(ref reader)).ReadValue<bool>(ref reservedItemInfo.canBeGrabbedBeforeGameStart, default(ForPrimitives));
				((FastBufferReader)(ref reader)).ReadValue<bool>(ref reservedItemInfo.forceUpdateRequiresBattery, default(ForPrimitives));
				((FastBufferReader)(ref reader)).ReadValue<bool>(ref reservedItemInfo.requiresBattery, default(ForPrimitives));
				Plugin.Log("RECEIVING INFO - Item: " + reservedItemInfo.itemName + " Prio: " + reservedItemInfo.hotbarSlotPriority + " INFO EXISTS: " + flag);
				ReservedItemInfo.AddItemInfoToList(reservedItemInfo, syncReservedItemsList, syncReservedItemsDict, syncReservedItemSlotReps);
			}
			Plugin.Log("Received sync for " + syncReservedItemSlotReps.Count + " reserved item slots. (" + syncReservedItemsList.Count + " items total)");
		}

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

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

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

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

		public static void SwapHotbarSlot(int hotbarIndex)
		{
			SendSwapHotbarUpdate(hotbarIndex);
			CallSwitchToItemSlotMethod(localPlayerController, hotbarIndex);
			Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0);
		}

		private static void CallSwitchToItemSlotMethod(PlayerControllerB playerController, int hotbarIndex)
		{
			if (hotbarIndex < playerController.ItemSlots.Length)
			{
				ShipBuildModeManager.Instance.CancelBuildMode(true);
				MethodInfo method = ((object)playerController).GetType().GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic);
				method.Invoke(playerController, new object[2] { hotbarIndex, null });
				if ((Object)(object)playerController.currentlyHeldObjectServer != (Object)null)
				{
					((Component)playerController.currentlyHeldObjectServer).gameObject.GetComponent<AudioSource>().PlayOneShot(playerController.currentlyHeldObjectServer.itemProperties.grabSFX, 0.6f);
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class Keybinds
	{
		public static PlayerControllerB localPlayerController;

		public static InputAction focusReservedHotbarAction;

		public static InputAction rawScrollAction;

		public static bool holdingModifierKey;

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void OnLocalPlayerConnect(PlayerControllerB __instance)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			localPlayerController = __instance;
			focusReservedHotbarAction = new InputAction((string)null, (InputActionType)0, ConfigSettings.focusReservedHotbarHotkey.Value, (string)null, (string)null, (string)null);
			rawScrollAction = new InputAction("Scroll", (InputActionType)0, "<Mouse>/scroll", (string)null, (string)null, (string)null);
			rawScrollAction.Enable();
			if (((Component)localPlayerController).gameObject.activeSelf)
			{
				SubscribeToEvents();
			}
		}

		private static void SubscribeToEvents()
		{
			if (focusReservedHotbarAction != null && SyncManager.numReservedItemSlots > 0)
			{
				focusReservedHotbarAction.performed += FocusReservedHotbarSlotsAction;
				if (!ConfigSettings.toggleFocusReservedHotbar.Value)
				{
					focusReservedHotbarAction.canceled += UnfocusReservedHotbarSlotsPerformed;
				}
				focusReservedHotbarAction.Enable();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "OnEnable")]
		[HarmonyPostfix]
		public static void OnEnable(PlayerControllerB __instance)
		{
			if ((Object)(object)__instance == (Object)(object)localPlayerController)
			{
				SubscribeToEvents();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "OnDisable")]
		[HarmonyPostfix]
		public static void OnDisable(PlayerControllerB __instance)
		{
			if (focusReservedHotbarAction != null && SyncManager.numReservedItemSlots > 0 && !((Object)(object)__instance != (Object)(object)localPlayerController))
			{
				focusReservedHotbarAction.performed -= FocusReservedHotbarSlotsAction;
				if (!ConfigSettings.toggleFocusReservedHotbar.Value)
				{
					focusReservedHotbarAction.canceled -= UnfocusReservedHotbarSlotsPerformed;
				}
				focusReservedHotbarAction.Disable();
			}
		}

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

		private static void UnfocusReservedHotbarSlotsPerformed(CallbackContext context)
		{
			if (!((Object)(object)localPlayerController == (Object)null) && ((NetworkBehaviour)localPlayerController).IsOwner && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject))
			{
				holdingModifierKey = false;
				if (((CallbackContext)(ref context)).canceled && ReservedItemPatcher.CanSwapToReservedHotbarSlot())
				{
					ReservedItemPatcher.FocusReservedHotbarSlots(active: false);
				}
			}
		}
	}
	[BepInPlugin("FlipMods.ReservedItemSlotCore", "ReservedItemSlotCore", "1.7.3")]
	internal class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		public static Plugin instance;

		public static bool reservedFlashlightSlotLoaded => IsModLoaded("FlipMods.ReservedFlashlightSlot");

		public static bool reservedWalkieSlotLoaded => IsModLoaded("FlipMods.ReservedWalkieSlot");

		public static bool reservedWeaponSlotLoaded => IsModLoaded("FlipMods.ReservedWeaponSlot");

		public static bool reservedSprayPaintSlotLoaded => IsModLoaded("FlipMods.ReservedSprayPaintSlot");

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

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

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

		public static int numReservedItemSlotsDefault => ReservedItemInfo.numReservedItemSlotsDefault;

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

		public static void Log(string message)
		{
			((BaseUnityPlugin)instance).Logger.LogInfo((object)message);
		}

		public static void LogError(string message)
		{
			((BaseUnityPlugin)instance).Logger.LogError((object)message);
		}

		public static void LogWarning(string message)
		{
			((BaseUnityPlugin)instance).Logger.LogWarning((object)message);
		}

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

		public static bool IsReservedItemDefault(string itemName)
		{
			return reservedItemsDictDefault.ContainsKey(itemName);
		}

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

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

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

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

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

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

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

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

		public string itemName = "";

		public HashSet<string> acceptedItemNames;

		public int hotbarSlotPriority = 0;

		public int reservedItemIndex = 0;

		public bool forceUpdateCanBeGrabbedBeforeGameStart = false;

		public bool canBeGrabbedBeforeGameStart = false;

		public bool forceUpdateRequiresBattery = false;

		public bool requiresBattery = false;

		public static int numReservedItemSlotsDefault => reservedItemSlotRepsDefault.Count;

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

		public ReservedItemInfo()
		{
		}

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

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

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

		public const string PLUGIN_NAME = "ReservedItemSlotCore";

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

		public static ConfigEntry<bool> toggleFocusReservedHotbar;

		public static ConfigEntry<bool> preventReservedItemSlotFade;

		public static string focusReservedHotbarHotkeyDisplayName;

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

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			focusReservedHotbarHotkey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedItemSlotCore", "FocusReservedItemSlotsHotkey", "<Keyboard>/leftAlt", "Which key will focus your reserved item slots hotbar to allow selcting, dropping, charging, etc.");
			toggleFocusReservedHotbar = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedItemSlotCore", "ToggleFocusReservedHotbar", false, "If set to true, swapping to the reserved hotbar slots will be toggled when pressing the hotkey rather than while holding the hotkey. Setting this option to true may have bugs at this current time.");
			preventReservedItemSlotFade = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedItemSlotCore", "PreventReservedHotbarSlotFade", false, "If true, the reserved hotbar slots will not fade with the rest of the default slots.");
			focusReservedHotbarHotkeyDisplayName = GetDisplayName(focusReservedHotbarHotkey.Value);
			currentConfigEntries.Add(((ConfigEntryBase)focusReservedHotbarHotkey).Definition.Key, (ConfigEntryBase)(object)focusReservedHotbarHotkey);
			currentConfigEntries.Add(((ConfigEntryBase)toggleFocusReservedHotbar).Definition.Key, (ConfigEntryBase)(object)toggleFocusReservedHotbar);
			currentConfigEntries.Add(((ConfigEntryBase)preventReservedItemSlotFade).Definition.Key, (ConfigEntryBase)(object)preventReservedItemSlotFade);
			TryRemoveOldConfigSettings();
		}

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

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

		private static int SERVER_EXEC_STAGE = 1;

		private static int CLIENT_EXEC_STAGE = 2;

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

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

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

		public static bool IsValidClientRpcExecStage(NetworkBehaviour __instance)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
			{
				return false;
			}
			int num = (int)Traverse.Create((object)__instance).Field("__rpc_exec_stage").GetValue();
			if ((singleton.IsServer || singleton.IsHost) && num != 2)
			{
				return false;
			}
			return true;
		}
	}
}
namespace ReservedItemSlotCore.Patches
{
	[HarmonyPatch]
	public static class HUDPatcher
	{
		private static CanvasScaler canvasScaler;

		private static AspectRatioFitter aspectRatioFitter;

		private static float iconWidth;

		private static float xPos;

		public static int startIndexReservedItemSlots;

		[HarmonyPatch(typeof(HUDManager), "Awake")]
		[HarmonyPrefix]
		public static void Initialize(HUDManager __instance)
		{
			//IL_0032: 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)
			canvasScaler = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<CanvasScaler>();
			aspectRatioFitter = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<AspectRatioFitter>();
			iconWidth = ((Component)__instance.itemSlotIconFrames[0]).GetComponent<RectTransform>().sizeDelta.x;
			xPos = canvasScaler.referenceResolution.x / 2f / aspectRatioFitter.aspectRatio - iconWidth / 4f;
		}

		public static void AddNewHotbarSlotsHud()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: 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_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c0: 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_02f0: Unknown result type (might be due to invalid IL or missing references)
			if (PlayerPatcher.reservedHotbarSize <= 0)
			{
				return;
			}
			List<Image> list = new List<Image>(HUDManager.Instance.itemSlotIconFrames);
			List<Image> list2 = new List<Image>(HUDManager.Instance.itemSlotIcons);
			float y = ((Component)HUDManager.Instance.itemSlotIconFrames[0]).GetComponent<RectTransform>().sizeDelta.y;
			Vector3 eulerAngles = ((Transform)((Component)HUDManager.Instance.itemSlotIconFrames[0]).GetComponent<RectTransform>()).eulerAngles;
			Vector3 eulerAngles2 = ((Transform)((Component)HUDManager.Instance.itemSlotIcons[0]).GetComponent<RectTransform>()).eulerAngles;
			Plugin.Log($"Adding {SyncManager.syncReservedItemSlotReps.Count} Reserved item slots to the inventory HUD. Previous inventory HUD size: {PlayerPatcher.reservedItemsStartIndex}");
			for (int i = 0; i < SyncManager.syncReservedItemSlotReps.Count; i++)
			{
				ReservedItemInfo reservedItemInfo = SyncManager.syncReservedItemSlotReps[i];
				Plugin.Log($"Adding Reserved item slot for item types [{reservedItemInfo.itemName}]. Inventory index: {list.Count}");
				float num = ((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.anchoredPosition.y + 1.125f * y * (float)i;
				Image val = Object.Instantiate<Image>(HUDManager.Instance.itemSlotIconFrames[PlayerPatcher.reservedItemsStartIndex - 1], ((Component)HUDManager.Instance.itemSlotIconFrames[0]).transform.parent);
				((Object)val).name = $"ReservedItemSlot{i} [{reservedItemInfo.itemName}]";
				((Graphic)val).rectTransform.anchoredPosition = new Vector2(xPos, num);
				((Transform)((Graphic)val).rectTransform).eulerAngles = eulerAngles;
				CanvasGroup val2 = ((Component)val).gameObject.AddComponent<CanvasGroup>();
				val2.ignoreParentGroups = ConfigSettings.preventReservedItemSlotFade.Value;
				val2.alpha = 1f;
				Image component = ((Component)((Component)val).transform.GetChild(0)).GetComponent<Image>();
				((Object)component).name = "Icon";
				((Transform)((Graphic)component).rectTransform).eulerAngles = eulerAngles2;
				list.Add(val);
				list2.Add(component);
			}
			if (SyncManager.numReservedItemSlots > 0)
			{
				TextMeshProUGUI component2 = new GameObject("ReservedItemSlotTooltip", new Type[2]
				{
					typeof(RectTransform),
					typeof(TextMeshProUGUI)
				}).GetComponent<TextMeshProUGUI>();
				RectTransform rectTransform = ((TMP_Text)component2).rectTransform;
				((Component)rectTransform).transform.parent = ((Component)list[PlayerPatcher.reservedItemsStartIndex]).transform;
				((Transform)rectTransform).localScale = Vector3.one;
				rectTransform.sizeDelta = new Vector2(((Graphic)list[0]).rectTransform.sizeDelta.x * 2f, 10f);
				rectTransform.pivot = Vector2.one / 2f;
				rectTransform.anchoredPosition3D = new Vector3(0f, (0f - rectTransform.sizeDelta.x / 2f) * 1.2f, 0f);
				((TMP_Text)component2).font = ((TMP_Text)HUDManager.Instance.controlTipLines[0]).font;
				((TMP_Text)component2).fontSize = 7f;
				((TMP_Text)component2).alignment = (TextAlignmentOptions)514;
				if (!ConfigSettings.toggleFocusReservedHotbar.Value)
				{
					((TMP_Text)component2).text = string.Format($"Hold: [{ConfigSettings.GetDisplayName(ConfigSettings.focusReservedHotbarHotkey.Value)}]");
				}
				else
				{
					((TMP_Text)component2).text = string.Format($"Toggle: [{ConfigSettings.GetDisplayName(ConfigSettings.focusReservedHotbarHotkey.Value)}]");
				}
			}
			HUDManager.Instance.itemSlotIconFrames = list.ToArray();
			HUDManager.Instance.itemSlotIcons = list2.ToArray();
			Plugin.Log($"Finished adding {PlayerPatcher.reservedHotbarSize} Reserved Item slots in the inventory HUD.");
		}

		public static void UpdateHUD()
		{
			//IL_001f: 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)
			for (int i = 0; i < PlayerPatcher.reservedHotbarSize; i++)
			{
				int num = PlayerPatcher.reservedItemsStartIndex + i;
				float num2 = ((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.anchoredPosition.y + 1.125f * iconWidth * (float)i;
				((Graphic)HUDManager.Instance.itemSlotIconFrames[num]).rectTransform.anchoredPosition = new Vector2(xPos, num2);
			}
		}
	}
	[HarmonyPatch]
	public static class ReservedItemPatcher
	{
		public static bool isReservedHotbarFocused = false;

		public static int indexUnfocusedReservedHotbar = 0;

		public static int indexFocusedReservedHotbar = 0;

		internal static Dictionary<PlayerControllerB, ReservedItemInfo> grabbingReservedItemInfoDict = new Dictionary<PlayerControllerB, ReservedItemInfo>();

		internal static Dictionary<PlayerControllerB, int> previousInventoryIndexDict = new Dictionary<PlayerControllerB, int>();

		public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController;

		public static int reservedItemsStartIndex => PlayerPatcher.reservedItemsStartIndex;

		public static int reservedHotbarSize => SyncManager.numReservedItemSlots;

		internal static ReservedItemInfo grabbingReservedItemInfoLocal
		{
			get
			{
				return ((Object)(object)localPlayerController != (Object)null) ? grabbingReservedItemInfoDict[localPlayerController] : null;
			}
			set
			{
				if (!((Object)(object)localPlayerController == (Object)null))
				{
					grabbingReservedItemInfoDict[localPlayerController] = value;
				}
			}
		}

		internal static int previousInventoryIndexLocal
		{
			get
			{
				return ((Object)(object)localPlayerController != (Object)null) ? previousInventoryIndexDict[localPlayerController] : (-1);
			}
			set
			{
				if (!((Object)(object)localPlayerController == (Object)null))
				{
					previousInventoryIndexDict[localPlayerController] = value;
				}
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		public static void InitSession(StartOfRound __instance)
		{
			grabbingReservedItemInfoDict.Clear();
			previousInventoryIndexDict.Clear();
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPostfix]
		public static void InitPlayer(PlayerControllerB __instance)
		{
			grabbingReservedItemInfoDict[__instance] = null;
			previousInventoryIndexDict[__instance] = -1;
		}

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

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

		[HarmonyPatch(typeof(PlayerControllerB), "BeginGrabObject")]
		[HarmonyPrefix]
		public static bool GrabReservedItemPrefix(PlayerControllerB __instance)
		{
			//IL_0030: 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_004a: Unknown result type (might be due to invalid IL or missing references)
			if (isReservedHotbarFocused && !ConfigSettings.toggleFocusReservedHotbar.Value)
			{
				return false;
			}
			Ray val = default(Ray);
			((Ray)(ref val))..ctor(((Component)__instance.gameplayCamera).transform.position, ((Component)__instance.gameplayCamera).transform.forward);
			RaycastHit val2 = default(RaycastHit);
			if (Physics.Raycast(val, ref val2, __instance.grabDistance, PlayerPatcher.INTERACTABLE_OBJECT_MASK) && ((Component)((RaycastHit)(ref val2)).collider).gameObject.layer != 8 && ((Component)((RaycastHit)(ref val2)).collider).tag == "PhysicsProp" && !__instance.twoHanded && __instance.sinkingValue >= 0.73f)
			{
				grabbingReservedItemInfoLocal = SyncManager.GetReservedItemInfo(((Component)((Component)((RaycastHit)(ref val2)).collider).transform).gameObject.GetComponent<GrabbableObject>());
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "BeginGrabObject")]
		[HarmonyPostfix]
		public static void GrabReservedItemPostfix(PlayerControllerB __instance)
		{
			if (grabbingReservedItemInfoLocal != null)
			{
				MethodInfo method = ((object)__instance).GetType().GetMethod("SetSpecialGrabAnimationBool", BindingFlags.Instance | BindingFlags.NonPublic);
				method.Invoke(__instance, new object[2] { false, null });
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")]
		[HarmonyPrefix]
		public static void GrabReservedItemClientRpcPrefix(bool grabValidated, NetworkObjectReference grabbedObject, PlayerControllerB __instance)
		{
			if (!NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance))
			{
				return;
			}
			NetworkObject val = default(NetworkObject);
			if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsListening && grabValidated && ((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null))
			{
				GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
				ReservedItemInfo reservedItemInfo = SyncManager.GetReservedItemInfo(component);
				if (reservedItemInfo != null && IsItemSlotEmpty(reservedItemInfo, __instance))
				{
					grabbingReservedItemInfoDict[__instance] = reservedItemInfo;
					previousInventoryIndexDict[__instance] = __instance.currentItemSlot;
					return;
				}
			}
			grabbingReservedItemInfoDict[__instance] = null;
			previousInventoryIndexDict[__instance] = -1;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")]
		[HarmonyPostfix]
		public static void GrabReservedItemClientRpcPostfix(bool grabValidated, NetworkObjectReference grabbedObject, PlayerControllerB __instance)
		{
			if (!NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance) || grabbingReservedItemInfoDict[__instance] == null)
			{
				return;
			}
			if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsListening)
			{
				NetworkObject val = default(NetworkObject);
				if (grabValidated && ((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null))
				{
					GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
					ReservedItemInfo reservedItemInfo = SyncManager.GetReservedItemInfo(component);
					if (reservedItemInfo != null)
					{
						MethodInfo method = ((object)__instance).GetType().GetMethod("SetSpecialGrabAnimationBool", BindingFlags.Instance | BindingFlags.NonPublic);
						method.Invoke(__instance, new object[2] { false, null });
						__instance.currentlyHeldObjectServer = __instance.ItemSlots[__instance.currentItemSlot];
						if ((Object)(object)__instance.currentlyHeldObjectServer != (Object)null)
						{
							__instance.twoHanded = __instance.currentlyHeldObjectServer.itemProperties.twoHanded;
							__instance.twoHandedAnimation = __instance.currentlyHeldObjectServer.itemProperties.twoHandedAnimation;
						}
						Traverse.Create((object)component).Field("previousPlayerHeldBy").SetValue((object)__instance);
						if ((Object)(object)__instance != (Object)(object)localPlayerController)
						{
							Plugin.Log("Grab object completed on player: " + ((Object)__instance).name);
							MethodInfo method2 = ((object)__instance).GetType().GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic);
							method2.Invoke(__instance, new object[2]
							{
								previousInventoryIndexDict[__instance],
								null
							});
							grabbingReservedItemInfoDict[__instance] = null;
							previousInventoryIndexDict[__instance] = -1;
						}
						else
						{
							((Component)HUDManager.Instance.itemSlotIconFrames[grabbingReservedItemInfoLocal.indexInInventory]).GetComponent<Animator>().SetBool("selectedSlot", false);
							((Component)HUDManager.Instance.itemSlotIconFrames[previousInventoryIndexLocal]).GetComponent<Animator>().SetBool("selectedSlot", true);
							((Component)HUDManager.Instance.itemSlotIconFrames[grabbingReservedItemInfoLocal.indexInInventory]).GetComponent<Animator>().Play("PanelLines", 0, 1f);
							((Component)HUDManager.Instance.itemSlotIconFrames[previousInventoryIndexLocal]).GetComponent<Animator>().Play("PanelEnlarge", 0, 1f);
							__instance.currentlyHeldObjectServer.EnableItemMeshes(false);
							MethodInfo method3 = ((object)__instance).GetType().GetMethod("SetSpecialGrabAnimationBool", BindingFlags.Instance | BindingFlags.NonPublic);
							method3.Invoke(__instance, new object[2] { false, null });
						}
						return;
					}
				}
				else if ((Object)(object)__instance == (Object)(object)localPlayerController)
				{
					Plugin.Log("Failed to validate ReservedItemGrab by the local player. Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + ".");
					Traverse.Create((object)localPlayerController).Field("grabInvalidated").SetValue((object)true);
				}
				else
				{
					Plugin.Log("Failed to validate ReservedItemGrab by player with id: " + ((Object)__instance).name + ". Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + ".");
				}
			}
			grabbingReservedItemInfoDict[__instance] = null;
			previousInventoryIndexDict[__instance] = -1;
		}

		[HarmonyPatch(typeof(GrabbableObject), "GrabItemOnClient")]
		[HarmonyPrefix]
		public static void OnReservedItemGrabbed(GrabbableObject __instance)
		{
			if (grabbingReservedItemInfoLocal != null && !((Object)(object)__instance != (Object)(object)GetCurrentlyGrabbingObject(localPlayerController)))
			{
				OnLocalPlayerGrabbedReservedItem();
				__instance.PocketItem();
			}
		}

		private static void OnLocalPlayerGrabbedReservedItem()
		{
			MethodInfo method = ((object)localPlayerController).GetType().GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic);
			method.Invoke(localPlayerController, new object[2] { previousInventoryIndexLocal, null });
			grabbingReservedItemInfoLocal = null;
			previousInventoryIndexLocal = -1;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "FirstEmptyItemSlot")]
		[HarmonyPostfix]
		public static void GetReservedItemSlotPlacementIndex(ref int __result, PlayerControllerB __instance)
		{
			ReservedItemInfo reservedItemInfo = grabbingReservedItemInfoDict[__instance];
			if (reservedItemInfo != null)
			{
				if (IsItemSlotEmpty(reservedItemInfo))
				{
					__result = reservedItemInfo.indexInInventory;
					return;
				}
				grabbingReservedItemInfoDict[__instance] = null;
			}
			if (__result < reservedItemsStartIndex || __result >= reservedItemsStartIndex + reservedHotbarSize)
			{
				return;
			}
			__result = -1;
			for (int i = 0; i < __instance.ItemSlots.Length; i++)
			{
				if ((i < reservedItemsStartIndex || i >= reservedItemsStartIndex + reservedHotbarSize) && (Object)(object)__instance.ItemSlots[i] == (Object)null)
				{
					__result = i;
					break;
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "NextItemSlot")]
		[HarmonyPostfix]
		public static void PreventScrollingOtherHotbar(ref int __result, bool forward, PlayerControllerB __instance)
		{
			if (reservedHotbarSize <= 0)
			{
				return;
			}
			bool flag = __result >= reservedItemsStartIndex && __result < reservedItemsStartIndex + reservedHotbarSize;
			bool flag2 = __instance.currentItemSlot >= reservedItemsStartIndex && __instance.currentItemSlot < reservedItemsStartIndex + reservedHotbarSize;
			if ((Object)(object)__instance != (Object)(object)localPlayerController && ((!flag && !flag2) || (flag && flag2 && (Object)(object)__instance.ItemSlots[__result] != (Object)null)))
			{
				return;
			}
			int num = (forward ? 1 : (-1));
			__result = __instance.currentItemSlot + num;
			if (!flag2)
			{
				if (__result < 0)
				{
					__result = __instance.ItemSlots.Length - 1;
					if (__result >= reservedItemsStartIndex && __result < reservedItemsStartIndex + reservedHotbarSize)
					{
						__result = reservedItemsStartIndex - 1;
					}
				}
				else if (__result >= reservedItemsStartIndex && __result < reservedItemsStartIndex + reservedHotbarSize)
				{
					__result = (forward ? (reservedItemsStartIndex + reservedHotbarSize) : (reservedItemsStartIndex - 1));
				}
				if (__result >= __instance.ItemSlots.Length)
				{
					__result = 0;
				}
				return;
			}
			if (__result < reservedItemsStartIndex)
			{
				__result = reservedItemsStartIndex + reservedHotbarSize - 1;
			}
			else if (__result >= reservedItemsStartIndex + reservedHotbarSize)
			{
				__result = reservedItemsStartIndex;
			}
			int num2 = __result;
			while (__result != __instance.currentItemSlot && (Object)(object)__instance.ItemSlots[__result] == (Object)null)
			{
				__result += num;
				if (__result < reservedItemsStartIndex)
				{
					__result = reservedItemsStartIndex + reservedHotbarSize - 1;
				}
				else if (__result >= reservedItemsStartIndex + reservedHotbarSize)
				{
					__result = reservedItemsStartIndex;
				}
			}
			if (__result == __instance.currentItemSlot && (Object)(object)__instance.ItemSlots[__instance.currentItemSlot] == (Object)null)
			{
				__result = num2;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ScrollMouse_performed")]
		[HarmonyPrefix]
		public static bool FixScrollingDirectionReservedHotbar(CallbackContext context, PlayerControllerB __instance)
		{
			if ((Object)(object)__instance != (Object)(object)localPlayerController || grabbingReservedItemInfoLocal != null || reservedHotbarSize <= 0 || !isReservedHotbarFocused || __instance.inTerminalMenu || !CanSwapToReservedHotbarSlot())
			{
				return true;
			}
			int num = 0;
			for (int i = reservedItemsStartIndex; i < reservedItemsStartIndex + reservedHotbarSize; i++)
			{
				num += (((Object)(object)localPlayerController.ItemSlots[i] != (Object)null) ? 1 : 0);
			}
			if (num == 1 && localPlayerController.currentItemSlot >= reservedItemsStartIndex && localPlayerController.currentItemSlot < reservedItemsStartIndex + reservedHotbarSize && (Object)(object)localPlayerController.ItemSlots[localPlayerController.currentItemSlot] != (Object)null)
			{
				return false;
			}
			return true;
		}

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

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

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

		public static void FocusReservedHotbarSlots(bool active)
		{
			if (reservedHotbarSize <= 0 || isReservedHotbarFocused == active)
			{
				return;
			}
			isReservedHotbarFocused = active;
			int num = localPlayerController.currentItemSlot;
			if (isReservedHotbarFocused && (num < reservedItemsStartIndex || num >= reservedItemsStartIndex + reservedHotbarSize))
			{
				if (indexFocusedReservedHotbar == -1)
				{
					indexFocusedReservedHotbar = reservedItemsStartIndex;
				}
				indexUnfocusedReservedHotbar = num;
				num = Mathf.Clamp(indexFocusedReservedHotbar, reservedItemsStartIndex, reservedItemsStartIndex + reservedHotbarSize - 1);
				if ((Object)(object)localPlayerController.ItemSlots[num] == (Object)null)
				{
					for (int i = 0; i < reservedHotbarSize; i++)
					{
						int num2 = reservedItemsStartIndex + i;
						if ((Object)(object)localPlayerController.ItemSlots[num2] != (Object)null)
						{
							num = num2;
							break;
						}
					}
				}
			}
			else if (!isReservedHotbarFocused && num >= reservedItemsStartIndex && num < reservedItemsStartIndex + reservedHotbarSize)
			{
				indexFocusedReservedHotbar = num;
				if (indexUnfocusedReservedHotbar >= reservedItemsStartIndex && indexUnfocusedReservedHotbar < reservedItemsStartIndex + reservedHotbarSize)
				{
					indexUnfocusedReservedHotbar = 0;
				}
				num = indexUnfocusedReservedHotbar;
			}
			SyncManager.SwapHotbarSlot(num);
		}

		public static bool IsItemSlotEmpty(string itemName, PlayerControllerB playerController)
		{
			return IsItemSlotEmpty(SyncManager.GetReservedItemInfo(itemName), playerController);
		}

		internal static bool IsItemSlotEmpty(ReservedItemInfo itemInfo, PlayerControllerB player = null)
		{
			if ((Object)(object)player == (Object)null)
			{
				player = localPlayerController;
			}
			if ((Object)(object)player == (Object)null)
			{
				return false;
			}
			return itemInfo != null && itemInfo.indexInInventory < player.ItemSlots.Length && (Object)(object)player.ItemSlots[itemInfo.indexInInventory] == (Object)null;
		}

		public static GrabbableObject GetHeldReservedObject(string itemName, PlayerControllerB player = null)
		{
			if ((Object)(object)player == (Object)null)
			{
				player = localPlayerController;
			}
			if ((Object)(object)player == (Object)null)
			{
				return null;
			}
			int reservedItemHotbarIndex = SyncManager.GetReservedItemHotbarIndex(itemName);
			return (reservedItemHotbarIndex >= 0 && reservedItemHotbarIndex < player.ItemSlots.Length && (Object)(object)player.ItemSlots[reservedItemHotbarIndex] != (Object)null) ? player.ItemSlots[reservedItemHotbarIndex] : null;
		}

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

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

		[HarmonyPatch(typeof(GrabbableObject), "Start")]
		[HarmonyPostfix]
		public static void InitializeReservedItemProperties(GrabbableObject __instance)
		{
			ReservedItemInfo reservedItemInfo = SyncManager.GetReservedItemInfo(__instance.itemProperties.itemName);
			if (reservedItemInfo != null)
			{
				if (reservedItemInfo.forceUpdateCanBeGrabbedBeforeGameStart)
				{
					__instance.itemProperties.canBeGrabbedBeforeGameStart = reservedItemInfo.canBeGrabbedBeforeGameStart;
				}
				if (reservedItemInfo.forceUpdateRequiresBattery)
				{
					__instance.itemProperties.requiresBattery = reservedItemInfo.requiresBattery;
				}
			}
		}
	}
	[HarmonyPatch]
	public static class PlayerPatcher
	{
		public static PlayerControllerB localPlayerController;

		public static int vanillaHotbarSize = -1;

		public static int reservedItemsStartIndex = 4;

		public static int oldHotbarSize = -1;

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

		private static bool isSynced = false;

		public static int INTERACTABLE_OBJECT_MASK { get; private set; }

		public static int reservedHotbarSize => SyncManager.numReservedItemSlots;

		public static int combinedHotbarSize => reservedItemsStartIndex + reservedHotbarSize;

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		public static void ResetVariables(StartOfRound __instance)
		{
			localPlayerController = null;
			vanillaHotbarSize = -1;
			ReservedItemPatcher.isReservedHotbarFocused = false;
			ReservedItemPatcher.indexUnfocusedReservedHotbar = 0;
			ReservedItemPatcher.indexFocusedReservedHotbar = -1;
			Keybinds.localPlayerController = null;
			Keybinds.focusReservedHotbarAction = null;
			Keybinds.holdingModifierKey = false;
			SyncManager.localPlayerController = null;
			playerData.Clear();
			isSynced = false;
		}

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

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPostfix]
		public static void InitializePlayerControllerLate(PlayerControllerB __instance)
		{
			playerData.Add(__instance, new ReservedPlayerData());
		}

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

		private static IEnumerator UpdateHotbarSlotsAfterSpawnAnimation()
		{
			yield return (object)new WaitForSeconds(3f);
			if (SyncManager.isSynced && !isSynced)
			{
				OnSyncedWithServer();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		public static void CheckForIncreasedInventorySize(PlayerControllerB __instance)
		{
			if ((Object)(object)__instance != (Object)(object)localPlayerController)
			{
				return;
			}
			if (SyncManager.isSynced && !isSynced)
			{
				OnSyncedWithServer();
			}
			if (reservedHotbarSize == 0 || oldHotbarSize == __instance.ItemSlots.Length)
			{
				return;
			}
			for (int i = 0; i < HUDManager.Instance.itemSlotIconFrames.Length; i++)
			{
				if (((Object)HUDManager.Instance.itemSlotIconFrames[i]).name.ToLower().StartsWith("reserveditemslot"))
				{
					reservedItemsStartIndex = i;
					oldHotbarSize = __instance.ItemSlots.Length;
					HUDPatcher.UpdateHUD();
					break;
				}
			}
		}

		private static void OnSyncedWithServer()
		{
			isSynced = true;
			reservedItemsStartIndex = localPlayerController.ItemSlots.Length;
			Plugin.Log("ReservedItemsStartIndex: " + reservedItemsStartIndex);
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				val.ItemSlots = (GrabbableObject[])(object)new GrabbableObject[val.ItemSlots.Length + reservedHotbarSize];
			}
			oldHotbarSize = localPlayerController.ItemSlots.Length;
			HUDPatcher.AddNewHotbarSlotsHud();
			List<Item> itemsList = StartOfRound.Instance.allItemsList.itemsList;
			foreach (Item item in itemsList)
			{
				ReservedItemInfo reservedItemInfo = SyncManager.GetReservedItemInfo(item.itemName);
				if (reservedItemInfo != null)
				{
					if (reservedItemInfo.forceUpdateCanBeGrabbedBeforeGameStart)
					{
						item.canBeGrabbedBeforeGameStart = reservedItemInfo.canBeGrabbedBeforeGameStart;
					}
					if (reservedItemInfo.forceUpdateRequiresBattery)
					{
						item.requiresBattery = reservedItemInfo.requiresBattery;
					}
				}
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/FlipMods-ReservedWalkieSlot/ReservedWalkieSlot.dll

Decompiled 9 months ago
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using ReservedItemSlotCore;
using ReservedItemSlotCore.Patches;
using ReservedWalkieSlot.Patches;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ReservedWalkieSlot")]
[assembly: AssemblyDescription("Mod made by flipf17")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReservedWalkieSlot")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("c15c320f-d8fc-4f1c-be3c-f2d2ffc41edd")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ReservedWalkieSlot
{
	public static class ConfigSettings
	{
		public static ConfigEntry<string> activateWalkieKey;

		public static ConfigEntry<bool> hideWalkieMeshShoulder;

		public static string activateWalkieDisplayName;

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

		public static void BindConfigSettings()
		{
			Plugin.Log("BindingConfigs");
			activateWalkieKey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedWalkieSlot", "ActivateWalkieKey", "<Keyboard>/x", "Activate walkie keybind.");
			hideWalkieMeshShoulder = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedWalkieSlot", "HideWalkieOnShoulder", false, "Hides the walkie mesh while on your shoulder. Only applies in scenarios where you can view your player in third person.");
			activateWalkieDisplayName = GetDisplayName(activateWalkieKey.Value);
			currentConfigEntries.Add(((ConfigEntryBase)activateWalkieKey).Definition.Key, (ConfigEntryBase)(object)activateWalkieKey);
			currentConfigEntries.Add(((ConfigEntryBase)hideWalkieMeshShoulder).Definition.Key, (ConfigEntryBase)(object)hideWalkieMeshShoulder);
			TryRemoveOldConfigSettings();
		}

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

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

		private static InputAction activateWalkieAction;

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		[HarmonyPostfix]
		public static void OnLocalPlayerConnect(PlayerControllerB __instance)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			localPlayerController = __instance;
			activateWalkieAction = new InputAction((string)null, (InputActionType)0, ConfigSettings.activateWalkieKey.Value, (string)null, (string)null, (string)null);
			if (((Component)localPlayerController).gameObject.activeSelf)
			{
				SubscribeToEvents();
			}
		}

		private static void SubscribeToEvents()
		{
			if (activateWalkieAction != null)
			{
				activateWalkieAction.performed += OnPressWalkieButtonPerformed;
				activateWalkieAction.canceled += OnReleaseWalkieButtonPerformed;
				activateWalkieAction.Enable();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "OnEnable")]
		[HarmonyPostfix]
		public static void OnEnable(PlayerControllerB __instance)
		{
			if ((Object)(object)__instance == (Object)(object)localPlayerController)
			{
				SubscribeToEvents();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "OnDisable")]
		[HarmonyPostfix]
		public static void OnDisable(PlayerControllerB __instance)
		{
			if (activateWalkieAction != null && !((Object)(object)__instance != (Object)(object)localPlayerController))
			{
				activateWalkieAction.performed -= OnPressWalkieButtonPerformed;
				activateWalkieAction.canceled -= OnReleaseWalkieButtonPerformed;
				activateWalkieAction.Disable();
			}
		}

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

		private static void OnReleaseWalkieButtonPerformed(CallbackContext context)
		{
			if (!((Object)(object)localPlayerController == (Object)null) && localPlayerController.isPlayerControlled && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject))
			{
				WalkieTalkie mainWalkie = ReservedWalkieSlotPatcher.GetMainWalkie(localPlayerController);
				if (((CallbackContext)(ref context)).canceled && !((Object)(object)mainWalkie == (Object)null))
				{
					Plugin.Log("Not talking into walkie");
					ShipBuildModeManager.Instance.CancelBuildMode(true);
					((GrabbableObject)mainWalkie).UseItemOnClient(false);
				}
			}
		}
	}
	[BepInPlugin("FlipMods.ReservedWalkieSlot", "ReservedWalkieSlot", "1.5.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	internal class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		private Harmony _harmony;

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

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

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

		public const string PLUGIN_NAME = "ReservedWalkieSlot";

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

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

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

		private static string originalControlTooltip = "";

		public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController;

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

		public static WalkieTalkie GetReservedWalkie(PlayerControllerB playerController)
		{
			GrabbableObject obj = ((playerController != null) ? playerController.ItemSlots[Plugin.walkieInfo.indexInInventory] : null);
			return (WalkieTalkie)(object)((obj is WalkieTalkie) ? obj : null);
		}

		public static WalkieTalkie GetCurrentlySelectedWalkie(PlayerControllerB playerController)
		{
			GrabbableObject obj = ((playerController != null) ? playerController.ItemSlots[playerController.currentItemSlot] : null);
			return (WalkieTalkie)(object)((obj is WalkieTalkie) ? obj : null);
		}

		[HarmonyPatch(typeof(WalkieTalkie), "__initializeVariables")]
		[HarmonyPostfix]
		public static void EditTooltips(WalkieTalkie __instance)
		{
			if (originalControlTooltip == "")
			{
				originalControlTooltip = ((GrabbableObject)__instance).itemProperties.toolTips[((GrabbableObject)__instance).itemProperties.toolTips.Length - 1];
			}
			((GrabbableObject)__instance).itemProperties.toolTips[((GrabbableObject)__instance).itemProperties.toolTips.Length - 1] = $"{originalControlTooltip}[{ConfigSettings.activateWalkieDisplayName.ToUpper()}]";
		}

		[HarmonyPatch(typeof(MenuManager), "OnEnable")]
		[HarmonyPostfix]
		public static void ResetVariables()
		{
			Keybinds.localPlayerController = null;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_performed")]
		[HarmonyPrefix]
		public static bool PreventActivatingDuplicateItem(CallbackContext context, PlayerControllerB __instance)
		{
			WalkieTalkie currentlySelectedWalkie = GetCurrentlySelectedWalkie(__instance);
			if ((Object)(object)__instance != (Object)(object)localPlayerController || (Object)(object)currentlySelectedWalkie == (Object)null)
			{
				return true;
			}
			if (!((CallbackContext)(ref context)).performed)
			{
				return false;
			}
			return true;
		}

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

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

		[HarmonyPatch(typeof(WalkieTalkie), "DiscardItem")]
		[HarmonyPostfix]
		public static void OnDiscardWalkie(WalkieTalkie __instance)
		{
			((Component)((Component)__instance).GetComponentInChildren<Renderer>()).gameObject.layer = 6;
		}

		[HarmonyPatch(typeof(GrabbableObject), "LateUpdate")]
		[HarmonyPostfix]
		public static void SetPositionOffset(GrabbableObject __instance)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			if (__instance is WalkieTalkie && (Object)(object)__instance.playerHeldBy != (Object)null && (Object)(object)__instance.parentObject != (Object)null && __instance.isPocketed && (Object)(object)__instance == (Object)(object)GetReservedWalkie(__instance.playerHeldBy) && (Object)(object)__instance != (Object)(object)GetCurrentlySelectedWalkie(__instance.playerHeldBy))
			{
				Transform transform = ((Component)__instance.parentObject).transform;
				((Component)__instance).transform.rotation = ((Component)__instance.parentObject).transform.rotation * Quaternion.Euler(playerShoulderRotationOffset);
				((Component)__instance).transform.position = transform.position + transform.rotation * playerShoulderPositionOffset;
			}
		}

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

BooBoo Building/BepInEx/plugins/FutureSavior-Boombox_Sync_Fix/BoomboxSyncFix.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BoomboxSyncFix")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("A mod to fix the base game bug of the Boombox not being synced between users.")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+71645702ebc3ea437c29afaa8432d4398a219be3")]
[assembly: AssemblyProduct("BoomboxSyncFix")]
[assembly: AssemblyTitle("BoomboxSyncFix")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.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 BoomboxSyncFix
{
	[BepInPlugin("BoomboxSyncFix", "BoomboxSyncFix", "1.1.0")]
	public class BoomboxSyncFixPlugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("BoomboxSyncFix");

		public static BoomboxSyncFixPlugin Instance;

		internal ManualLogSource logger;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			logger = Logger.CreateLogSource("BoomboxSyncFix");
			logger.LogInfo((object)"Plugin BoomboxSyncFix has loaded!");
			harmony.PatchAll(typeof(BoomboxSyncFixPlugin));
			harmony.PatchAll(typeof(BoomboxItemStartMusicPatch));
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "BoomboxSyncFix";

		public const string PLUGIN_NAME = "BoomboxSyncFix";

		public const string PLUGIN_VERSION = "1.1.0";
	}
}
namespace BoomboxSyncFix.Patches
{
	[HarmonyPatch]
	internal class BoomboxItemStartMusicPatch
	{
		private static Dictionary<BoomboxItem, bool> seedSyncDictionary = new Dictionary<BoomboxItem, bool>();

		private static FieldInfo playersManagerField = AccessTools.Field(typeof(BoomboxItem), "playersManager");

		[HarmonyPatch(typeof(BoomboxItem), "StartMusic")]
		[HarmonyPrefix]
		public static void StartMusicPatch(BoomboxItem __instance)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			StartOfRound val = (StartOfRound)playersManagerField.GetValue(__instance);
			if ((!seedSyncDictionary.TryGetValue(__instance, out var value) || !value) && (Object)(object)val != (Object)null && val.randomMapSeed > 0)
			{
				int num = val.randomMapSeed - 10;
				__instance.musicRandomizer = new Random(num);
				BoomboxSyncFixPlugin.Instance.logger.LogInfo((object)$"Musicrandomizer variable has been synced with seed: {num}");
				seedSyncDictionary[__instance] = true;
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "OnPlayerConnectedClientRpc")]
		[HarmonyPrefix]
		public static void OnPlayerConnectedPatch(StartOfRound __instance)
		{
			BoomboxSyncFixPlugin.Instance.logger.LogInfo((object)"Another client joined -- forcing everyone to reintialize musicRandomizer.");
			forceReinitialize(seedSyncDictionary);
		}

		[HarmonyPatch(typeof(StartOfRound), "openingDoorsSequence")]
		[HarmonyPrefix]
		public static void openingDoorsSequencePatch(StartOfRound __instance)
		{
			BoomboxSyncFixPlugin.Instance.logger.LogInfo((object)"Round has loaded for all -- forcing everyone to reinitialize musicRandomizer.");
			forceReinitialize(seedSyncDictionary);
		}

		private static void forceReinitialize(Dictionary<BoomboxItem, bool> seedSyncDictionary)
		{
			foreach (BoomboxItem item in seedSyncDictionary.Keys.ToList())
			{
				seedSyncDictionary[item] = false;
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/FutureSavior-Hold_Scan_Button/HoldScanButton.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using HoldScanButton.Patches;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("HoldScanButton")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("A mod which allows you to hold the scan button instead of needing to spam it.")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1+92607af20e0f471d869a59ef64bf096440b07cf2")]
[assembly: AssemblyProduct("HoldScanButton")]
[assembly: AssemblyTitle("HoldScanButton")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace HoldScanButton
{
	[BepInPlugin("HoldScanButton", "HoldScanButton", "1.1.1")]
	public class HoldScanButtonPlugin : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("HoldScanButton");

		public static HoldScanButtonPlugin Instance;

		internal ManualLogSource logger;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			logger = Logger.CreateLogSource("HoldScanButton");
			logger.LogInfo((object)"Plugin HoldScanButton has loaded!");
			harmony.PatchAll(typeof(HoldScanButtonPatch));
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "HoldScanButton";

		public const string PLUGIN_NAME = "HoldScanButton";

		public const string PLUGIN_VERSION = "1.1.1";
	}
}
namespace HoldScanButton.Patches
{
	internal class HoldScanButtonPatch
	{
		private static CallbackContext pingContext;

		[HarmonyPatch(typeof(HUDManager), "Update")]
		[HarmonyPostfix]
		private static void UpdatePatch(HUDManager __instance)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (IngamePlayerSettings.Instance.playerInput.actions.FindAction("PingScan", false).IsPressed())
			{
				__instance.PingScan_performed(pingContext);
			}
		}

		[HarmonyPatch(typeof(HUDManager), "PingScan_performed")]
		[HarmonyPrefix]
		private static void OnScan(HUDManager __instance, CallbackContext context)
		{
			//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)
			pingContext = context;
		}
	}
}

BooBoo Building/BepInEx/plugins/Giltong-LethalCompanyDRP/LethalCompanyDRP.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Discord;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LethalCompanyDRP")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Discord Rich Presence for Lethal Company")]
[assembly: AssemblyFileVersion("1.3.5.0")]
[assembly: AssemblyInformationalVersion("1.3.5")]
[assembly: AssemblyProduct("LethalCompanyDRP")]
[assembly: AssemblyTitle("LethalCompanyDRP")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.3.5.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 Discord
{
	public class ActivityManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ActivityJoinHandler(IntPtr ptr, [MarshalAs(UnmanagedType.LPStr)] string secret);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ActivitySpectateHandler(IntPtr ptr, [MarshalAs(UnmanagedType.LPStr)] string secret);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ActivityJoinRequestHandler(IntPtr ptr, ref User user);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ActivityInviteHandler(IntPtr ptr, ActivityActionType type, ref User user, ref Activity activity);

			internal ActivityJoinHandler OnActivityJoin;

			internal ActivitySpectateHandler OnActivitySpectate;

			internal ActivityJoinRequestHandler OnActivityJoinRequest;

			internal ActivityInviteHandler OnActivityInvite;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result RegisterCommandMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string command);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result RegisterSteamMethod(IntPtr methodsPtr, uint steamId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void UpdateActivityCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void UpdateActivityMethod(IntPtr methodsPtr, ref Activity activity, IntPtr callbackData, UpdateActivityCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ClearActivityCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ClearActivityMethod(IntPtr methodsPtr, IntPtr callbackData, ClearActivityCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SendRequestReplyCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SendRequestReplyMethod(IntPtr methodsPtr, long userId, ActivityJoinRequestReply reply, IntPtr callbackData, SendRequestReplyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SendInviteCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SendInviteMethod(IntPtr methodsPtr, long userId, ActivityActionType type, [MarshalAs(UnmanagedType.LPStr)] string content, IntPtr callbackData, SendInviteCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void AcceptInviteCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void AcceptInviteMethod(IntPtr methodsPtr, long userId, IntPtr callbackData, AcceptInviteCallback callback);

			internal RegisterCommandMethod RegisterCommand;

			internal RegisterSteamMethod RegisterSteam;

			internal UpdateActivityMethod UpdateActivity;

			internal ClearActivityMethod ClearActivity;

			internal SendRequestReplyMethod SendRequestReply;

			internal SendInviteMethod SendInvite;

			internal AcceptInviteMethod AcceptInvite;
		}

		public delegate void UpdateActivityHandler(Result result);

		public delegate void ClearActivityHandler(Result result);

		public delegate void SendRequestReplyHandler(Result result);

		public delegate void SendInviteHandler(Result result);

		public delegate void AcceptInviteHandler(Result result);

		public delegate void ActivityJoinHandler(string secret);

		public delegate void ActivitySpectateHandler(string secret);

		public delegate void ActivityJoinRequestHandler(ref User user);

		public delegate void ActivityInviteHandler(ActivityActionType type, ref User user, ref Activity activity);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event ActivityJoinHandler OnActivityJoin;

		public event ActivitySpectateHandler OnActivitySpectate;

		public event ActivityJoinRequestHandler OnActivityJoinRequest;

		public event ActivityInviteHandler OnActivityInvite;

		public void RegisterCommand()
		{
			RegisterCommand(null);
		}

		internal ActivityManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnActivityJoin = OnActivityJoinImpl;
			events.OnActivitySpectate = OnActivitySpectateImpl;
			events.OnActivityJoinRequest = OnActivityJoinRequestImpl;
			events.OnActivityInvite = OnActivityInviteImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public void RegisterCommand(string command)
		{
			Result result = Methods.RegisterCommand(MethodsPtr, command);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void RegisterSteam(uint steamId)
		{
			Result result = Methods.RegisterSteam(MethodsPtr, steamId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		[MonoPInvokeCallback]
		private static void UpdateActivityCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			UpdateActivityHandler updateActivityHandler = (UpdateActivityHandler)gCHandle.Target;
			gCHandle.Free();
			updateActivityHandler(result);
		}

		public void UpdateActivity(Activity activity, UpdateActivityHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.UpdateActivity(MethodsPtr, ref activity, GCHandle.ToIntPtr(value), UpdateActivityCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void ClearActivityCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			ClearActivityHandler clearActivityHandler = (ClearActivityHandler)gCHandle.Target;
			gCHandle.Free();
			clearActivityHandler(result);
		}

		public void ClearActivity(ClearActivityHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.ClearActivity(MethodsPtr, GCHandle.ToIntPtr(value), ClearActivityCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void SendRequestReplyCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SendRequestReplyHandler sendRequestReplyHandler = (SendRequestReplyHandler)gCHandle.Target;
			gCHandle.Free();
			sendRequestReplyHandler(result);
		}

		public void SendRequestReply(long userId, ActivityJoinRequestReply reply, SendRequestReplyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.SendRequestReply(MethodsPtr, userId, reply, GCHandle.ToIntPtr(value), SendRequestReplyCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void SendInviteCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SendInviteHandler sendInviteHandler = (SendInviteHandler)gCHandle.Target;
			gCHandle.Free();
			sendInviteHandler(result);
		}

		public void SendInvite(long userId, ActivityActionType type, string content, SendInviteHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.SendInvite(MethodsPtr, userId, type, content, GCHandle.ToIntPtr(value), SendInviteCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void AcceptInviteCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			AcceptInviteHandler acceptInviteHandler = (AcceptInviteHandler)gCHandle.Target;
			gCHandle.Free();
			acceptInviteHandler(result);
		}

		public void AcceptInvite(long userId, AcceptInviteHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.AcceptInvite(MethodsPtr, userId, GCHandle.ToIntPtr(value), AcceptInviteCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void OnActivityJoinImpl(IntPtr ptr, string secret)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.ActivityManagerInstance.OnActivityJoin != null)
			{
				discord.ActivityManagerInstance.OnActivityJoin(secret);
			}
		}

		[MonoPInvokeCallback]
		private static void OnActivitySpectateImpl(IntPtr ptr, string secret)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.ActivityManagerInstance.OnActivitySpectate != null)
			{
				discord.ActivityManagerInstance.OnActivitySpectate(secret);
			}
		}

		[MonoPInvokeCallback]
		private static void OnActivityJoinRequestImpl(IntPtr ptr, ref User user)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.ActivityManagerInstance.OnActivityJoinRequest != null)
			{
				discord.ActivityManagerInstance.OnActivityJoinRequest(ref user);
			}
		}

		[MonoPInvokeCallback]
		private static void OnActivityInviteImpl(IntPtr ptr, ActivityActionType type, ref User user, ref Activity activity)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.ActivityManagerInstance.OnActivityInvite != null)
			{
				discord.ActivityManagerInstance.OnActivityInvite(type, ref user, ref activity);
			}
		}
	}
	internal static class Constants
	{
		public const string DllName = "discord_game_sdk";
	}
	public enum Result
	{
		Ok,
		ServiceUnavailable,
		InvalidVersion,
		LockFailed,
		InternalError,
		InvalidPayload,
		InvalidCommand,
		InvalidPermissions,
		NotFetched,
		NotFound,
		Conflict,
		InvalidSecret,
		InvalidJoinSecret,
		NoEligibleActivity,
		InvalidInvite,
		NotAuthenticated,
		InvalidAccessToken,
		ApplicationMismatch,
		InvalidDataUrl,
		InvalidBase64,
		NotFiltered,
		LobbyFull,
		InvalidLobbySecret,
		InvalidFilename,
		InvalidFileSize,
		InvalidEntitlement,
		NotInstalled,
		NotRunning,
		InsufficientBuffer,
		PurchaseCanceled,
		InvalidGuild,
		InvalidEvent,
		InvalidChannel,
		InvalidOrigin,
		RateLimited,
		OAuth2Error,
		SelectChannelTimeout,
		GetGuildTimeout,
		SelectVoiceForceRequired,
		CaptureShortcutAlreadyListening,
		UnauthorizedForAchievement,
		InvalidGiftCode,
		PurchaseError,
		TransactionAborted,
		DrawingInitFailed
	}
	public enum CreateFlags
	{
		Default,
		NoRequireDiscord
	}
	public enum LogLevel
	{
		Error = 1,
		Warn,
		Info,
		Debug
	}
	public enum UserFlag
	{
		Partner = 2,
		HypeSquadEvents = 4,
		HypeSquadHouse1 = 0x40,
		HypeSquadHouse2 = 0x80,
		HypeSquadHouse3 = 0x100
	}
	public enum PremiumType
	{
		None,
		Tier1,
		Tier2
	}
	public enum ImageType
	{
		User
	}
	public enum ActivityPartyPrivacy
	{
		Private,
		Public
	}
	public enum ActivityType
	{
		Playing,
		Streaming,
		Listening,
		Watching
	}
	public enum ActivityActionType
	{
		Join = 1,
		Spectate
	}
	public enum ActivitySupportedPlatformFlags
	{
		Desktop = 1,
		Android = 2,
		iOS = 4
	}
	public enum ActivityJoinRequestReply
	{
		No,
		Yes,
		Ignore
	}
	public enum Status
	{
		Offline,
		Online,
		Idle,
		DoNotDisturb
	}
	public enum RelationshipType
	{
		None,
		Friend,
		Blocked,
		PendingIncoming,
		PendingOutgoing,
		Implicit
	}
	public enum LobbyType
	{
		Private = 1,
		Public
	}
	public enum LobbySearchComparison
	{
		LessThanOrEqual = -2,
		LessThan,
		Equal,
		GreaterThan,
		GreaterThanOrEqual,
		NotEqual
	}
	public enum LobbySearchCast
	{
		String = 1,
		Number
	}
	public enum LobbySearchDistance
	{
		Local,
		Default,
		Extended,
		Global
	}
	public enum KeyVariant
	{
		Normal,
		Right,
		Left
	}
	public enum MouseButton
	{
		Left,
		Middle,
		Right
	}
	public enum EntitlementType
	{
		Purchase = 1,
		PremiumSubscription,
		DeveloperGift,
		TestModePurchase,
		FreePurchase,
		UserGift,
		PremiumPurchase
	}
	public enum SkuType
	{
		Application = 1,
		DLC,
		Consumable,
		Bundle
	}
	public enum InputModeType
	{
		VoiceActivity,
		PushToTalk
	}
	public struct User
	{
		public long Id;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
		public string Username;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
		public string Discriminator;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Avatar;

		public bool Bot;
	}
	public struct OAuth2Token
	{
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string AccessToken;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
		public string Scopes;

		public long Expires;
	}
	public struct ImageHandle
	{
		public ImageType Type;

		public long Id;

		public uint Size;

		public static ImageHandle User(long id)
		{
			return User(id, 128u);
		}

		public static ImageHandle User(long id, uint size)
		{
			ImageHandle result = default(ImageHandle);
			result.Type = ImageType.User;
			result.Id = id;
			result.Size = size;
			return result;
		}
	}
	public struct ImageDimensions
	{
		public uint Width;

		public uint Height;
	}
	public struct ActivityTimestamps
	{
		public long Start;

		public long End;
	}
	public struct ActivityAssets
	{
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string LargeImage;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string LargeText;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string SmallImage;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string SmallText;
	}
	public struct PartySize
	{
		public int CurrentSize;

		public int MaxSize;
	}
	public struct ActivityParty
	{
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Id;

		public PartySize Size;

		public ActivityPartyPrivacy Privacy;
	}
	public struct ActivitySecrets
	{
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Match;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Join;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Spectate;
	}
	public struct Activity
	{
		public ActivityType Type;

		public long ApplicationId;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Name;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string State;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Details;

		public ActivityTimestamps Timestamps;

		public ActivityAssets Assets;

		public ActivityParty Party;

		public ActivitySecrets Secrets;

		public bool Instance;

		public uint SupportedPlatforms;
	}
	public struct Presence
	{
		public Status Status;

		public Activity Activity;
	}
	public struct Relationship
	{
		public RelationshipType Type;

		public User User;

		public Presence Presence;
	}
	public struct Lobby
	{
		public long Id;

		public LobbyType Type;

		public long OwnerId;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Secret;

		public uint Capacity;

		public bool Locked;
	}
	public struct ImeUnderline
	{
		public int From;

		public int To;

		public uint Color;

		public uint BackgroundColor;

		public bool Thick;
	}
	public struct Rect
	{
		public int Left;

		public int Top;

		public int Right;

		public int Bottom;
	}
	public struct FileStat
	{
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
		public string Filename;

		public ulong Size;

		public ulong LastModified;
	}
	public struct Entitlement
	{
		public long Id;

		public EntitlementType Type;

		public long SkuId;
	}
	public struct SkuPrice
	{
		public uint Amount;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
		public string Currency;
	}
	public struct Sku
	{
		public long Id;

		public SkuType Type;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
		public string Name;

		public SkuPrice Price;
	}
	public struct InputMode
	{
		public InputModeType Type;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
		public string Shortcut;
	}
	public struct UserAchievement
	{
		public long UserId;

		public long AchievementId;

		public byte PercentComplete;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
		public string UnlockedAt;
	}
	public struct LobbyTransaction
	{
		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result SetTypeMethod(IntPtr methodsPtr, LobbyType type);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result SetOwnerMethod(IntPtr methodsPtr, long ownerId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result SetCapacityMethod(IntPtr methodsPtr, uint capacity);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result SetMetadataMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key, [MarshalAs(UnmanagedType.LPStr)] string value);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result DeleteMetadataMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result SetLockedMethod(IntPtr methodsPtr, bool locked);

			internal SetTypeMethod SetType;

			internal SetOwnerMethod SetOwner;

			internal SetCapacityMethod SetCapacity;

			internal SetMetadataMethod SetMetadata;

			internal DeleteMetadataMethod DeleteMetadata;

			internal SetLockedMethod SetLocked;
		}

		internal IntPtr MethodsPtr;

		internal object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public void SetType(LobbyType type)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetType(MethodsPtr, type);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void SetOwner(long ownerId)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetOwner(MethodsPtr, ownerId);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void SetCapacity(uint capacity)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetCapacity(MethodsPtr, capacity);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void SetMetadata(string key, string value)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetMetadata(MethodsPtr, key, value);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void DeleteMetadata(string key)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.DeleteMetadata(MethodsPtr, key);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void SetLocked(bool locked)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetLocked(MethodsPtr, locked);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}
	}
	public struct LobbyMemberTransaction
	{
		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result SetMetadataMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key, [MarshalAs(UnmanagedType.LPStr)] string value);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result DeleteMetadataMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key);

			internal SetMetadataMethod SetMetadata;

			internal DeleteMetadataMethod DeleteMetadata;
		}

		internal IntPtr MethodsPtr;

		internal object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public void SetMetadata(string key, string value)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetMetadata(MethodsPtr, key, value);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void DeleteMetadata(string key)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.DeleteMetadata(MethodsPtr, key);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}
	}
	public struct LobbySearchQuery
	{
		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result FilterMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key, LobbySearchComparison comparison, LobbySearchCast cast, [MarshalAs(UnmanagedType.LPStr)] string value);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result SortMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key, LobbySearchCast cast, [MarshalAs(UnmanagedType.LPStr)] string value);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result LimitMethod(IntPtr methodsPtr, uint limit);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result DistanceMethod(IntPtr methodsPtr, LobbySearchDistance distance);

			internal FilterMethod Filter;

			internal SortMethod Sort;

			internal LimitMethod Limit;

			internal DistanceMethod Distance;
		}

		internal IntPtr MethodsPtr;

		internal object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public void Filter(string key, LobbySearchComparison comparison, LobbySearchCast cast, string value)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.Filter(MethodsPtr, key, comparison, cast, value);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void Sort(string key, LobbySearchCast cast, string value)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.Sort(MethodsPtr, key, cast, value);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void Limit(uint limit)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.Limit(MethodsPtr, limit);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void Distance(LobbySearchDistance distance)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.Distance(MethodsPtr, distance);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}
	}
	public class ResultException : Exception
	{
		public readonly Result Result;

		public ResultException(Result result)
			: base(result.ToString())
		{
		}
	}
	public class Discord : IDisposable
	{
		internal struct FFIEvents
		{
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void DestroyHandler(IntPtr MethodsPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result RunCallbacksMethod(IntPtr methodsPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SetLogHookCallback(IntPtr ptr, LogLevel level, [MarshalAs(UnmanagedType.LPStr)] string message);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SetLogHookMethod(IntPtr methodsPtr, LogLevel minLevel, IntPtr callbackData, SetLogHookCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetApplicationManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetUserManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetImageManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetActivityManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetRelationshipManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetLobbyManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetNetworkManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetOverlayManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetStorageManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetStoreManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetVoiceManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate IntPtr GetAchievementManagerMethod(IntPtr discordPtr);

			internal DestroyHandler Destroy;

			internal RunCallbacksMethod RunCallbacks;

			internal SetLogHookMethod SetLogHook;

			internal GetApplicationManagerMethod GetApplicationManager;

			internal GetUserManagerMethod GetUserManager;

			internal GetImageManagerMethod GetImageManager;

			internal GetActivityManagerMethod GetActivityManager;

			internal GetRelationshipManagerMethod GetRelationshipManager;

			internal GetLobbyManagerMethod GetLobbyManager;

			internal GetNetworkManagerMethod GetNetworkManager;

			internal GetOverlayManagerMethod GetOverlayManager;

			internal GetStorageManagerMethod GetStorageManager;

			internal GetStoreManagerMethod GetStoreManager;

			internal GetVoiceManagerMethod GetVoiceManager;

			internal GetAchievementManagerMethod GetAchievementManager;
		}

		internal struct FFICreateParams
		{
			internal long ClientId;

			internal ulong Flags;

			internal IntPtr Events;

			internal IntPtr EventData;

			internal IntPtr ApplicationEvents;

			internal uint ApplicationVersion;

			internal IntPtr UserEvents;

			internal uint UserVersion;

			internal IntPtr ImageEvents;

			internal uint ImageVersion;

			internal IntPtr ActivityEvents;

			internal uint ActivityVersion;

			internal IntPtr RelationshipEvents;

			internal uint RelationshipVersion;

			internal IntPtr LobbyEvents;

			internal uint LobbyVersion;

			internal IntPtr NetworkEvents;

			internal uint NetworkVersion;

			internal IntPtr OverlayEvents;

			internal uint OverlayVersion;

			internal IntPtr StorageEvents;

			internal uint StorageVersion;

			internal IntPtr StoreEvents;

			internal uint StoreVersion;

			internal IntPtr VoiceEvents;

			internal uint VoiceVersion;

			internal IntPtr AchievementEvents;

			internal uint AchievementVersion;
		}

		public delegate void SetLogHookHandler(LogLevel level, string message);

		private GCHandle SelfHandle;

		private IntPtr EventsPtr;

		private FFIEvents Events;

		private IntPtr ApplicationEventsPtr;

		private ApplicationManager.FFIEvents ApplicationEvents;

		internal ApplicationManager ApplicationManagerInstance;

		private IntPtr UserEventsPtr;

		private UserManager.FFIEvents UserEvents;

		internal UserManager UserManagerInstance;

		private IntPtr ImageEventsPtr;

		private ImageManager.FFIEvents ImageEvents;

		internal ImageManager ImageManagerInstance;

		private IntPtr ActivityEventsPtr;

		private ActivityManager.FFIEvents ActivityEvents;

		internal ActivityManager ActivityManagerInstance;

		private IntPtr RelationshipEventsPtr;

		private RelationshipManager.FFIEvents RelationshipEvents;

		internal RelationshipManager RelationshipManagerInstance;

		private IntPtr LobbyEventsPtr;

		private LobbyManager.FFIEvents LobbyEvents;

		internal LobbyManager LobbyManagerInstance;

		private IntPtr NetworkEventsPtr;

		private NetworkManager.FFIEvents NetworkEvents;

		internal NetworkManager NetworkManagerInstance;

		private IntPtr OverlayEventsPtr;

		private OverlayManager.FFIEvents OverlayEvents;

		internal OverlayManager OverlayManagerInstance;

		private IntPtr StorageEventsPtr;

		private StorageManager.FFIEvents StorageEvents;

		internal StorageManager StorageManagerInstance;

		private IntPtr StoreEventsPtr;

		private StoreManager.FFIEvents StoreEvents;

		internal StoreManager StoreManagerInstance;

		private IntPtr VoiceEventsPtr;

		private VoiceManager.FFIEvents VoiceEvents;

		internal VoiceManager VoiceManagerInstance;

		private IntPtr AchievementEventsPtr;

		private AchievementManager.FFIEvents AchievementEvents;

		internal AchievementManager AchievementManagerInstance;

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private GCHandle? setLogHook;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		[DllImport("discord_game_sdk", ExactSpelling = true)]
		private static extern Result DiscordCreate(uint version, ref FFICreateParams createParams, out IntPtr manager);

		public Discord(long clientId, ulong flags)
		{
			FFICreateParams createParams = default(FFICreateParams);
			createParams.ClientId = clientId;
			createParams.Flags = flags;
			Events = default(FFIEvents);
			EventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(Events));
			createParams.Events = EventsPtr;
			SelfHandle = GCHandle.Alloc(this);
			createParams.EventData = GCHandle.ToIntPtr(SelfHandle);
			ApplicationEvents = default(ApplicationManager.FFIEvents);
			ApplicationEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ApplicationEvents));
			createParams.ApplicationEvents = ApplicationEventsPtr;
			createParams.ApplicationVersion = 1u;
			UserEvents = default(UserManager.FFIEvents);
			UserEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(UserEvents));
			createParams.UserEvents = UserEventsPtr;
			createParams.UserVersion = 1u;
			ImageEvents = default(ImageManager.FFIEvents);
			ImageEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ImageEvents));
			createParams.ImageEvents = ImageEventsPtr;
			createParams.ImageVersion = 1u;
			ActivityEvents = default(ActivityManager.FFIEvents);
			ActivityEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ActivityEvents));
			createParams.ActivityEvents = ActivityEventsPtr;
			createParams.ActivityVersion = 1u;
			RelationshipEvents = default(RelationshipManager.FFIEvents);
			RelationshipEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(RelationshipEvents));
			createParams.RelationshipEvents = RelationshipEventsPtr;
			createParams.RelationshipVersion = 1u;
			LobbyEvents = default(LobbyManager.FFIEvents);
			LobbyEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(LobbyEvents));
			createParams.LobbyEvents = LobbyEventsPtr;
			createParams.LobbyVersion = 1u;
			NetworkEvents = default(NetworkManager.FFIEvents);
			NetworkEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(NetworkEvents));
			createParams.NetworkEvents = NetworkEventsPtr;
			createParams.NetworkVersion = 1u;
			OverlayEvents = default(OverlayManager.FFIEvents);
			OverlayEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(OverlayEvents));
			createParams.OverlayEvents = OverlayEventsPtr;
			createParams.OverlayVersion = 2u;
			StorageEvents = default(StorageManager.FFIEvents);
			StorageEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(StorageEvents));
			createParams.StorageEvents = StorageEventsPtr;
			createParams.StorageVersion = 1u;
			StoreEvents = default(StoreManager.FFIEvents);
			StoreEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(StoreEvents));
			createParams.StoreEvents = StoreEventsPtr;
			createParams.StoreVersion = 1u;
			VoiceEvents = default(VoiceManager.FFIEvents);
			VoiceEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VoiceEvents));
			createParams.VoiceEvents = VoiceEventsPtr;
			createParams.VoiceVersion = 1u;
			AchievementEvents = default(AchievementManager.FFIEvents);
			AchievementEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(AchievementEvents));
			createParams.AchievementEvents = AchievementEventsPtr;
			createParams.AchievementVersion = 1u;
			InitEvents(EventsPtr, ref Events);
			Result result = DiscordCreate(3u, ref createParams, out MethodsPtr);
			if (result != 0)
			{
				Dispose();
				throw new ResultException(result);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public void Dispose()
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Methods.Destroy(MethodsPtr);
			}
			SelfHandle.Free();
			Marshal.FreeHGlobal(EventsPtr);
			Marshal.FreeHGlobal(ApplicationEventsPtr);
			Marshal.FreeHGlobal(UserEventsPtr);
			Marshal.FreeHGlobal(ImageEventsPtr);
			Marshal.FreeHGlobal(ActivityEventsPtr);
			Marshal.FreeHGlobal(RelationshipEventsPtr);
			Marshal.FreeHGlobal(LobbyEventsPtr);
			Marshal.FreeHGlobal(NetworkEventsPtr);
			Marshal.FreeHGlobal(OverlayEventsPtr);
			Marshal.FreeHGlobal(StorageEventsPtr);
			Marshal.FreeHGlobal(StoreEventsPtr);
			Marshal.FreeHGlobal(VoiceEventsPtr);
			Marshal.FreeHGlobal(AchievementEventsPtr);
			if (setLogHook.HasValue)
			{
				setLogHook.Value.Free();
			}
		}

		public void RunCallbacks()
		{
			Result result = Methods.RunCallbacks(MethodsPtr);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		[MonoPInvokeCallback]
		private static void SetLogHookCallbackImpl(IntPtr ptr, LogLevel level, string message)
		{
			SetLogHookHandler setLogHookHandler = (SetLogHookHandler)GCHandle.FromIntPtr(ptr).Target;
			setLogHookHandler(level, message);
		}

		public void SetLogHook(LogLevel minLevel, SetLogHookHandler callback)
		{
			if (setLogHook.HasValue)
			{
				setLogHook.Value.Free();
			}
			setLogHook = GCHandle.Alloc(callback);
			Methods.SetLogHook(MethodsPtr, minLevel, GCHandle.ToIntPtr(setLogHook.Value), SetLogHookCallbackImpl);
		}

		public ApplicationManager GetApplicationManager()
		{
			if (ApplicationManagerInstance == null)
			{
				ApplicationManagerInstance = new ApplicationManager(Methods.GetApplicationManager(MethodsPtr), ApplicationEventsPtr, ref ApplicationEvents);
			}
			return ApplicationManagerInstance;
		}

		public UserManager GetUserManager()
		{
			if (UserManagerInstance == null)
			{
				UserManagerInstance = new UserManager(Methods.GetUserManager(MethodsPtr), UserEventsPtr, ref UserEvents);
			}
			return UserManagerInstance;
		}

		public ImageManager GetImageManager()
		{
			if (ImageManagerInstance == null)
			{
				ImageManagerInstance = new ImageManager(Methods.GetImageManager(MethodsPtr), ImageEventsPtr, ref ImageEvents);
			}
			return ImageManagerInstance;
		}

		public ActivityManager GetActivityManager()
		{
			if (ActivityManagerInstance == null)
			{
				ActivityManagerInstance = new ActivityManager(Methods.GetActivityManager(MethodsPtr), ActivityEventsPtr, ref ActivityEvents);
			}
			return ActivityManagerInstance;
		}

		public RelationshipManager GetRelationshipManager()
		{
			if (RelationshipManagerInstance == null)
			{
				RelationshipManagerInstance = new RelationshipManager(Methods.GetRelationshipManager(MethodsPtr), RelationshipEventsPtr, ref RelationshipEvents);
			}
			return RelationshipManagerInstance;
		}

		public LobbyManager GetLobbyManager()
		{
			if (LobbyManagerInstance == null)
			{
				LobbyManagerInstance = new LobbyManager(Methods.GetLobbyManager(MethodsPtr), LobbyEventsPtr, ref LobbyEvents);
			}
			return LobbyManagerInstance;
		}

		public NetworkManager GetNetworkManager()
		{
			if (NetworkManagerInstance == null)
			{
				NetworkManagerInstance = new NetworkManager(Methods.GetNetworkManager(MethodsPtr), NetworkEventsPtr, ref NetworkEvents);
			}
			return NetworkManagerInstance;
		}

		public OverlayManager GetOverlayManager()
		{
			if (OverlayManagerInstance == null)
			{
				OverlayManagerInstance = new OverlayManager(Methods.GetOverlayManager(MethodsPtr), OverlayEventsPtr, ref OverlayEvents);
			}
			return OverlayManagerInstance;
		}

		public StorageManager GetStorageManager()
		{
			if (StorageManagerInstance == null)
			{
				StorageManagerInstance = new StorageManager(Methods.GetStorageManager(MethodsPtr), StorageEventsPtr, ref StorageEvents);
			}
			return StorageManagerInstance;
		}

		public StoreManager GetStoreManager()
		{
			if (StoreManagerInstance == null)
			{
				StoreManagerInstance = new StoreManager(Methods.GetStoreManager(MethodsPtr), StoreEventsPtr, ref StoreEvents);
			}
			return StoreManagerInstance;
		}

		public VoiceManager GetVoiceManager()
		{
			if (VoiceManagerInstance == null)
			{
				VoiceManagerInstance = new VoiceManager(Methods.GetVoiceManager(MethodsPtr), VoiceEventsPtr, ref VoiceEvents);
			}
			return VoiceManagerInstance;
		}

		public AchievementManager GetAchievementManager()
		{
			if (AchievementManagerInstance == null)
			{
				AchievementManagerInstance = new AchievementManager(Methods.GetAchievementManager(MethodsPtr), AchievementEventsPtr, ref AchievementEvents);
			}
			return AchievementManagerInstance;
		}
	}
	internal class MonoPInvokeCallbackAttribute : Attribute
	{
	}
	public class ApplicationManager
	{
		internal struct FFIEvents
		{
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ValidateOrExitCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ValidateOrExitMethod(IntPtr methodsPtr, IntPtr callbackData, ValidateOrExitCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void GetCurrentLocaleMethod(IntPtr methodsPtr, StringBuilder locale);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void GetCurrentBranchMethod(IntPtr methodsPtr, StringBuilder branch);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void GetOAuth2TokenCallback(IntPtr ptr, Result result, ref OAuth2Token oauth2Token);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void GetOAuth2TokenMethod(IntPtr methodsPtr, IntPtr callbackData, GetOAuth2TokenCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void GetTicketCallback(IntPtr ptr, Result result, [MarshalAs(UnmanagedType.LPStr)] ref string data);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void GetTicketMethod(IntPtr methodsPtr, IntPtr callbackData, GetTicketCallback callback);

			internal ValidateOrExitMethod ValidateOrExit;

			internal GetCurrentLocaleMethod GetCurrentLocale;

			internal GetCurrentBranchMethod GetCurrentBranch;

			internal GetOAuth2TokenMethod GetOAuth2Token;

			internal GetTicketMethod GetTicket;
		}

		public delegate void ValidateOrExitHandler(Result result);

		public delegate void GetOAuth2TokenHandler(Result result, ref OAuth2Token oauth2Token);

		public delegate void GetTicketHandler(Result result, ref string data);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		internal ApplicationManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		[MonoPInvokeCallback]
		private static void ValidateOrExitCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			ValidateOrExitHandler validateOrExitHandler = (ValidateOrExitHandler)gCHandle.Target;
			gCHandle.Free();
			validateOrExitHandler(result);
		}

		public void ValidateOrExit(ValidateOrExitHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.ValidateOrExit(MethodsPtr, GCHandle.ToIntPtr(value), ValidateOrExitCallbackImpl);
		}

		public string GetCurrentLocale()
		{
			StringBuilder stringBuilder = new StringBuilder(128);
			Methods.GetCurrentLocale(MethodsPtr, stringBuilder);
			return stringBuilder.ToString();
		}

		public string GetCurrentBranch()
		{
			StringBuilder stringBuilder = new StringBuilder(4096);
			Methods.GetCurrentBranch(MethodsPtr, stringBuilder);
			return stringBuilder.ToString();
		}

		[MonoPInvokeCallback]
		private static void GetOAuth2TokenCallbackImpl(IntPtr ptr, Result result, ref OAuth2Token oauth2Token)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			GetOAuth2TokenHandler getOAuth2TokenHandler = (GetOAuth2TokenHandler)gCHandle.Target;
			gCHandle.Free();
			getOAuth2TokenHandler(result, ref oauth2Token);
		}

		public void GetOAuth2Token(GetOAuth2TokenHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.GetOAuth2Token(MethodsPtr, GCHandle.ToIntPtr(value), GetOAuth2TokenCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void GetTicketCallbackImpl(IntPtr ptr, Result result, ref string data)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			GetTicketHandler getTicketHandler = (GetTicketHandler)gCHandle.Target;
			gCHandle.Free();
			getTicketHandler(result, ref data);
		}

		public void GetTicket(GetTicketHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.GetTicket(MethodsPtr, GCHandle.ToIntPtr(value), GetTicketCallbackImpl);
		}
	}
	public class UserManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void CurrentUserUpdateHandler(IntPtr ptr);

			internal CurrentUserUpdateHandler OnCurrentUserUpdate;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetCurrentUserMethod(IntPtr methodsPtr, ref User currentUser);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void GetUserCallback(IntPtr ptr, Result result, ref User user);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void GetUserMethod(IntPtr methodsPtr, long userId, IntPtr callbackData, GetUserCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetCurrentUserPremiumTypeMethod(IntPtr methodsPtr, ref PremiumType premiumType);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result CurrentUserHasFlagMethod(IntPtr methodsPtr, UserFlag flag, ref bool hasFlag);

			internal GetCurrentUserMethod GetCurrentUser;

			internal GetUserMethod GetUser;

			internal GetCurrentUserPremiumTypeMethod GetCurrentUserPremiumType;

			internal CurrentUserHasFlagMethod CurrentUserHasFlag;
		}

		public delegate void GetUserHandler(Result result, ref User user);

		public delegate void CurrentUserUpdateHandler();

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event CurrentUserUpdateHandler OnCurrentUserUpdate;

		internal UserManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnCurrentUserUpdate = OnCurrentUserUpdateImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public User GetCurrentUser()
		{
			User currentUser = default(User);
			Result result = Methods.GetCurrentUser(MethodsPtr, ref currentUser);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return currentUser;
		}

		[MonoPInvokeCallback]
		private static void GetUserCallbackImpl(IntPtr ptr, Result result, ref User user)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			GetUserHandler getUserHandler = (GetUserHandler)gCHandle.Target;
			gCHandle.Free();
			getUserHandler(result, ref user);
		}

		public void GetUser(long userId, GetUserHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.GetUser(MethodsPtr, userId, GCHandle.ToIntPtr(value), GetUserCallbackImpl);
		}

		public PremiumType GetCurrentUserPremiumType()
		{
			PremiumType premiumType = PremiumType.None;
			Result result = Methods.GetCurrentUserPremiumType(MethodsPtr, ref premiumType);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return premiumType;
		}

		public bool CurrentUserHasFlag(UserFlag flag)
		{
			bool hasFlag = false;
			Result result = Methods.CurrentUserHasFlag(MethodsPtr, flag, ref hasFlag);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return hasFlag;
		}

		[MonoPInvokeCallback]
		private static void OnCurrentUserUpdateImpl(IntPtr ptr)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.UserManagerInstance.OnCurrentUserUpdate != null)
			{
				discord.UserManagerInstance.OnCurrentUserUpdate();
			}
		}
	}
	public class ImageManager
	{
		internal struct FFIEvents
		{
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void FetchCallback(IntPtr ptr, Result result, ImageHandle handleResult);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void FetchMethod(IntPtr methodsPtr, ImageHandle handle, bool refresh, IntPtr callbackData, FetchCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetDimensionsMethod(IntPtr methodsPtr, ImageHandle handle, ref ImageDimensions dimensions);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetDataMethod(IntPtr methodsPtr, ImageHandle handle, byte[] data, int dataLen);

			internal FetchMethod Fetch;

			internal GetDimensionsMethod GetDimensions;

			internal GetDataMethod GetData;
		}

		public delegate void FetchHandler(Result result, ImageHandle handleResult);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		internal ImageManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		[MonoPInvokeCallback]
		private static void FetchCallbackImpl(IntPtr ptr, Result result, ImageHandle handleResult)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			FetchHandler fetchHandler = (FetchHandler)gCHandle.Target;
			gCHandle.Free();
			fetchHandler(result, handleResult);
		}

		public void Fetch(ImageHandle handle, bool refresh, FetchHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.Fetch(MethodsPtr, handle, refresh, GCHandle.ToIntPtr(value), FetchCallbackImpl);
		}

		public ImageDimensions GetDimensions(ImageHandle handle)
		{
			ImageDimensions dimensions = default(ImageDimensions);
			Result result = Methods.GetDimensions(MethodsPtr, handle, ref dimensions);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return dimensions;
		}

		public void GetData(ImageHandle handle, byte[] data)
		{
			Result result = Methods.GetData(MethodsPtr, handle, data, data.Length);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void Fetch(ImageHandle handle, FetchHandler callback)
		{
			Fetch(handle, refresh: false, callback);
		}

		public byte[] GetData(ImageHandle handle)
		{
			ImageDimensions dimensions = GetDimensions(handle);
			byte[] array = new byte[dimensions.Width * dimensions.Height * 4];
			GetData(handle, array);
			return array;
		}
	}
	public class RelationshipManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void RefreshHandler(IntPtr ptr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void RelationshipUpdateHandler(IntPtr ptr, ref Relationship relationship);

			internal RefreshHandler OnRefresh;

			internal RelationshipUpdateHandler OnRelationshipUpdate;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate bool FilterCallback(IntPtr ptr, ref Relationship relationship);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void FilterMethod(IntPtr methodsPtr, IntPtr callbackData, FilterCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result CountMethod(IntPtr methodsPtr, ref int count);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetMethod(IntPtr methodsPtr, long userId, ref Relationship relationship);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetAtMethod(IntPtr methodsPtr, uint index, ref Relationship relationship);

			internal FilterMethod Filter;

			internal CountMethod Count;

			internal GetMethod Get;

			internal GetAtMethod GetAt;
		}

		public delegate bool FilterHandler(ref Relationship relationship);

		public delegate void RefreshHandler();

		public delegate void RelationshipUpdateHandler(ref Relationship relationship);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event RefreshHandler OnRefresh;

		public event RelationshipUpdateHandler OnRelationshipUpdate;

		internal RelationshipManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnRefresh = OnRefreshImpl;
			events.OnRelationshipUpdate = OnRelationshipUpdateImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		[MonoPInvokeCallback]
		private static bool FilterCallbackImpl(IntPtr ptr, ref Relationship relationship)
		{
			FilterHandler filterHandler = (FilterHandler)GCHandle.FromIntPtr(ptr).Target;
			return filterHandler(ref relationship);
		}

		public void Filter(FilterHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.Filter(MethodsPtr, GCHandle.ToIntPtr(value), FilterCallbackImpl);
			value.Free();
		}

		public int Count()
		{
			int count = 0;
			Result result = Methods.Count(MethodsPtr, ref count);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return count;
		}

		public Relationship Get(long userId)
		{
			Relationship relationship = default(Relationship);
			Result result = Methods.Get(MethodsPtr, userId, ref relationship);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return relationship;
		}

		public Relationship GetAt(uint index)
		{
			Relationship relationship = default(Relationship);
			Result result = Methods.GetAt(MethodsPtr, index, ref relationship);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return relationship;
		}

		[MonoPInvokeCallback]
		private static void OnRefreshImpl(IntPtr ptr)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.RelationshipManagerInstance.OnRefresh != null)
			{
				discord.RelationshipManagerInstance.OnRefresh();
			}
		}

		[MonoPInvokeCallback]
		private static void OnRelationshipUpdateImpl(IntPtr ptr, ref Relationship relationship)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.RelationshipManagerInstance.OnRelationshipUpdate != null)
			{
				discord.RelationshipManagerInstance.OnRelationshipUpdate(ref relationship);
			}
		}
	}
	public class LobbyManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void LobbyUpdateHandler(IntPtr ptr, long lobbyId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void LobbyDeleteHandler(IntPtr ptr, long lobbyId, uint reason);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void MemberConnectHandler(IntPtr ptr, long lobbyId, long userId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void MemberUpdateHandler(IntPtr ptr, long lobbyId, long userId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void MemberDisconnectHandler(IntPtr ptr, long lobbyId, long userId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void LobbyMessageHandler(IntPtr ptr, long lobbyId, long userId, IntPtr dataPtr, int dataLen);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SpeakingHandler(IntPtr ptr, long lobbyId, long userId, bool speaking);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void NetworkMessageHandler(IntPtr ptr, long lobbyId, long userId, byte channelId, IntPtr dataPtr, int dataLen);

			internal LobbyUpdateHandler OnLobbyUpdate;

			internal LobbyDeleteHandler OnLobbyDelete;

			internal MemberConnectHandler OnMemberConnect;

			internal MemberUpdateHandler OnMemberUpdate;

			internal MemberDisconnectHandler OnMemberDisconnect;

			internal LobbyMessageHandler OnLobbyMessage;

			internal SpeakingHandler OnSpeaking;

			internal NetworkMessageHandler OnNetworkMessage;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetLobbyCreateTransactionMethod(IntPtr methodsPtr, ref IntPtr transaction);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetLobbyUpdateTransactionMethod(IntPtr methodsPtr, long lobbyId, ref IntPtr transaction);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetMemberUpdateTransactionMethod(IntPtr methodsPtr, long lobbyId, long userId, ref IntPtr transaction);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void CreateLobbyCallback(IntPtr ptr, Result result, ref Lobby lobby);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void CreateLobbyMethod(IntPtr methodsPtr, IntPtr transaction, IntPtr callbackData, CreateLobbyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void UpdateLobbyCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void UpdateLobbyMethod(IntPtr methodsPtr, long lobbyId, IntPtr transaction, IntPtr callbackData, UpdateLobbyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void DeleteLobbyCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void DeleteLobbyMethod(IntPtr methodsPtr, long lobbyId, IntPtr callbackData, DeleteLobbyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ConnectLobbyCallback(IntPtr ptr, Result result, ref Lobby lobby);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ConnectLobbyMethod(IntPtr methodsPtr, long lobbyId, [MarshalAs(UnmanagedType.LPStr)] string secret, IntPtr callbackData, ConnectLobbyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ConnectLobbyWithActivitySecretCallback(IntPtr ptr, Result result, ref Lobby lobby);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ConnectLobbyWithActivitySecretMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string activitySecret, IntPtr callbackData, ConnectLobbyWithActivitySecretCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void DisconnectLobbyCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void DisconnectLobbyMethod(IntPtr methodsPtr, long lobbyId, IntPtr callbackData, DisconnectLobbyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetLobbyMethod(IntPtr methodsPtr, long lobbyId, ref Lobby lobby);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetLobbyActivitySecretMethod(IntPtr methodsPtr, long lobbyId, StringBuilder secret);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetLobbyMetadataValueMethod(IntPtr methodsPtr, long lobbyId, [MarshalAs(UnmanagedType.LPStr)] string key, StringBuilder value);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetLobbyMetadataKeyMethod(IntPtr methodsPtr, long lobbyId, int index, StringBuilder key);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result LobbyMetadataCountMethod(IntPtr methodsPtr, long lobbyId, ref int count);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result MemberCountMethod(IntPtr methodsPtr, long lobbyId, ref int count);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetMemberUserIdMethod(IntPtr methodsPtr, long lobbyId, int index, ref long userId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetMemberUserMethod(IntPtr methodsPtr, long lobbyId, long userId, ref User user);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetMemberMetadataValueMethod(IntPtr methodsPtr, long lobbyId, long userId, [MarshalAs(UnmanagedType.LPStr)] string key, StringBuilder value);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetMemberMetadataKeyMethod(IntPtr methodsPtr, long lobbyId, long userId, int index, StringBuilder key);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result MemberMetadataCountMethod(IntPtr methodsPtr, long lobbyId, long userId, ref int count);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void UpdateMemberCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void UpdateMemberMethod(IntPtr methodsPtr, long lobbyId, long userId, IntPtr transaction, IntPtr callbackData, UpdateMemberCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SendLobbyMessageCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SendLobbyMessageMethod(IntPtr methodsPtr, long lobbyId, byte[] data, int dataLen, IntPtr callbackData, SendLobbyMessageCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetSearchQueryMethod(IntPtr methodsPtr, ref IntPtr query);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SearchCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SearchMethod(IntPtr methodsPtr, IntPtr query, IntPtr callbackData, SearchCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void LobbyCountMethod(IntPtr methodsPtr, ref int count);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result GetLobbyIdMethod(IntPtr methodsPtr, int index, ref long lobbyId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ConnectVoiceCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ConnectVoiceMethod(IntPtr methodsPtr, long lobbyId, IntPtr callbackData, ConnectVoiceCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void DisconnectVoiceCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void DisconnectVoiceMethod(IntPtr methodsPtr, long lobbyId, IntPtr callbackData, DisconnectVoiceCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result ConnectNetworkMethod(IntPtr methodsPtr, long lobbyId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result DisconnectNetworkMethod(IntPtr methodsPtr, long lobbyId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result FlushNetworkMethod(IntPtr methodsPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result OpenNetworkChannelMethod(IntPtr methodsPtr, long lobbyId, byte channelId, bool reliable);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result SendNetworkMessageMethod(IntPtr methodsPtr, long lobbyId, long userId, byte channelId, byte[] data, int dataLen);

			internal GetLobbyCreateTransactionMethod GetLobbyCreateTransaction;

			internal GetLobbyUpdateTransactionMethod GetLobbyUpdateTransaction;

			internal GetMemberUpdateTransactionMethod GetMemberUpdateTransaction;

			internal CreateLobbyMethod CreateLobby;

			internal UpdateLobbyMethod UpdateLobby;

			internal DeleteLobbyMethod DeleteLobby;

			internal ConnectLobbyMethod ConnectLobby;

			internal ConnectLobbyWithActivitySecretMethod ConnectLobbyWithActivitySecret;

			internal DisconnectLobbyMethod DisconnectLobby;

			internal GetLobbyMethod GetLobby;

			internal GetLobbyActivitySecretMethod GetLobbyActivitySecret;

			internal GetLobbyMetadataValueMethod GetLobbyMetadataValue;

			internal GetLobbyMetadataKeyMethod GetLobbyMetadataKey;

			internal LobbyMetadataCountMethod LobbyMetadataCount;

			internal MemberCountMethod MemberCount;

			internal GetMemberUserIdMethod GetMemberUserId;

			internal GetMemberUserMethod GetMemberUser;

			internal GetMemberMetadataValueMethod GetMemberMetadataValue;

			internal GetMemberMetadataKeyMethod GetMemberMetadataKey;

			internal MemberMetadataCountMethod MemberMetadataCount;

			internal UpdateMemberMethod UpdateMember;

			internal SendLobbyMessageMethod SendLobbyMessage;

			internal GetSearchQueryMethod GetSearchQuery;

			internal SearchMethod Search;

			internal LobbyCountMethod LobbyCount;

			internal GetLobbyIdMethod GetLobbyId;

			internal ConnectVoiceMethod ConnectVoice;

			internal DisconnectVoiceMethod DisconnectVoice;

			internal ConnectNetworkMethod ConnectNetwork;

			internal DisconnectNetworkMethod DisconnectNetwork;

			internal FlushNetworkMethod FlushNetwork;

			internal OpenNetworkChannelMethod OpenNetworkChannel;

			internal SendNetworkMessageMethod SendNetworkMessage;
		}

		public delegate void CreateLobbyHandler(Result result, ref Lobby lobby);

		public delegate void UpdateLobbyHandler(Result result);

		public delegate void DeleteLobbyHandler(Result result);

		public delegate void ConnectLobbyHandler(Result result, ref Lobby lobby);

		public delegate void ConnectLobbyWithActivitySecretHandler(Result result, ref Lobby lobby);

		public delegate void DisconnectLobbyHandler(Result result);

		public delegate void UpdateMemberHandler(Result result);

		public delegate void SendLobbyMessageHandler(Result result);

		public delegate void SearchHandler(Result result);

		public delegate void ConnectVoiceHandler(Result result);

		public delegate void DisconnectVoiceHandler(Result result);

		public delegate void LobbyUpdateHandler(long lobbyId);

		public delegate void LobbyDeleteHandler(long lobbyId, uint reason);

		public delegate void MemberConnectHandler(long lobbyId, long userId);

		public delegate void MemberUpdateHandler(long lobbyId, long userId);

		public delegate void MemberDisconnectHandler(long lobbyId, long userId);

		public delegate void LobbyMessageHandler(long lobbyId, long userId, byte[] data);

		public delegate void SpeakingHandler(long lobbyId, long userId, bool speaking);

		public delegate void NetworkMessageHandler(long lobbyId, long userId, byte channelId, byte[] data);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event LobbyUpdateHandler OnLobbyUpdate;

		public event LobbyDeleteHandler OnLobbyDelete;

		public event MemberConnectHandler OnMemberConnect;

		public event MemberUpdateHandler OnMemberUpdate;

		public event MemberDisconnectHandler OnMemberDisconnect;

		public event LobbyMessageHandler OnLobbyMessage;

		public event SpeakingHandler OnSpeaking;

		public event NetworkMessageHandler OnNetworkMessage;

		internal LobbyManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnLobbyUpdate = OnLobbyUpdateImpl;
			events.OnLobbyDelete = OnLobbyDeleteImpl;
			events.OnMemberConnect = OnMemberConnectImpl;
			events.OnMemberUpdate = OnMemberUpdateImpl;
			events.OnMemberDisconnect = OnMemberDisconnectImpl;
			events.OnLobbyMessage = OnLobbyMessageImpl;
			events.OnSpeaking = OnSpeakingImpl;
			events.OnNetworkMessage = OnNetworkMessageImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public LobbyTransaction GetLobbyCreateTransaction()
		{
			LobbyTransaction result = default(LobbyTransaction);
			Result result2 = Methods.GetLobbyCreateTransaction(MethodsPtr, ref result.MethodsPtr);
			if (result2 != 0)
			{
				throw new ResultException(result2);
			}
			return result;
		}

		public LobbyTransaction GetLobbyUpdateTransaction(long lobbyId)
		{
			LobbyTransaction result = default(LobbyTransaction);
			Result result2 = Methods.GetLobbyUpdateTransaction(MethodsPtr, lobbyId, ref result.MethodsPtr);
			if (result2 != 0)
			{
				throw new ResultException(result2);
			}
			return result;
		}

		public LobbyMemberTransaction GetMemberUpdateTransaction(long lobbyId, long userId)
		{
			LobbyMemberTransaction result = default(LobbyMemberTransaction);
			Result result2 = Methods.GetMemberUpdateTransaction(MethodsPtr, lobbyId, userId, ref result.MethodsPtr);
			if (result2 != 0)
			{
				throw new ResultException(result2);
			}
			return result;
		}

		[MonoPInvokeCallback]
		private static void CreateLobbyCallbackImpl(IntPtr ptr, Result result, ref Lobby lobby)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			CreateLobbyHandler createLobbyHandler = (CreateLobbyHandler)gCHandle.Target;
			gCHandle.Free();
			createLobbyHandler(result, ref lobby);
		}

		public void CreateLobby(LobbyTransaction transaction, CreateLobbyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.CreateLobby(MethodsPtr, transaction.MethodsPtr, GCHandle.ToIntPtr(value), CreateLobbyCallbackImpl);
			transaction.MethodsPtr = IntPtr.Zero;
		}

		[MonoPInvokeCallback]
		private static void UpdateLobbyCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			UpdateLobbyHandler updateLobbyHandler = (UpdateLobbyHandler)gCHandle.Target;
			gCHandle.Free();
			updateLobbyHandler(result);
		}

		public void UpdateLobby(long lobbyId, LobbyTransaction transaction, UpdateLobbyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.UpdateLobby(MethodsPtr, lobbyId, transaction.MethodsPtr, GCHandle.ToIntPtr(value), UpdateLobbyCallbackImpl);
			transaction.MethodsPtr = IntPtr.Zero;
		}

		[MonoPInvokeCallback]
		private static void DeleteLobbyCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			DeleteLobbyHandler deleteLobbyHandler = (DeleteLobbyHandler)gCHandle.Target;
			gCHandle.Free();
			deleteLobbyHandler(result);
		}

		public void DeleteLobby(long lobbyId, DeleteLobbyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.DeleteLobby(MethodsPtr, lobbyId, GCHandle.ToIntPtr(value), DeleteLobbyCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void ConnectLobbyCallbackImpl(IntPtr ptr, Result result, ref Lobby lobby)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			ConnectLobbyHandler connectLobbyHandler = (ConnectLobbyHandler)gCHandle.Target;
			gCHandle.Free();
			connectLobbyHandler(result, ref lobby);
		}

		public void ConnectLobby(long lobbyId, string secret, ConnectLobbyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.ConnectLobby(MethodsPtr, lobbyId, secret, GCHandle.ToIntPtr(value), ConnectLobbyCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void ConnectLobbyWithActivitySecretCallbackImpl(IntPtr ptr, Result result, ref Lobby lobby)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			ConnectLobbyWithActivitySecretHandler connectLobbyWithActivitySecretHandler = (ConnectLobbyWithActivitySecretHandler)gCHandle.Target;
			gCHandle.Free();
			connectLobbyWithActivitySecretHandler(result, ref lobby);
		}

		public void ConnectLobbyWithActivitySecret(string activitySecret, ConnectLobbyWithActivitySecretHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.ConnectLobbyWithActivitySecret(MethodsPtr, activitySecret, GCHandle.ToIntPtr(value), ConnectLobbyWithActivitySecretCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void DisconnectLobbyCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			DisconnectLobbyHandler disconnectLobbyHandler = (DisconnectLobbyHandler)gCHandle.Target;
			gCHandle.Free();
			disconnectLobbyHandler(result);
		}

		public void DisconnectLobby(long lobbyId, DisconnectLobbyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.DisconnectLobby(MethodsPtr, lobbyId, GCHandle.ToIntPtr(value), DisconnectLobbyCallbackImpl);
		}

		public Lobby GetLobby(long lobbyId)
		{
			Lobby lobby = default(Lobby);
			Result result = Methods.GetLobby(MethodsPtr, lobbyId, ref lobby);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return lobby;
		}

		public string GetLobbyActivitySecret(long lobbyId)
		{
			StringBuilder stringBuilder = new StringBuilder(128);
			Result result = Methods.GetLobbyActivitySecret(MethodsPtr, lobbyId, stringBuilder);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return stringBuilder.ToString();
		}

		public string GetLobbyMetadataValue(long lobbyId, string key)
		{
			StringBuilder stringBuilder = new StringBuilder(4096);
			Result result = Methods.GetLobbyMetadataValue(MethodsPtr, lobbyId, key, stringBuilder);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return stringBuilder.ToString();
		}

		public string GetLobbyMetadataKey(long lobbyId, int index)
		{
			StringBuilder stringBuilder = new StringBuilder(256);
			Result result = Methods.GetLobbyMetadataKey(MethodsPtr, lobbyId, index, stringBuilder);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return stringBuilder.ToString();
		}

		public int LobbyMetadataCount(long lobbyId)
		{
			int count = 0;
			Result result = Methods.LobbyMetadataCount(MethodsPtr, lobbyId, ref count);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return count;
		}

		public int MemberCount(long lobbyId)
		{
			int count = 0;
			Result result = Methods.MemberCount(MethodsPtr, lobbyId, ref count);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return count;
		}

		public long GetMemberUserId(long lobbyId, int index)
		{
			long userId = 0L;
			Result result = Methods.GetMemberUserId(MethodsPtr, lobbyId, index, ref userId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return userId;
		}

		public User GetMemberUser(long lobbyId, long userId)
		{
			User user = default(User);
			Result result = Methods.GetMemberUser(MethodsPtr, lobbyId, userId, ref user);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return user;
		}

		public string GetMemberMetadataValue(long lobbyId, long userId, string key)
		{
			StringBuilder stringBuilder = new StringBuilder(4096);
			Result result = Methods.GetMemberMetadataValue(MethodsPtr, lobbyId, userId, key, stringBuilder);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return stringBuilder.ToString();
		}

		public string GetMemberMetadataKey(long lobbyId, long userId, int index)
		{
			StringBuilder stringBuilder = new StringBuilder(256);
			Result result = Methods.GetMemberMetadataKey(MethodsPtr, lobbyId, userId, index, stringBuilder);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return stringBuilder.ToString();
		}

		public int MemberMetadataCount(long lobbyId, long userId)
		{
			int count = 0;
			Result result = Methods.MemberMetadataCount(MethodsPtr, lobbyId, userId, ref count);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return count;
		}

		[MonoPInvokeCallback]
		private static void UpdateMemberCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			UpdateMemberHandler updateMemberHandler = (UpdateMemberHandler)gCHandle.Target;
			gCHandle.Free();
			updateMemberHandler(result);
		}

		public void UpdateMember(long lobbyId, long userId, LobbyMemberTransaction transaction, UpdateMemberHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.UpdateMember(MethodsPtr, lobbyId, userId, transaction.MethodsPtr, GCHandle.ToIntPtr(value), UpdateMemberCallbackImpl);
			transaction.MethodsPtr = IntPtr.Zero;
		}

		[MonoPInvokeCallback]
		private static void SendLobbyMessageCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SendLobbyMessageHandler sendLobbyMessageHandler = (SendLobbyMessageHandler)gCHandle.Target;
			gCHandle.Free();
			sendLobbyMessageHandler(result);
		}

		public void SendLobbyMessage(long lobbyId, byte[] data, SendLobbyMessageHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.SendLobbyMessage(MethodsPtr, lobbyId, data, data.Length, GCHandle.ToIntPtr(value), SendLobbyMessageCallbackImpl);
		}

		public LobbySearchQuery GetSearchQuery()
		{
			LobbySearchQuery result = default(LobbySearchQuery);
			Result result2 = Methods.GetSearchQuery(MethodsPtr, ref result.MethodsPtr);
			if (result2 != 0)
			{
				throw new ResultException(result2);
			}
			return result;
		}

		[MonoPInvokeCallback]
		private static void SearchCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SearchHandler searchHandler = (SearchHandler)gCHandle.Target;
			gCHandle.Free();
			searchHandler(result);
		}

		public void Search(LobbySearchQuery query, SearchHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.Search(MethodsPtr, query.MethodsPtr, GCHandle.ToIntPtr(value), SearchCallbackImpl);
			query.MethodsPtr = IntPtr.Zero;
		}

		public int LobbyCount()
		{
			int count = 0;
			Methods.LobbyCount(MethodsPtr, ref count);
			return count;
		}

		public long GetLobbyId(int index)
		{
			long lobbyId = 0L;
			Result result = Methods.GetLobbyId(MethodsPtr, index, ref lobbyId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return lobbyId;
		}

		[MonoPInvokeCallback]
		private static void ConnectVoiceCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			ConnectVoiceHandler connectVoiceHandler = (ConnectVoiceHandler)gCHandle.Target;
			gCHandle.Free();
			connectVoiceHandler(result);
		}

		public void ConnectVoice(long lobbyId, ConnectVoiceHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.ConnectVoice(MethodsPtr, lobbyId, GCHandle.ToIntPtr(value), ConnectVoiceCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void DisconnectVoiceCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			DisconnectVoiceHandler disconnectVoiceHandler = (DisconnectVoiceHandler)gCHandle.Target;
			gCHandle.Free();
			disconnectVoiceHandler(result);
		}

		public void DisconnectVoice(long lobbyId, DisconnectVoiceHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.DisconnectVoice(MethodsPtr, lobbyId, GCHandle.ToIntPtr(value), DisconnectVoiceCallbackImpl);
		}

		public void ConnectNetwork(long lobbyId)
		{
			Result result = Methods.ConnectNetwork(MethodsPtr, lobbyId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void DisconnectNetwork(long lobbyId)
		{
			Result result = Methods.DisconnectNetwork(MethodsPtr, lobbyId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void FlushNetwork()
		{
			Result result = Methods.FlushNetwork(MethodsPtr);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void OpenNetworkChannel(long lobbyId, byte channelId, bool reliable)
		{
			Result result = Methods.OpenNetworkChannel(MethodsPtr, lobbyId, channelId, reliable);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void SendNetworkMessage(long lobbyId, long userId, byte channelId, byte[] data)
		{
			Result result = Methods.SendNetworkMessage(MethodsPtr, lobbyId, userId, channelId, data, data.Length);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		[MonoPInvokeCallback]
		private static void OnLobbyUpdateImpl(IntPtr ptr, long lobbyId)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnLobbyUpdate != null)
			{
				discord.LobbyManagerInstance.OnLobbyUpdate(lobbyId);
			}
		}

		[MonoPInvokeCallback]
		private static void OnLobbyDeleteImpl(IntPtr ptr, long lobbyId, uint reason)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnLobbyDelete != null)
			{
				discord.LobbyManagerInstance.OnLobbyDelete(lobbyId, reason);
			}
		}

		[MonoPInvokeCallback]
		private static void OnMemberConnectImpl(IntPtr ptr, long lobbyId, long userId)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnMemberConnect != null)
			{
				discord.LobbyManagerInstance.OnMemberConnect(lobbyId, userId);
			}
		}

		[MonoPInvokeCallback]
		private static void OnMemberUpdateImpl(IntPtr ptr, long lobbyId, long userId)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnMemberUpdate != null)
			{
				discord.LobbyManagerInstance.OnMemberUpdate(lobbyId, userId);
			}
		}

		[MonoPInvokeCallback]
		private static void OnMemberDisconnectImpl(IntPtr ptr, long lobbyId, long userId)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnMemberDisconnect != null)
			{
				discord.LobbyManagerInstance.OnMemberDisconnect(lobbyId, userId);
			}
		}

		[MonoPInvokeCallback]
		private static void OnLobbyMessageImpl(IntPtr ptr, long lobbyId, long userId, IntPtr dataPtr, int dataLen)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnLobbyMessage != null)
			{
				byte[] array = new byte[dataLen];
				Marshal.Copy(dataPtr, array, 0, dataLen);
				discord.LobbyManagerInstance.OnLobbyMessage(lobbyId, userId, array);
			}
		}

		[MonoPInvokeCallback]
		private static void OnSpeakingImpl(IntPtr ptr, long lobbyId, long userId, bool speaking)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnSpeaking != null)
			{
				discord.LobbyManagerInstance.OnSpeaking(lobbyId, userId, speaking);
			}
		}

		[MonoPInvokeCallback]
		private static void OnNetworkMessageImpl(IntPtr ptr, long lobbyId, long userId, byte channelId, IntPtr dataPtr, int dataLen)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnNetworkMessage != null)
			{
				byte[] array = new byte[dataLen];
				Marshal.Copy(dataPtr, array, 0, dataLen);
				discord.LobbyManagerInstance.OnNetworkMessage(lobbyId, userId, channelId, array);
			}
		}

		public IEnumerable<User> GetMemberUsers(long lobbyID)
		{
			int num = MemberCount(lobbyID);
			List<User> list = new List<User>();
			for (int i = 0; i < num; i++)
			{
				list.Add(GetMemberUser(lobbyID, GetMemberUserId(lobbyID, i)));
			}
			return list;
		}

		public void SendLobbyMessage(long lobbyID, string data, SendLobbyMessageHandler handler)
		{
			SendLobbyMessage(lobbyID, Encoding.UTF8.GetBytes(data), handler);
		}
	}
	public class NetworkManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void MessageHandler(IntPtr ptr, ulong peerId, byte channelId, IntPtr dataPtr, int dataLen);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void RouteUpdateHandler(IntPtr ptr, [MarshalAs(UnmanagedType.LPStr)] string routeData);

			internal MessageHandler OnMessage;

			internal RouteUpdateHandler OnRouteUpdate;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void GetPeerIdMethod(IntPtr methodsPtr, ref ulong peerId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result FlushMethod(IntPtr methodsPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result OpenPeerMethod(IntPtr methodsPtr, ulong peerId, [MarshalAs(UnmanagedType.LPStr)] string routeData);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result UpdatePeerMethod(IntPtr methodsPtr, ulong peerId, [MarshalAs(UnmanagedType.LPStr)] string routeData);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result ClosePeerMethod(IntPtr methodsPtr, ulong peerId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result OpenChannelMethod(IntPtr methodsPtr, ulong peerId, byte channelId, bool reliable);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result CloseChannelMethod(IntPtr methodsPtr, ulong peerId, byte channelId);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result SendMessageMethod(IntPtr methodsPtr, ulong peerId, byte channelId, byte[] data, int dataLen);

			internal GetPeerIdMethod GetPeerId;

			internal FlushMethod Flush;

			internal OpenPeerMethod OpenPeer;

			internal UpdatePeerMethod UpdatePeer;

			internal ClosePeerMethod ClosePeer;

			internal OpenChannelMethod OpenChannel;

			internal CloseChannelMethod CloseChannel;

			internal SendMessageMethod SendMessage;
		}

		public delegate void MessageHandler(ulong peerId, byte channelId, byte[] data);

		public delegate void RouteUpdateHandler(string routeData);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event MessageHandler OnMessage;

		public event RouteUpdateHandler OnRouteUpdate;

		internal NetworkManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnMessage = OnMessageImpl;
			events.OnRouteUpdate = OnRouteUpdateImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public ulong GetPeerId()
		{
			ulong peerId = 0uL;
			Methods.GetPeerId(MethodsPtr, ref peerId);
			return peerId;
		}

		public void Flush()
		{
			Result result = Methods.Flush(MethodsPtr);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void OpenPeer(ulong peerId, string routeData)
		{
			Result result = Methods.OpenPeer(MethodsPtr, peerId, routeData);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void UpdatePeer(ulong peerId, string routeData)
		{
			Result result = Methods.UpdatePeer(MethodsPtr, peerId, routeData);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void ClosePeer(ulong peerId)
		{
			Result result = Methods.ClosePeer(MethodsPtr, peerId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void OpenChannel(ulong peerId, byte channelId, bool reliable)
		{
			Result result = Methods.OpenChannel(MethodsPtr, peerId, channelId, reliable);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void CloseChannel(ulong peerId, byte channelId)
		{
			Result result = Methods.CloseChannel(MethodsPtr, peerId, channelId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void SendMessage(ulong peerId, byte channelId, byte[] data)
		{
			Result result = Methods.SendMessage(MethodsPtr, peerId, channelId, data, data.Length);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		[MonoPInvokeCallback]
		private static void OnMessageImpl(IntPtr ptr, ulong peerId, byte channelId, IntPtr dataPtr, int dataLen)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.NetworkManagerInstance.OnMessage != null)
			{
				byte[] array = new byte[dataLen];
				Marshal.Copy(dataPtr, array, 0, dataLen);
				discord.NetworkManagerInstance.OnMessage(peerId, channelId, array);
			}
		}

		[MonoPInvokeCallback]
		private static void OnRouteUpdateImpl(IntPtr ptr, string routeData)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.NetworkManagerInstance.OnRouteUpdate != null)
			{
				discord.NetworkManagerInstance.OnRouteUpdate(routeData);
			}
		}
	}
	public class OverlayManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ToggleHandler(IntPtr ptr, bool locked);

			internal ToggleHandler OnToggle;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void IsEnabledMethod(IntPtr methodsPtr, ref bool enabled);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void IsLockedMethod(IntPtr methodsPtr, ref bool locked);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SetLockedCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SetLockedMethod(IntPtr methodsPtr, bool locked, IntPtr callbackData, SetLockedCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void OpenActivityInviteCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void OpenActivityInviteMethod(IntPtr methodsPtr, ActivityActionType type, IntPtr callbackData, OpenActivityInviteCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void OpenGuildInviteCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void OpenGuildInviteMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string code, IntPtr callbackData, OpenGuildInviteCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void OpenVoiceSettingsCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void OpenVoiceSettingsMethod(IntPtr methodsPtr, IntPtr callbackData, OpenVoiceSettingsCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result InitDrawingDxgiMethod(IntPtr methodsPtr, IntPtr swapchain, bool useMessageForwarding);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void OnPresentMethod(IntPtr methodsPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ForwardMessageMethod(IntPtr methodsPtr, IntPtr message);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void KeyEventMethod(IntPtr methodsPtr, bool down, [MarshalAs(UnmanagedType.LPStr)] string keyCode, KeyVariant variant);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void CharEventMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string character);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void MouseButtonEventMethod(IntPtr methodsPtr, byte down, int clickCount, MouseButton which, int x, int y);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void MouseMotionEventMethod(IntPtr methodsPtr, int x, int y);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ImeCommitTextMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string text);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ImeSetCompositionMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string text, ref ImeUnderline underlines, int from, int to);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void ImeCancelCompositionMethod(IntPtr methodsPtr);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SetImeCompositionRangeCallbackCallback(IntPtr ptr, int from, int to, ref Rect bounds);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SetImeCompositionRangeCallbackMethod(IntPtr methodsPtr, IntPtr callbackData, SetImeCompositionRangeCallbackCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SetImeSelectionBoundsCallbackCallback(IntPtr ptr, Rect anchor, Rect focus, bool isAnchorFirst);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate void SetImeSelectionBoundsCallbackMethod(IntPtr methodsPtr, IntPtr callbackData, SetImeSelectionBoundsCallbackCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate bool IsPointInsideClickZoneMethod(IntPtr methodsPtr, int x, int y);

			internal IsEnabledMethod IsEnabled;

			internal IsLockedMethod IsLocked;

			internal SetLockedMethod SetLocked;

			internal OpenActivityInviteMethod OpenActivityInvite;

			internal OpenGuildInviteMethod OpenGuildInvite;

			internal OpenVoiceSettingsMethod OpenVoiceSettings;

			internal InitDrawingDxgiMethod InitDrawingDxgi;

			internal OnPresentMethod OnPresent;

			internal ForwardMessageMethod ForwardMessage;

			internal KeyEventMethod KeyEvent;

			internal CharEventMethod CharEvent;

			internal MouseButtonEventMethod MouseButtonEvent;

			internal MouseMotionEventMethod MouseMotionEvent;

			internal ImeCommitTextMethod ImeCommitText;

			internal ImeSetCompositionMethod ImeSetComposition;

			internal ImeCancelCompositionMethod ImeCancelComposition;

			internal SetImeCompositionRangeCallbackMethod SetImeCompositionRangeCallback;

			internal SetImeSelectionBoundsCallbackMethod SetImeSelectionBoundsCallback;

			internal IsPointInsideClickZoneMethod IsPointInsideClickZone;
		}

		public delegate void SetLockedHandler(Result result);

		public delegate void OpenActivityInviteHandler(Result result);

		public delegate void OpenGuildInviteHandler(Result result);

		public delegate void OpenVoiceSettingsHandler(Result result);

		public delegate void SetImeCompositionRangeCallbackHandler(int from, int to, ref Rect bounds);

		public delegate void SetImeSelectionBoundsCallbackHandler(Rect anchor, Rect focus, bool isAnchorFirst);

		public delegate void ToggleHandler(bool locked);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event ToggleHandler OnToggle;

		internal OverlayManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnToggle = OnToggleImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public bool IsEnabled()
		{
			bool enabled = false;
			Methods.IsEnabled(MethodsPtr, ref enabled);
			return enabled;
		}

		public bool IsLocked()
		{
			bool locked = false;
			Methods.IsLocked(MethodsPtr, ref locked);
			return locked;
		}

		[MonoPInvokeCallback]
		private static void SetLockedCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SetLockedHandler setLockedHandler = (SetLockedHandler)gCHandle.Target;
			gCHandle.Free();
			setLockedHandler(result);
		}

		public void SetLocked(bool locked, SetLockedHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.SetLocked(MethodsPtr, locked, GCHandle.ToIntPtr(value), SetLockedCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void OpenActivityInviteCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			OpenActivityInviteHandler openActivityInviteHandler = (OpenActivityInviteHandler)gCHandle.Target;
			gCHandle.Free();
			openActivityInviteHandler(result);
		}

		public void OpenActivityInvite(ActivityActionType type, OpenActivityInviteHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.OpenActivityInvite(MethodsPtr, type, GCHandle.ToIntPtr(value), OpenActivityInviteCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void OpenGuildInviteCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			OpenGuildInviteHandler openGuildInviteHandler = (OpenGuildInviteHandler)gCHandle.Target;
			gCHandle.Free();
			openGuildInviteHandler(result);
		}

		public void OpenGuildInvite(string code, OpenGuildInviteHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.OpenGuildInvite(MethodsPtr, code, GCHandle.ToIntPtr(value), OpenGuildInviteCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void OpenVoiceSettingsCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			OpenVoiceSettingsHandler openVoiceSettingsHandler = (OpenVoiceSettingsHandler)gCHandle.Target;
			gCHandle.Free();
			openVoiceSettingsHandler(result);
		}

		public void OpenVoiceSettings(OpenVoiceSettingsHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.OpenVoiceSettings(MethodsPtr, GCHandle.ToIntPtr(value), OpenVoiceSettingsCallbackImpl);
		}

		public void InitDrawingDxgi(IntPtr swapchain, bool useMessageForwarding)
		{
			Result result = Methods.InitDrawingDxgi(MethodsPtr, swapchain, useMessageForwarding);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void OnPresent()
		{
			Methods.OnPresent(MethodsPtr);
		}

		public void ForwardMessage(IntPtr message)
		{
			Methods.ForwardMessage(MethodsPtr, message);
		}

		public void KeyEvent(bool down, string keyCode, KeyVariant variant)
		{
			Methods.KeyEvent(MethodsPtr, down, keyCode, variant);
		}

		public void CharEvent(string character)
		{
			Methods.CharEvent(MethodsPtr, character);
		}

		public void MouseButtonEvent(byte down, int clickCount, MouseButton which, int x, int y)
		{
			Methods.MouseButtonEvent(MethodsPtr, down, clickCount, which, x, y);
		}

		public void MouseMotionEvent(int x, int y)
		{
			Methods.MouseMotionEvent(MethodsPtr, x, y);
		}

		public void ImeCommitText(string text)
		{
			Methods.ImeCommitText(MethodsPtr, text);
		}

		public void ImeSetComposition(string text, ImeUnderline underlines, int from, int to)
		{
			Methods.ImeSetComposition(MethodsPtr, text, ref underlines, from, to);
		}

		public void ImeCancelComposition()
		{
			Methods.ImeCancelComposition(MethodsPtr);
		}

		[MonoPInvokeCallback]
		private static void SetImeCompositionRangeCallbackCallbackImpl(IntPtr ptr, int from, int to, ref Rect bounds)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SetImeCompositionRangeCallbackHandler setImeCompositionRangeCallbackHandler = (SetImeCompositionRangeCallbackHandler)gCHandle.Target;
			gCHandle.Free();
			setImeCompositionRangeCallbackHandler(from, to, ref bounds);
		}

		public void SetImeCompositionRangeCallback(SetImeCompositionRangeCallbackHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.SetImeCompositionRangeCallback(MethodsPtr, GCHandle.ToIntPtr(value), SetImeCompositionRangeCallbackCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void SetImeSelectionBoundsCallbackCallbackImpl(IntPtr ptr, Rect anchor, Rect focus, bool isAnchorFirst)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SetImeSelectionBoundsCallbackHandler setImeSelectionBoundsCallbackHandler = (SetImeSelectionBoundsCallbackHandler)gCHandle.Target;
			gCHandle.Free();
			setImeSelectionBoundsCallbackHandler(anchor, focus, isAnchorFirst);
		}

		public void SetImeSelectionBoundsCallback(SetImeSelectionBoundsCallbackHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.SetImeSelectionBoundsCallback(MethodsPtr, GCHandle.ToIntPtr(value), SetImeSelectionBoundsCallbackCallbackImpl);
		}

		public bool IsPointInsideClickZone(int x, int y)
		{
			return Methods.IsPointInsideClickZone(MethodsPtr, x, y);
		}

		[MonoPInvokeCallback]
		private static void OnToggleImpl(IntPtr ptr, bool locked)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.OverlayManagerInstance.OnToggle != null)
			{
				discord.OverlayManagerInstance.OnToggle(locked);
			}
		}
	}
	public class StorageManager
	{
		internal struct FFIEvents
		{
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Winapi)]
			internal delegate Result ReadMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string nam

BooBoo Building/BepInEx/plugins/itsmeowdev-DoorFix/DoorFix.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using DunGen;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("DoorFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Fixes the hitbox of doors so items can be picked up through open doors more easily.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DoorFix")]
[assembly: AssemblyTitle("DoorFix")]
[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 DoorFix
{
	[BepInPlugin("DoorFix", "DoorFix", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(DungeonUtil))]
		[HarmonyPatch("AddAndSetupDoorComponent")]
		public class DungeonUtilPatch
		{
			private static void Postfix(Dungeon dungeon, GameObject doorPrefab, Doorway doorway)
			{
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_003a: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b1: Expected O, but got Unknown
				//IL_0118: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)doorPrefab).name.StartsWith("SteelDoorMapSpawn"))
				{
					return;
				}
				foreach (Transform item in doorPrefab.GetComponent<SpawnSyncedObject>().spawnPrefab.transform)
				{
					Transform val = item;
					if (!((Object)val).name.StartsWith("SteelDoor"))
					{
						continue;
					}
					foreach (Transform item2 in ((Component)val).transform)
					{
						Transform val2 = item2;
						if (!((Object)val2).name.StartsWith("DoorMesh"))
						{
							continue;
						}
						LOGGER.LogInfo((object)((object)val2).ToString());
						foreach (Transform item3 in ((Component)val2).transform)
						{
							Transform val3 = item3;
							if (((Component)val3).tag != "InteractTrigger")
							{
								continue;
							}
							LOGGER.LogInfo((object)((object)val3).ToString());
							BoxCollider[] components = ((Component)val3).gameObject.GetComponents<BoxCollider>();
							foreach (BoxCollider val4 in components)
							{
								if (((Collider)val4).isTrigger)
								{
									LOGGER.LogDebug((object)"Patching door size");
									val4.size = new Vector3(0.64f, 1f, 1f);
								}
							}
						}
					}
				}
			}
		}

		private static readonly ManualLogSource LOGGER = Logger.CreateLogSource("DoorFix");

		private void Awake()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			new Harmony("DoorFix").PatchAll();
			LOGGER.LogInfo((object)"Plugin DoorFix is loaded!");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "DoorFix";

		public const string PLUGIN_NAME = "DoorFix";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

BooBoo Building/BepInEx/plugins/LethalPlugging-LethalHaptics/LethalVibrations.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Buttplug.Client;
using Buttplug.Client.Connectors.WebsocketConnector;
using Buttplug.Core;
using Costura;
using GameNetcodeStuff;
using HarmonyLib;
using LethalVibrations.Buttplug;
using LethalVibrations.Patches;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7", FrameworkDisplayName = ".NET Framework 4.7")]
[assembly: AssemblyCompany("LethalVibrations")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Lethal Company mod that makes your sex toys vibrate.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LethalVibrations")]
[assembly: AssemblyTitle("LethalVibrations")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
internal class <Module>
{
	static <Module>()
	{
		AssemblyLoader.Attach();
	}
}
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 LethalVibrations
{
	[BepInPlugin("LethalVibrations", "LethalVibrations", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		internal static DeviceManager DeviceManager { get; private set; }

		private void Awake()
		{
			//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_007b: 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_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			DeviceManager = new DeviceManager(((BaseUnityPlugin)this).Logger, "LethalVibrations");
			DeviceManager.ConnectDevices();
			PlayerControllerBPatches.Init(((BaseUnityPlugin)this).Logger);
			ItemChargerPatches.Init(((BaseUnityPlugin)this).Logger);
			WalkieTalkiePatches.Init(((BaseUnityPlugin)this).Logger);
			EnemyAIPatches.Init(((BaseUnityPlugin)this).Logger);
			HUDManagerPatches.Init(((BaseUnityPlugin)this).Logger);
			GrabbableObjectPatches.Init(((BaseUnityPlugin)this).Logger);
			Harmony val = new Harmony("LethalVibrations");
			val.PatchAll(typeof(PlayerControllerBPatches));
			val.PatchAll(typeof(ItemChargerPatches));
			val.PatchAll(typeof(WalkieTalkiePatches));
			val.PatchAll(typeof(EnemyAIPatches));
			val.PatchAll(typeof(HUDManagerPatches));
			val.PatchAll(typeof(GrabbableObjectPatches));
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LethalVibrations (1.0.0) is loaded!");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LethalVibrations";

		public const string PLUGIN_NAME = "LethalVibrations";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace LethalVibrations.Patches
{
	internal class EnemyAIPatches
	{
		private static ManualLogSource Logger { get; set; }

		public static void Init(ManualLogSource logger)
		{
			Logger = logger;
		}

		[HarmonyPatch(typeof(EnemyAI), "HitEnemy")]
		[HarmonyPostfix]
		private static void HitEnemyPatch(int force, PlayerControllerB playerWhoHit)
		{
			if (playerWhoHit.playerClientId == GameNetworkManager.Instance.localPlayerController.playerClientId)
			{
				Logger.LogInfo((object)"HitEnemy got called");
				if (Plugin.DeviceManager.IsConnected() && Config.VibrateDamageDealtEnabled.Value)
				{
					Plugin.DeviceManager.VibrateConnectedDevices(0.5f + Config.VibrateDamageDealtAmplifier.Value, Config.VibrateDamageDealtDuration.Value);
				}
			}
		}
	}
	internal class GrabbableObjectPatches
	{
		private static ManualLogSource Logger { get; set; }

		public static void Init(ManualLogSource logger)
		{
			Logger = logger;
		}

		[HarmonyPatch(typeof(GrabbableObject), "GrabItemOnClient")]
		[HarmonyPostfix]
		private static void GrabItemOnClientPatch(GrabbableObject __instance)
		{
			if (__instance.itemProperties.isScrap)
			{
				Logger.LogInfo((object)"GrabItemOnClient called");
				if (Plugin.DeviceManager.IsConnected() && Config.GoodboyMode.Value)
				{
					Plugin.DeviceManager.VibrateConnectedDevices(0.2f + Config.VibrateKilledAmplifier.Value, Config.VibrateKilledDuration.Value);
				}
			}
		}
	}
	internal class HUDManagerPatches
	{
		private static ManualLogSource Logger { get; set; }

		public static void Init(ManualLogSource logger)
		{
			Logger = logger;
		}

		[HarmonyPatch(typeof(HUDManager), "ShakeCamera")]
		[HarmonyPostfix]
		private static void ShakeCameraPatch(ScreenShakeType shakeType)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected I4, but got Unknown
			Logger.LogInfo((object)$"ShakeCamera {shakeType} got called");
			if (Plugin.DeviceManager.IsConnected() && Config.VibrateShakeScreenEnabled.Value)
			{
				switch ((int)shakeType)
				{
				case 0:
					Plugin.DeviceManager.VibrateConnectedDevices(0.3f + Config.VibrateShakeScreenAmplifier.Value, Config.VibrateShakeScreenDuration.Value);
					break;
				case 1:
					Plugin.DeviceManager.VibrateConnectedDevices(0.6f + Config.VibrateShakeScreenAmplifier.Value, Config.VibrateShakeScreenDuration.Value);
					break;
				case 2:
					Plugin.DeviceManager.VibrateConnectedDevices(0.5f + Config.VibrateShakeScreenAmplifier.Value, Config.VibrateShakeScreenDuration.Value + 0.6f);
					break;
				case 3:
					Plugin.DeviceManager.VibrateConnectedDevices(0.9f + Config.VibrateShakeScreenAmplifier.Value, Config.VibrateShakeScreenDuration.Value + 0.3f);
					break;
				}
			}
		}

		[HarmonyPatch(typeof(HUDManager), "PingScan_performed")]
		[HarmonyPostfix]
		private static void PingScan_performedPatch()
		{
			Logger.LogInfo((object)"PingScan_performed got called");
			if (Plugin.DeviceManager.IsConnected() && Config.VibrateShakeScreenEnabled.Value)
			{
				Plugin.DeviceManager.VibrateConnectedDevices(0.3f + Config.PingScanAmplifier.Value, Config.PingScanDuration.Value);
			}
		}
	}
	internal class ItemChargerPatches
	{
		internal static ManualLogSource Logger { get; set; }

		public static void Init(ManualLogSource logger)
		{
			Logger = logger;
		}

		[HarmonyPatch(typeof(ItemCharger), "ChargeItem")]
		[HarmonyPostfix]
		private static void ChargeItemPatch()
		{
			Logger.LogInfo((object)"ChargeItem got called");
			if (Plugin.DeviceManager.IsConnected() && Config.VibrateItemChargerChargeEnabled.Value)
			{
				Plugin.DeviceManager.VibrateConnectedDevices(0.8f + Config.VibrateItemChargerChargeAmplifier.Value, Config.VibrateItemChargerChargeDuration.Value);
			}
		}
	}
	internal class PlayerControllerBPatches
	{
		private static ManualLogSource Logger { get; set; }

		public static void Init(ManualLogSource logger)
		{
			Logger = logger;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "DamagePlayer")]
		[HarmonyPostfix]
		private static void DamagePlayerPatch(PlayerControllerB __instance, int damageNumber)
		{
			if (__instance.playerClientId == GameNetworkManager.Instance.localPlayerController.playerClientId)
			{
				float num = damageNumber;
				Logger.LogInfo((object)$"DamagePlayer got called: {num} ({num / 100f})");
				if (Plugin.DeviceManager.IsConnected() && Config.VibrateDamageReceivedEnabled.Value)
				{
					Plugin.DeviceManager.VibrateConnectedDevices(num / 100f + Config.VibrateDamageReceivedAmplifier.Value, Config.VibrateDamageReceivedDuration.Value);
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
		[HarmonyPostfix]
		private static void KillPlayerPatch(PlayerControllerB __instance)
		{
			if (__instance.playerClientId == GameNetworkManager.Instance.localPlayerController.playerClientId)
			{
				Logger.LogInfo((object)"KillPlayer got called");
				if (Plugin.DeviceManager.IsConnected() && Config.VibrateKilledEnabled.Value)
				{
					Plugin.DeviceManager.VibrateConnectedDevices(0.9f + Config.VibrateKilledAmplifier.Value, Config.VibrateKilledDuration.Value);
				}
			}
		}
	}
	internal class WalkieTalkiePatches
	{
		internal static ManualLogSource Logger { get; set; }

		public static void Init(ManualLogSource logger)
		{
			Logger = logger;
		}

		[HarmonyPatch(typeof(WalkieTalkie), "SendWalkieTalkieStartTransmissionSFX")]
		[HarmonyPostfix]
		private static void SendWalkieTalkieStartTransmissionSFXPatch(int playerId)
		{
			if (playerId != (int)GameNetworkManager.Instance.localPlayerController.playerClientId)
			{
				Logger.LogInfo((object)"SendWalkieTalkieStartTransmissionSFX got called");
				if (Plugin.DeviceManager.IsConnected() && Config.VibrateWalkieTalkieReceivedEnabled.Value)
				{
					Plugin.DeviceManager.VibrateConnectedDevices(0.6f + Config.VibrateWalkieTalkieReceivedAmplifier.Value, Config.VibrateWalkieTalkieReceivedDuration.Value);
				}
			}
		}
	}
}
namespace LethalVibrations.Buttplug
{
	internal class Config
	{
		private static ConfigFile ConfigFile { get; set; }

		internal static ConfigEntry<string> ServerUri { get; set; }

		internal static ConfigEntry<float> VibrateAmplifier { get; set; }

		internal static ConfigEntry<bool> GoodboyMode { get; set; }

		internal static ConfigEntry<bool> VibrateDamageReceivedEnabled { get; set; }

		internal static ConfigEntry<float> VibrateDamageReceivedDuration { get; set; }

		internal static ConfigEntry<float> VibrateDamageReceivedAmplifier { get; set; }

		internal static ConfigEntry<bool> VibrateDamageDealtEnabled { get; set; }

		internal static ConfigEntry<float> VibrateDamageDealtDuration { get; set; }

		internal static ConfigEntry<float> VibrateDamageDealtAmplifier { get; set; }

		internal static ConfigEntry<bool> VibrateKilledEnabled { get; set; }

		internal static ConfigEntry<float> VibrateKilledDuration { get; set; }

		internal static ConfigEntry<float> VibrateKilledAmplifier { get; set; }

		internal static ConfigEntry<bool> VibrateItemChargerChargeEnabled { get; set; }

		internal static ConfigEntry<float> VibrateItemChargerChargeDuration { get; set; }

		internal static ConfigEntry<float> VibrateItemChargerChargeAmplifier { get; set; }

		internal static ConfigEntry<bool> VibrateWalkieTalkieReceivedEnabled { get; set; }

		internal static ConfigEntry<float> VibrateWalkieTalkieReceivedDuration { get; set; }

		internal static ConfigEntry<float> VibrateWalkieTalkieReceivedAmplifier { get; set; }

		internal static ConfigEntry<bool> VibrateShakeScreenEnabled { get; set; }

		internal static ConfigEntry<float> VibrateShakeScreenDuration { get; set; }

		internal static ConfigEntry<float> VibrateShakeScreenAmplifier { get; set; }

		internal static ConfigEntry<bool> PingScanEnabled { get; set; }

		internal static ConfigEntry<float> PingScanDuration { get; set; }

		internal static ConfigEntry<float> PingScanAmplifier { get; set; }

		static Config()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			ConfigFile = new ConfigFile(Paths.ConfigPath + "\\LethalVibrations.cfg", true);
			ServerUri = ConfigFile.Bind<string>("Devices", "Server Uri", "ws://localhost:12345", "URI of the Intiface server.");
			VibrateAmplifier = ConfigFile.Bind<float>("Vibrations", "Amplifier", 0f, "Change the amplification of vibration");
			GoodboyMode = ConfigFile.Bind<bool>("Vibrations", "GoodBoyMode", false, "Enabled rewarding");
			VibrateDamageReceivedEnabled = ConfigFile.Bind<bool>("Vibrations.DamageReceived", "Enabled", true, "Vibrate when you receive damage");
			VibrateDamageReceivedDuration = ConfigFile.Bind<float>("Vibrations.DamageReceived", "Duration", 1f, "Length of time to vibrate for");
			VibrateDamageReceivedAmplifier = ConfigFile.Bind<float>("Vibrations.DamageReceived", "Amplifier", 0f, "Change the amplification of vibration");
			VibrateDamageDealtEnabled = ConfigFile.Bind<bool>("Vibrations.DamageDealt", "Enabled", true, "Vibrate when you deal damage");
			VibrateDamageDealtDuration = ConfigFile.Bind<float>("Vibrations.DamageDealt", "Duration", 1f, "Length of time to vibrate for");
			VibrateDamageDealtAmplifier = ConfigFile.Bind<float>("Vibrations.DamageDealt", "Amplifier", 0f, "Change the amplification of vibration");
			VibrateKilledEnabled = ConfigFile.Bind<bool>("Vibrations.PlayerKilled", "Enabled", true, "Vibrate when you die");
			VibrateKilledDuration = ConfigFile.Bind<float>("Vibrations.PlayerKilled", "Duration", 1f, "Length of time to vibrate for");
			VibrateKilledAmplifier = ConfigFile.Bind<float>("Vibrations.PlayerKilled", "Amplifier", 0f, "Change the amplification of vibration");
			VibrateItemChargerChargeEnabled = ConfigFile.Bind<bool>("Vibrations.ItemCharge", "Enabled", true, "Vibrate when you charge an item");
			VibrateItemChargerChargeDuration = ConfigFile.Bind<float>("Vibrations.ItemCharge", "Duration", 1f, "Length of time to vibrate for");
			VibrateItemChargerChargeAmplifier = ConfigFile.Bind<float>("Vibrations.ItemCharge", "Amplifier", 0f, "Change the amplification of vibration");
			VibrateWalkieTalkieReceivedEnabled = ConfigFile.Bind<bool>("Vibrations.WalkieTalkieReceived", "Enabled", false, "Vibrate when you receive audio from the WalkieTalkie");
			VibrateWalkieTalkieReceivedDuration = ConfigFile.Bind<float>("Vibrations.WalkieTalkieReceived", "Duration", 1f, "Length of time to vibrate for");
			VibrateWalkieTalkieReceivedAmplifier = ConfigFile.Bind<float>("Vibrations.WalkieTalkieReceived", "Amplifier", 0f, "Change the amplification of vibration");
			VibrateShakeScreenEnabled = ConfigFile.Bind<bool>("Vibrations.ShakeScreen", "Enabled", true, "Vibrate when your screen shakes");
			VibrateShakeScreenDuration = ConfigFile.Bind<float>("Vibrations.ShakeScreen", "Duration", 1f, "Length of time to vibrate for");
			VibrateShakeScreenAmplifier = ConfigFile.Bind<float>("Vibrations.ShakeScreen", "Amplifier", 0f, "Change the amplification of vibration");
			PingScanEnabled = ConfigFile.Bind<bool>("Vibrations.PingScan", "Enabled", true, "Vibrate when you press right click");
			PingScanDuration = ConfigFile.Bind<float>("Vibrations.PingScan", "Duration", 0.3f, "Length of time to vibrate for");
			PingScanAmplifier = ConfigFile.Bind<float>("Vibrations.PingScan", "Amplifier", 0f, "Change the amplification of vibration");
		}
	}
	public class DeviceManager
	{
		private static ManualLogSource Log { get; set; }

		private List<ButtplugClientDevice> ConnectedDevices { get; set; }

		private ButtplugClient ButtplugClient { get; set; }

		public DeviceManager(ManualLogSource logger, string clientName)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			Log = logger;
			ConnectedDevices = new List<ButtplugClientDevice>();
			ButtplugClient = new ButtplugClient(clientName);
			Log.LogInfo((object)("BP client created for " + clientName));
			ButtplugClient.DeviceAdded += HandleDeviceAdded;
			ButtplugClient.DeviceRemoved += HandleDeviceRemoved;
		}

		public bool IsConnected()
		{
			return ButtplugClient.Connected;
		}

		public async void ConnectDevices()
		{
			if (ButtplugClient.Connected)
			{
				return;
			}
			try
			{
				Log.LogInfo((object)("Attempting to connect to Intiface server at " + Config.ServerUri.Value));
				await ButtplugClient.ConnectAsync((IButtplugClientConnector)new ButtplugWebsocketConnector(new Uri(Config.ServerUri.Value)), default(CancellationToken));
				Log.LogInfo((object)"Connection successful. Beginning scan for devices");
				await ButtplugClient.StartScanningAsync(default(CancellationToken));
			}
			catch (ButtplugException val)
			{
				ButtplugException arg = val;
				Log.LogError((object)"Attempt to connect to devices failed. Ensure Intiface is running and attempt to reconnect from the 'Devices' section in the mod's in-game settings.");
				Log.LogDebug((object)$"ButtplugIO error occured while connecting devices: {arg}");
			}
		}

		public void VibrateConnectedDevices(double intensity, float time)
		{
			intensity += Config.VibrateAmplifier.Value;
			ConnectedDevices.ForEach(Action);
			async void Action(ButtplugClientDevice device)
			{
				await device.VibrateAsync((double)Mathf.Clamp((float)intensity, 0f, 1f));
				await Task.Delay((int)(time * 1000f));
				await device.VibrateAsync(0.0);
			}
		}

		public void StopConnectedDevices()
		{
			ConnectedDevices.ForEach(async delegate(ButtplugClientDevice device)
			{
				await device.Stop();
			});
		}

		internal void CleanUp()
		{
			StopConnectedDevices();
		}

		private void HandleDeviceAdded(object sender, DeviceAddedEventArgs args)
		{
			if (!IsVibratableDevice(args.Device))
			{
				Log.LogInfo((object)(args.Device.Name + " was detected but ignored due to it not being vibratable."));
				return;
			}
			Log.LogInfo((object)(args.Device.Name + " connected to client " + ButtplugClient.Name));
			ConnectedDevices.Add(args.Device);
		}

		private void HandleDeviceRemoved(object sender, DeviceRemovedEventArgs args)
		{
			if (IsVibratableDevice(args.Device))
			{
				Log.LogInfo((object)(args.Device.Name + " disconnected from client " + ButtplugClient.Name));
				ConnectedDevices.Remove(args.Device);
			}
		}

		private bool IsVibratableDevice(ButtplugClientDevice device)
		{
			return device.VibrateAttributes.Count > 0;
		}
	}
}
namespace Costura
{
	[CompilerGenerated]
	internal static class AssemblyLoader
	{
		private static object nullCacheLock = new object();

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

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

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

		private static int isAttached;

		private static string CultureToString(CultureInfo culture)
		{
			if (culture == null)
			{
				return "";
			}
			return culture.Name;
		}

		private static Assembly ReadExistingAssembly(AssemblyName name)
		{
			AppDomain currentDomain = AppDomain.CurrentDomain;
			Assembly[] assemblies = currentDomain.GetAssemblies();
			Assembly[] array = assemblies;
			foreach (Assembly assembly in array)
			{
				AssemblyName name2 = assembly.GetName();
				if (string.Equals(name2.Name, name.Name, StringComparison.InvariantCultureIgnoreCase) && string.Equals(CultureToString(name2.CultureInfo), CultureToString(name.CultureInfo), StringComparison.InvariantCultureIgnoreCase))
				{
					return assembly;
				}
			}
			return null;
		}

		private static void CopyTo(Stream source, Stream destination)
		{
			byte[] array = new byte[81920];
			int count;
			while ((count = source.Read(array, 0, array.Length)) != 0)
			{
				destination.Write(array, 0, count);
			}
		}

		private static Stream LoadStream(string fullName)
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			if (fullName.EndsWith(".compressed"))
			{
				using (Stream stream = executingAssembly.GetManifestResourceStream(fullName))
				{
					using DeflateStream source = new DeflateStream(stream, CompressionMode.Decompress);
					MemoryStream memoryStream = new MemoryStream();
					CopyTo(source, memoryStream);
					memoryStream.Position = 0L;
					return memoryStream;
				}
			}
			return executingAssembly.GetManifestResourceStream(fullName);
		}

		private static Stream LoadStream(Dictionary<string, string> resourceNames, string name)
		{
			if (resourceNames.TryGetValue(name, out var value))
			{
				return LoadStream(value);
			}
			return null;
		}

		private static byte[] ReadStream(Stream stream)
		{
			byte[] array = new byte[stream.Length];
			stream.Read(array, 0, array.Length);
			return array;
		}

		private static Assembly ReadFromEmbeddedResources(Dictionary<string, string> assemblyNames, Dictionary<string, string> symbolNames, AssemblyName requestedAssemblyName)
		{
			string text = requestedAssemblyName.Name.ToLowerInvariant();
			if (requestedAssemblyName.CultureInfo != null && !string.IsNullOrEmpty(requestedAssemblyName.CultureInfo.Name))
			{
				text = requestedAssemblyName.CultureInfo.Name + "." + text;
			}
			byte[] rawAssembly;
			using (Stream stream = LoadStream(assemblyNames, text))
			{
				if (stream == null)
				{
					return null;
				}
				rawAssembly = ReadStream(stream);
			}
			using (Stream stream2 = LoadStream(symbolNames, text))
			{
				if (stream2 != null)
				{
					byte[] rawSymbolStore = ReadStream(stream2);
					return Assembly.Load(rawAssembly, rawSymbolStore);
				}
			}
			return Assembly.Load(rawAssembly);
		}

		public static Assembly ResolveAssembly(object sender, ResolveEventArgs e)
		{
			lock (nullCacheLock)
			{
				if (nullCache.ContainsKey(e.Name))
				{
					return null;
				}
			}
			AssemblyName assemblyName = new AssemblyName(e.Name);
			Assembly assembly = ReadExistingAssembly(assemblyName);
			if ((object)assembly != null)
			{
				return assembly;
			}
			assembly = ReadFromEmbeddedResources(assemblyNames, symbolNames, assemblyName);
			if ((object)assembly == null)
			{
				lock (nullCacheLock)
				{
					nullCache[e.Name] = true;
				}
				if ((assemblyName.Flags & AssemblyNameFlags.Retargetable) != 0)
				{
					assembly = Assembly.Load(assemblyName);
				}
			}
			return assembly;
		}

		static AssemblyLoader()
		{
			assemblyNames.Add("buttplug.client.connectors.websocketconnector", "costura.buttplug.client.connectors.websocketconnector.dll.compressed");
			assemblyNames.Add("buttplug", "costura.buttplug.dll.compressed");
			assemblyNames.Add("deniszykov.websocketlistener", "costura.deniszykov.websocketlistener.dll.compressed");
			assemblyNames.Add("system.appcontext", "costura.system.appcontext.dll.compressed");
			assemblyNames.Add("system.collections.concurrent", "costura.system.collections.concurrent.dll.compressed");
			assemblyNames.Add("system.collections", "costura.system.collections.dll.compressed");
			assemblyNames.Add("system.collections.nongeneric", "costura.system.collections.nongeneric.dll.compressed");
			assemblyNames.Add("system.collections.specialized", "costura.system.collections.specialized.dll.compressed");
			assemblyNames.Add("system.componentmodel.annotations", "costura.system.componentmodel.annotations.dll.compressed");
			assemblyNames.Add("system.componentmodel.composition", "costura.system.componentmodel.composition.dll.compressed");
			assemblyNames.Add("system.componentmodel", "costura.system.componentmodel.dll.compressed");
			assemblyNames.Add("system.componentmodel.eventbasedasync", "costura.system.componentmodel.eventbasedasync.dll.compressed");
			assemblyNames.Add("system.componentmodel.primitives", "costura.system.componentmodel.primitives.dll.compressed");
			assemblyNames.Add("system.componentmodel.typeconverter", "costura.system.componentmodel.typeconverter.dll.compressed");
			assemblyNames.Add("system.console", "costura.system.console.dll.compressed");
			assemblyNames.Add("system.core", "costura.system.core.dll.compressed");
			assemblyNames.Add("system.data.common", "costura.system.data.common.dll.compressed");
			assemblyNames.Add("system.data", "costura.system.data.dll.compressed");
			assemblyNames.Add("system.diagnostics.contracts", "costura.system.diagnostics.contracts.dll.compressed");
			assemblyNames.Add("system.diagnostics.debug", "costura.system.diagnostics.debug.dll.compressed");
			assemblyNames.Add("system.diagnostics.diagnosticsource", "costura.system.diagnostics.diagnosticsource.dll.compressed");
			assemblyNames.Add("system.diagnostics.fileversioninfo", "costura.system.diagnostics.fileversioninfo.dll.compressed");
			assemblyNames.Add("system.diagnostics.process", "costura.system.diagnostics.process.dll.compressed");
			assemblyNames.Add("system.diagnostics.stacktrace", "costura.system.diagnostics.stacktrace.dll.compressed");
			assemblyNames.Add("system.diagnostics.textwritertracelistener", "costura.system.diagnostics.textwritertracelistener.dll.compressed");
			assemblyNames.Add("system.diagnostics.tools", "costura.system.diagnostics.tools.dll.compressed");
			assemblyNames.Add("system.diagnostics.tracesource", "costura.system.diagnostics.tracesource.dll.compressed");
			assemblyNames.Add("system.diagnostics.tracing", "costura.system.diagnostics.tracing.dll.compressed");
			assemblyNames.Add("system.drawing", "costura.system.drawing.dll.compressed");
			assemblyNames.Add("system.drawing.primitives", "costura.system.drawing.primitives.dll.compressed");
			assemblyNames.Add("system.dynamic.runtime", "costura.system.dynamic.runtime.dll.compressed");
			assemblyNames.Add("system.globalization.calendars", "costura.system.globalization.calendars.dll.compressed");
			assemblyNames.Add("system.globalization", "costura.system.globalization.dll.compressed");
			assemblyNames.Add("system.globalization.extensions", "costura.system.globalization.extensions.dll.compressed");
			assemblyNames.Add("system.io.compression", "costura.system.io.compression.dll.compressed");
			assemblyNames.Add("system.io.compression.filesystem", "costura.system.io.compression.filesystem.dll.compressed");
			assemblyNames.Add("system.io.compression.zipfile", "costura.system.io.compression.zipfile.dll.compressed");
			assemblyNames.Add("system.io", "costura.system.io.dll.compressed");
			assemblyNames.Add("system.io.filesystem", "costura.system.io.filesystem.dll.compressed");
			assemblyNames.Add("system.io.filesystem.driveinfo", "costura.system.io.filesystem.driveinfo.dll.compressed");
			assemblyNames.Add("system.io.filesystem.primitives", "costura.system.io.filesystem.primitives.dll.compressed");
			assemblyNames.Add("system.io.filesystem.watcher", "costura.system.io.filesystem.watcher.dll.compressed");
			assemblyNames.Add("system.io.isolatedstorage", "costura.system.io.isolatedstorage.dll.compressed");
			assemblyNames.Add("system.io.memorymappedfiles", "costura.system.io.memorymappedfiles.dll.compressed");
			assemblyNames.Add("system.io.pipes", "costura.system.io.pipes.dll.compressed");
			assemblyNames.Add("system.io.unmanagedmemorystream", "costura.system.io.unmanagedmemorystream.dll.compressed");
			assemblyNames.Add("system.linq", "costura.system.linq.dll.compressed");
			assemblyNames.Add("system.linq.expressions", "costura.system.linq.expressions.dll.compressed");
			assemblyNames.Add("system.linq.parallel", "costura.system.linq.parallel.dll.compressed");
			assemblyNames.Add("system.linq.queryable", "costura.system.linq.queryable.dll.compressed");
			assemblyNames.Add("system.net.http", "costura.system.net.http.dll.compressed");
			assemblyNames.Add("system.net.nameresolution", "costura.system.net.nameresolution.dll.compressed");
			assemblyNames.Add("system.net.networkinformation", "costura.system.net.networkinformation.dll.compressed");
			assemblyNames.Add("system.net.ping", "costura.system.net.ping.dll.compressed");
			assemblyNames.Add("system.net.primitives", "costura.system.net.primitives.dll.compressed");
			assemblyNames.Add("system.net.requests", "costura.system.net.requests.dll.compressed");
			assemblyNames.Add("system.net.security", "costura.system.net.security.dll.compressed");
			assemblyNames.Add("system.net.sockets", "costura.system.net.sockets.dll.compressed");
			assemblyNames.Add("system.net.webheadercollection", "costura.system.net.webheadercollection.dll.compressed");
			assemblyNames.Add("system.net.websockets.client", "costura.system.net.websockets.client.dll.compressed");
			assemblyNames.Add("system.net.websockets", "costura.system.net.websockets.dll.compressed");
			assemblyNames.Add("system.numerics", "costura.system.numerics.dll.compressed");
			assemblyNames.Add("system.objectmodel", "costura.system.objectmodel.dll.compressed");
			assemblyNames.Add("system.reflection", "costura.system.reflection.dll.compressed");
			assemblyNames.Add("system.reflection.emit", "costura.system.reflection.emit.dll.compressed");
			assemblyNames.Add("system.reflection.emit.ilgeneration", "costura.system.reflection.emit.ilgeneration.dll.compressed");
			assemblyNames.Add("system.reflection.emit.lightweight", "costura.system.reflection.emit.lightweight.dll.compressed");
			assemblyNames.Add("system.reflection.extensions", "costura.system.reflection.extensions.dll.compressed");
			assemblyNames.Add("system.reflection.primitives", "costura.system.reflection.primitives.dll.compressed");
			assemblyNames.Add("system.resources.reader", "costura.system.resources.reader.dll.compressed");
			assemblyNames.Add("system.resources.resourcemanager", "costura.system.resources.resourcemanager.dll.compressed");
			assemblyNames.Add("system.resources.writer", "costura.system.resources.writer.dll.compressed");
			assemblyNames.Add("system.runtime.compilerservices.unsafe", "costura.system.runtime.compilerservices.unsafe.dll.compressed");
			assemblyNames.Add("system.runtime.compilerservices.visualc", "costura.system.runtime.compilerservices.visualc.dll.compressed");
			assemblyNames.Add("system.runtime", "costura.system.runtime.dll.compressed");
			assemblyNames.Add("system.runtime.extensions", "costura.system.runtime.extensions.dll.compressed");
			assemblyNames.Add("system.runtime.handles", "costura.system.runtime.handles.dll.compressed");
			assemblyNames.Add("system.runtime.interopservices", "costura.system.runtime.interopservices.dll.compressed");
			assemblyNames.Add("system.runtime.interopservices.runtimeinformation", "costura.system.runtime.interopservices.runtimeinformation.dll.compressed");
			assemblyNames.Add("system.runtime.interopservices.windowsruntime", "costura.system.runtime.interopservices.windowsruntime.dll.compressed");
			assemblyNames.Add("system.runtime.numerics", "costura.system.runtime.numerics.dll.compressed");
			assemblyNames.Add("system.runtime.serialization", "costura.system.runtime.serialization.dll.compressed");
			assemblyNames.Add("system.runtime.serialization.formatters", "costura.system.runtime.serialization.formatters.dll.compressed");
			assemblyNames.Add("system.runtime.serialization.json", "costura.system.runtime.serialization.json.dll.compressed");
			assemblyNames.Add("system.runtime.serialization.primitives", "costura.system.runtime.serialization.primitives.dll.compressed");
			assemblyNames.Add("system.runtime.serialization.xml", "costura.system.runtime.serialization.xml.dll.compressed");
			assemblyNames.Add("system.security.claims", "costura.system.security.claims.dll.compressed");
			assemblyNames.Add("system.security.cryptography.algorithms", "costura.system.security.cryptography.algorithms.dll.compressed");
			assemblyNames.Add("system.security.cryptography.csp", "costura.system.security.cryptography.csp.dll.compressed");
			assemblyNames.Add("system.security.cryptography.encoding", "costura.system.security.cryptography.encoding.dll.compressed");
			assemblyNames.Add("system.security.cryptography.primitives", "costura.system.security.cryptography.primitives.dll.compressed");
			assemblyNames.Add("system.security.cryptography.x509certificates", "costura.system.security.cryptography.x509certificates.dll.compressed");
			assemblyNames.Add("system.security.principal", "costura.system.security.principal.dll.compressed");
			assemblyNames.Add("system.security.securestring", "costura.system.security.securestring.dll.compressed");
			assemblyNames.Add("system.servicemodel.duplex", "costura.system.servicemodel.duplex.dll.compressed");
			assemblyNames.Add("system.servicemodel.http", "costura.system.servicemodel.http.dll.compressed");
			assemblyNames.Add("system.servicemodel.nettcp", "costura.system.servicemodel.nettcp.dll.compressed");
			assemblyNames.Add("system.servicemodel.primitives", "costura.system.servicemodel.primitives.dll.compressed");
			assemblyNames.Add("system.servicemodel.security", "costura.system.servicemodel.security.dll.compressed");
			assemblyNames.Add("system.text.encoding", "costura.system.text.encoding.dll.compressed");
			assemblyNames.Add("system.text.encoding.extensions", "costura.system.text.encoding.extensions.dll.compressed");
			assemblyNames.Add("system.text.regularexpressions", "costura.system.text.regularexpressions.dll.compressed");
			assemblyNames.Add("system.threading.channels", "costura.system.threading.channels.dll.compressed");
			assemblyNames.Add("system.threading", "costura.system.threading.dll.compressed");
			assemblyNames.Add("system.threading.overlapped", "costura.system.threading.overlapped.dll.compressed");
			assemblyNames.Add("system.threading.tasks", "costura.system.threading.tasks.dll.compressed");
			assemblyNames.Add("system.threading.tasks.extensions", "costura.system.threading.tasks.extensions.dll.compressed");
			assemblyNames.Add("system.threading.tasks.parallel", "costura.system.threading.tasks.parallel.dll.compressed");
			assemblyNames.Add("system.threading.thread", "costura.system.threading.thread.dll.compressed");
			assemblyNames.Add("system.threading.threadpool", "costura.system.threading.threadpool.dll.compressed");
			assemblyNames.Add("system.threading.timer", "costura.system.threading.timer.dll.compressed");
			assemblyNames.Add("system.valuetuple", "costura.system.valuetuple.dll.compressed");
			assemblyNames.Add("system.xml", "costura.system.xml.dll.compressed");
			assemblyNames.Add("system.xml.linq", "costura.system.xml.linq.dll.compressed");
			assemblyNames.Add("system.xml.readerwriter", "costura.system.xml.readerwriter.dll.compressed");
			assemblyNames.Add("system.xml.xdocument", "costura.system.xml.xdocument.dll.compressed");
			assemblyNames.Add("system.xml.xmldocument", "costura.system.xml.xmldocument.dll.compressed");
			assemblyNames.Add("system.xml.xmlserializer", "costura.system.xml.xmlserializer.dll.compressed");
			assemblyNames.Add("system.xml.xpath", "costura.system.xml.xpath.dll.compressed");
			assemblyNames.Add("system.xml.xpath.xdocument", "costura.system.xml.xpath.xdocument.dll.compressed");
		}

		public static void Attach()
		{
			if (Interlocked.Exchange(ref isAttached, 1) == 1)
			{
				return;
			}
			AppDomain currentDomain = AppDomain.CurrentDomain;
			currentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)
			{
				lock (nullCacheLock)
				{
					if (nullCache.ContainsKey(e.Name))
					{
						return null;
					}
				}
				AssemblyName assemblyName = new AssemblyName(e.Name);
				Assembly assembly = ReadExistingAssembly(assemblyName);
				if ((object)assembly != null)
				{
					return assembly;
				}
				assembly = ReadFromEmbeddedResources(assemblyNames, symbolNames, assemblyName);
				if ((object)assembly == null)
				{
					lock (nullCacheLock)
					{
						nullCache[e.Name] = true;
					}
					if ((assemblyName.Flags & AssemblyNameFlags.Retargetable) != 0)
					{
						assembly = Assembly.Load(assemblyName);
					}
				}
				return assembly;
			};
		}
	}
}
internal class LethalVibrations_ProcessedByFody
{
	internal const string FodyVersion = "6.8.0.0";

	internal const string Costura = "5.7.0";
}

BooBoo Building/BepInEx/plugins/matsuura-HealthMetrics/HealthMetrics.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("HealthMetrics")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HealthMetrics")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("eba7b111-51e5-4353-807d-1268e6290901")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HealthMetrics
{
	[BepInPlugin("Matsuura.HealthMetrics", "HealthMetrics", "1.0.0")]
	public class HealthMetricsBase : BaseUnityPlugin
	{
		private const string modGUID = "Matsuura.HealthMetrics";

		private const string modName = "HealthMetrics";

		private const string modVersion = "1.0.0";

		private readonly Harmony _harmony = new Harmony("Matsuura.HealthMetrics");

		private static HealthMetricsBase _instance;

		private static ManualLogSource _logSource;

		internal void Awake()
		{
			if ((Object)(object)_instance == (Object)null)
			{
				_instance = this;
			}
			if (_logSource == null)
			{
				_logSource = Logger.CreateLogSource("Matsuura.HealthMetrics");
			}
			_harmony.PatchAll();
			_logSource.LogInfo((object)"HealthMetrics Awake");
		}

		internal static void Log(string message)
		{
			if (_logSource != null)
			{
				_logSource.LogInfo((object)message);
			}
		}

		internal static void LogD(string message)
		{
			if (_logSource != null)
			{
				_logSource.LogDebug((object)message);
			}
		}
	}
}
namespace HealthMetrics.Patches
{
	[HarmonyPatch(typeof(HUDManager))]
	internal class HealthHUDPatches
	{
		private static TextMeshProUGUI _healthText;

		private static readonly string DefaultValueHealthText = " ¤";

		public static int _oldValuehealthValueForUpdater = 0;

		public static int _healthValueForUpdater = 100;

		private static readonly Color _healthyColor = Color32.op_Implicit(new Color32((byte)0, byte.MaxValue, (byte)0, byte.MaxValue));

		private static readonly Color _criticalHealthColor = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)0, (byte)0, byte.MaxValue));

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void Start(ref HUDManager __instance)
		{
			//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_0039: 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)
			GameObject val = new GameObject("HealthHUDDisplay");
			val.AddComponent<RectTransform>();
			TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>();
			RectTransform rectTransform = ((TMP_Text)obj).rectTransform;
			((Transform)rectTransform).SetParent(((Component)__instance.PTTIcon).transform, false);
			rectTransform.anchoredPosition = new Vector2(8f, -57f);
			((TMP_Text)obj).font = ((TMP_Text)__instance.controlTipLines[0]).font;
			((TMP_Text)obj).fontSize = 16f;
			((TMP_Text)obj).text = "100";
			((Graphic)obj).color = _healthyColor;
			((TMP_Text)obj).overflowMode = (TextOverflowModes)0;
			((Behaviour)obj).enabled = true;
			_healthText = obj;
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void Update()
		{
			//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_0088: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_healthText != (Object)null && _healthValueForUpdater != _oldValuehealthValueForUpdater)
			{
				_oldValuehealthValueForUpdater = _healthValueForUpdater;
				if (_healthValueForUpdater > 0)
				{
					((TMP_Text)_healthText).text = _healthValueForUpdater.ToString().PadLeft((_healthValueForUpdater < 10) ? 2 : 3, ' ');
				}
				else
				{
					((TMP_Text)_healthText).text = DefaultValueHealthText;
				}
				double percentage = (double)_healthValueForUpdater / 100.0;
				((Graphic)_healthText).color = ColorInterpolation(_criticalHealthColor, _healthyColor, percentage);
			}
		}

		public static int LinearInterpolation(int start, int end, double percentage)
		{
			return start + (int)Math.Round(percentage * (double)(end - start));
		}

		public static Color ColorInterpolation(Color start, Color end, double percentage)
		{
			//IL_0000: 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_0021: 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_0042: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			return new Color(hexToFloat(LinearInterpolation(floatToHex(start.r), floatToHex(end.r), percentage)), hexToFloat(LinearInterpolation(floatToHex(start.g), floatToHex(end.g), percentage)), hexToFloat(LinearInterpolation(floatToHex(start.b), floatToHex((int)end.b), percentage)), 1f);
		}

		public static float hexToFloat(int hex)
		{
			return (float)hex / 255f;
		}

		public static int floatToHex(float f)
		{
			return (int)f * 255;
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch("LateUpdate")]
		private static void LateUpdate_Prefix(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject))
			{
				HealthHUDPatches._healthValueForUpdater = ((__instance.health >= 0) ? __instance.health : 0);
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/MaxWasUnavailable-ScrollInverter/ScrollInverter.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("ScrollInverter")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Inverts the scroll wheel direction for the item bar.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ScrollInverter")]
[assembly: AssemblyTitle("ScrollInverter")]
[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 ScrollInverter
{
	[BepInPlugin("ScrollInverter", "ScrollInverter", "1.0.0")]
	public class ScrollInverter : BaseUnityPlugin
	{
		private bool _isPatched;

		private Harmony Harmony { get; set; }

		internal static ManualLogSource Logger { get; set; }

		public static ScrollInverter Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
			Logger = ((BaseUnityPlugin)this).Logger;
			PatchAll();
			Logger.LogInfo((object)"Plugin ScrollInverter is loaded!");
		}

		public void PatchAll()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			if (_isPatched)
			{
				Logger.LogWarning((object)"Already patched!");
				return;
			}
			Logger.LogDebug((object)"Patching...");
			Harmony = new Harmony("ScrollInverter");
			Harmony.PatchAll();
			_isPatched = true;
			Logger.LogDebug((object)"Patched!");
		}

		public void UnpatchAll()
		{
			if (!_isPatched)
			{
				Logger.LogWarning((object)"Already unpatched!");
				return;
			}
			Logger.LogDebug((object)"Unpatching...");
			Harmony.UnpatchSelf();
			_isPatched = false;
			Logger.LogDebug((object)"Unpatched!");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "ScrollInverter";

		public const string PLUGIN_NAME = "ScrollInverter";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace ScrollInverter.Patches
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	public class PlayerControllerBPatches
	{
		[HarmonyPatch("SwitchItem_performed")]
		[HarmonyTranspiler]
		public static IEnumerable<CodeInstruction> InvertControlsSwitchItemPerformed(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return new CodeMatcher(instructions, (ILGenerator)null).SearchForward((Func<CodeInstruction, bool>)delegate(CodeInstruction instruction)
			{
				string? name = instruction.opcode.Name;
				OpCode ble_Un = OpCodes.Ble_Un;
				return name == ble_Un.Name;
			}).ThrowIfInvalid("Could not find branch instruction").SetOpcodeAndAdvance(OpCodes.Bge_Un_S)
				.InstructionEnumeration();
		}
	}
}

BooBoo Building/BepInEx/plugins/MegaPiggy-InsanityMeter/InsanityMeter.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
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(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("InsanityMeter")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright © 2023 MegaPiggy")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("InsanityMeter")]
[assembly: AssemblyTitle("InsanityMeter")]
[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 InsanityMeter
{
	[BepInPlugin("MegaPiggy.InsanityMeter", "Insanity Meter", "1.0.0")]
	public class InsanityMeterMod : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(HUDManager))]
		internal class HUDManagerPatch
		{
			[HarmonyPatch("Awake")]
			[HarmonyPostfix]
			public static void AwakePostfix(HUDManager __instance)
			{
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0044: Expected O, but got Unknown
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				//IL_005c: Unknown result type (might be due to invalid IL or missing references)
				//IL_006c: Expected O, but got Unknown
				//IL_0079: 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_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
				//IL_0116: Unknown result type (might be due to invalid IL or missing references)
				//IL_011d: Expected O, but got Unknown
				//IL_0128: Unknown result type (might be due to invalid IL or missing references)
				//IL_0132: Unknown result type (might be due to invalid IL or missing references)
				//IL_0149: Unknown result type (might be due to invalid IL or missing references)
				//IL_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)
				Transform parent = ((Component)__instance.HUDElements[2].canvasGroup).transform.parent;
				GameObject val = new GameObject("InsanityMeter", new Type[2]
				{
					typeof(Image),
					typeof(CanvasGroup)
				});
				__instance.HUDElements = CollectionExtensions.AddToArray<HUDElement>(__instance.HUDElements, new HUDElement
				{
					canvasGroup = val.GetComponent<CanvasGroup>(),
					targetAlpha = 1f
				});
				RectTransform component = val.GetComponent<RectTransform>();
				component.pivot = Vector2.one * 0.5f;
				component.sizeDelta = new Vector2(150f, 20f);
				component.anchoredPosition3D = new Vector3(0f, 220f, -0.075f);
				Image component2 = val.GetComponent<Image>();
				component2.sprite = CreateSpriteFromTexture(Texture2D.whiteTexture);
				((Graphic)component2).color = Color.black;
				((Component)component2).transform.SetParent(parent, false);
				GameObject val2 = new GameObject("InsanityBar", new Type[2]
				{
					typeof(Image),
					typeof(InsanityMeterUI)
				});
				RectTransform component3 = val2.GetComponent<RectTransform>();
				component3.pivot = Vector2.one * 0.5f;
				component3.sizeDelta = new Vector2(150f, 20f);
				Image component4 = val2.GetComponent<Image>();
				component4.fillMethod = (FillMethod)0;
				component4.type = (Type)3;
				component4.sprite = CreateSpriteFromTexture(Texture2D.whiteTexture);
				((Graphic)component4).color = Color32.op_Implicit(new Color32((byte)123, (byte)0, (byte)236, byte.MaxValue));
				val2.transform.SetParent(((Component)component2).transform, false);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB))]
		internal class PlayerControllerPatch
		{
			[HarmonyPatch("LateUpdate")]
			[HarmonyPostfix]
			public static void LateUpdatePostfix(PlayerControllerB __instance)
			{
				if (((NetworkBehaviour)__instance).IsOwner && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject) && __instance.isPlayerControlled && !__instance.isPlayerDead)
				{
					InsanityMeterUI.Instance.UpdatePercentage(__instance.GetInsanityPercentage());
				}
			}
		}

		private const string modGUID = "MegaPiggy.InsanityMeter";

		private const string modName = "Insanity Meter";

		private const string modVersion = "1.0.0";

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

		private static InsanityMeterMod Instance { get; set; }

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

		public static Sprite CreateSpriteFromTexture(Texture2D texture2D)
		{
			//IL_001a: 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)
			Sprite val = Sprite.Create(texture2D, new Rect(0f, 0f, (float)((Texture)texture2D).width, (float)((Texture)texture2D).height), new Vector2(0.5f, 0.5f));
			((Object)val).name = ((Object)texture2D).name;
			return val;
		}

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Insanity Meter is loaded with version 1.0.0!");
		}
	}
	public class InsanityMeterUI : MonoBehaviour
	{
		private Image image;

		public static InsanityMeterUI Instance { get; private set; }

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			image = ((Component)this).GetComponent<Image>();
		}

		public void UpdatePercentage(float insanityPercentage)
		{
			image.fillAmount = insanityPercentage;
		}
	}
	public static class PlayerExtensions
	{
		public static float GetInsanityPercentage(this PlayerControllerB player)
		{
			return player.insanityLevel / player.maxInsanityLevel;
		}
	}
}

BooBoo Building/BepInEx/plugins/MMHOOK/MMHOOK_AmazingAssets.TerrainToMesh.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using AmazingAssets.TerrainToMesh;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On;
using On.AmazingAssets.TerrainToMesh;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On
{
	public static class \u200f\u202b\u202b\u202c\u206d\u206e\u206e\u202b\u200d\u202b\u202d\u200e\u206f\u200b\u206a\u202d\u206e\u206d\u200b\u202b\u200d\u206f\u202e\u202b\u200c\u206c\u200b\u202c\u206e\u202d\u206e\u202d\u202a\u200e\u206c\u202d\u206c\u200b\u202c\u200f\u202e
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate object orig_\u206f\u202b\u200f\u206e\u206e\u202c\u202c\u206d\u206b\u206d\u206c\u206f\u202d\u200d\u206b\u200d\u202a\u206c\u200c\u206c\u206b\u200c\u200f\u202a\u202b\u200f\u202c\u206d\u200b\u202e\u202d\u206b\u206a\u200b\u200f\u206a\u200e\u200e\u200e\u202e(TerrainData P_0, bool P_1, bool P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate object hook_\u206f\u202b\u200f\u206e\u206e\u202c\u202c\u206d\u206b\u206d\u206c\u206f\u202d\u200d\u206b\u200d\u202a\u206c\u200c\u206c\u206b\u200c\u200f\u202a\u202b\u200f\u202c\u206d\u200b\u202e\u202d\u206b\u206a\u200b\u200f\u206a\u200e\u200e\u200e\u202e(orig_\u206f\u202b\u200f\u206e\u206e\u202c\u202c\u206d\u206b\u206d\u206c\u206f\u202d\u200d\u206b\u200d\u202a\u206c\u200c\u206c\u206b\u200c\u200f\u202a\u202b\u200f\u202c\u206d\u200b\u202e\u202d\u206b\u206a\u200b\u200f\u206a\u200e\u200e\u200e\u202e orig, TerrainData P_1, bool P_2, bool P_3);

		public static event hook_\u206f\u202b\u200f\u206e\u206e\u202c\u202c\u206d\u206b\u206d\u206c\u206f\u202d\u200d\u206b\u200d\u202a\u206c\u200c\u206c\u206b\u200c\u200f\u202a\u202b\u200f\u202c\u206d\u200b\u202e\u202d\u206b\u206a\u200b\u200f\u206a\u200e\u200e\u200e\u202e \u206f\u202b\u200f\u206e\u206e\u202c\u202c\u206d\u206b\u206d\u206c\u206f\u202d\u200d\u206b\u200d\u202a\u206c\u200c\u206c\u206b\u200c\u200f\u202a\u202b\u200f\u202c\u206d\u200b\u202e\u202d\u206b\u206a\u200b\u200f\u206a\u200e\u200e\u200e\u202e
		{
			add
			{
				HookEndpointManager.Add<hook_\u206f\u202b\u200f\u206e\u206e\u202c\u202c\u206d\u206b\u206d\u206c\u206f\u202d\u200d\u206b\u200d\u202a\u206c\u200c\u206c\u206b\u200c\u200f\u202a\u202b\u200f\u202c\u206d\u200b\u202e\u202d\u206b\u206a\u200b\u200f\u206a\u200e\u200e\u200e\u202e>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_\u206f\u202b\u200f\u206e\u206e\u202c\u202c\u206d\u206b\u206d\u206c\u206f\u202d\u200d\u206b\u200d\u202a\u206c\u200c\u206c\u206b\u200c\u200f\u202a\u202b\u200f\u202c\u206d\u200b\u202e\u202d\u206b\u206a\u200b\u200f\u206a\u200e\u200e\u200e\u202e>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class \u200f\u202b\u202b\u202c\u206d\u206e\u206e\u202b\u200d\u202b\u202d\u200e\u206f\u200b\u206a\u202d\u206e\u206d\u200b\u202b\u200d\u206f\u202e\u202b\u200c\u206c\u200b\u202c\u206e\u202d\u206e\u202d\u202a\u200e\u206c\u202d\u206c\u200b\u202c\u200f\u202e
	{
		public static event Manipulator \u206f\u202b\u200f\u206e\u206e\u202c\u202c\u206d\u206b\u206d\u206c\u206f\u202d\u200d\u206b\u200d\u202a\u206c\u200c\u206c\u206b\u200c\u200f\u202a\u202b\u200f\u202c\u206d\u200b\u202e\u202d\u206b\u206a\u200b\u200f\u206a\u200e\u200e\u200e\u202e
		{
			add
			{
				HookEndpointManager.Modify<On.\u200f\u202b\u202b\u202c\u206d\u206e\u206e\u202b\u200d\u202b\u202d\u200e\u206f\u200b\u206a\u202d\u206e\u206d\u200b\u202b\u200d\u206f\u202e\u202b\u200c\u206c\u200b\u202c\u206e\u202d\u206e\u202d\u202a\u200e\u206c\u202d\u206c\u200b\u202c\u200f\u202e.hook_\u206f\u202b\u200f\u206e\u206e\u202c\u202c\u206d\u206b\u206d\u206c\u206f\u202d\u200d\u206b\u200d\u202a\u206c\u200c\u206c\u206b\u200c\u200f\u202a\u202b\u200f\u202c\u206d\u200b\u202e\u202d\u206b\u206a\u200b\u200f\u206a\u200e\u200e\u200e\u202e>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.\u200f\u202b\u202b\u202c\u206d\u206e\u206e\u202b\u200d\u202b\u202d\u200e\u206f\u200b\u206a\u202d\u206e\u206d\u200b\u202b\u200d\u206f\u202e\u202b\u200c\u206c\u200b\u202c\u206e\u202d\u206e\u202d\u202a\u200e\u206c\u202d\u206c\u200b\u202c\u200f\u202e.hook_\u206f\u202b\u200f\u206e\u206e\u202c\u202c\u206d\u206b\u206d\u206c\u206f\u202d\u200d\u206b\u200d\u202a\u206c\u200c\u206c\u206b\u200c\u200f\u202a\u202b\u200f\u202c\u206d\u200b\u202e\u202d\u206b\u206a\u200b\u200f\u206a\u200e\u200e\u200e\u202e>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class \u200f\u202c\u202d\u202a\u206a\u200b\u200b\u202c\u200e\u200c\u200f\u206f\u200d\u200c\u206c\u206e\u200e\u206f\u206b\u206b\u202c\u200f\u206b\u200f\u200c\u206f\u200d\u202d\u206e\u206c\u202c\u200f\u202b\u202a\u200c\u202a\u202a\u206c\u200d\u206f\u202e
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(object self, TerrainData P_1, bool P_2, bool P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, object self, TerrainData P_2, bool P_3, bool P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u202a\u200c\u206b\u206f\u202d\u200d\u200b\u200d\u206e\u202a\u202c\u206e\u200c\u200e\u206a\u202e\u202c\u200e\u206d\u200c\u200e\u200c\u202d\u200f\u206b\u202b\u206b\u206c\u206b\u206f\u202c\u202a\u200b\u202a\u200b\u206e\u202a\u202b\u206e\u206b\u202e(Texture P_0, RenderTexture P_1, bool P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u202a\u200c\u206b\u206f\u202d\u200d\u200b\u200d\u206e\u202a\u202c\u206e\u200c\u200e\u206a\u202e\u202c\u200e\u206d\u200c\u200e\u200c\u202d\u200f\u206b\u202b\u206b\u206c\u206b\u206f\u202c\u202a\u200b\u202a\u200b\u206e\u202a\u202b\u206e\u206b\u202e(orig_\u202a\u200c\u206b\u206f\u202d\u200d\u200b\u200d\u206e\u202a\u202c\u206e\u200c\u200e\u206a\u202e\u202c\u200e\u206d\u200c\u200e\u200c\u202d\u200f\u206b\u202b\u206b\u206c\u206b\u206f\u202c\u202a\u200b\u202a\u200b\u206e\u202a\u202b\u206e\u206b\u202e orig, Texture P_1, RenderTexture P_2, bool P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u200c\u200b\u200b\u200e\u200b\u206d\u202e\u202c\u200b\u200e\u206b\u202b\u200e\u202e\u200b\u200f\u200f\u202e\u206f\u200e\u200c\u200f\u202c\u200f\u206a\u206a\u200c\u206d\u206b\u206d\u206c\u200f\u202a\u202a\u200c\u206d\u206e\u200f\u202b\u202a\u202e(Texture P_0, RenderTexture P_1, Material P_2, bool P_3, int P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u200c\u200b\u200b\u200e\u200b\u206d\u202e\u202c\u200b\u200e\u206b\u202b\u200e\u202e\u200b\u200f\u200f\u202e\u206f\u200e\u200c\u200f\u202c\u200f\u206a\u206a\u200c\u206d\u206b\u206d\u206c\u200f\u202a\u202a\u200c\u206d\u206e\u200f\u202b\u202a\u202e(orig_\u200c\u200b\u200b\u200e\u200b\u206d\u202e\u202c\u200b\u200e\u206b\u202b\u200e\u202e\u200b\u200f\u200f\u202e\u206f\u200e\u200c\u200f\u202c\u200f\u206a\u206a\u200c\u206d\u206b\u206d\u206c\u200f\u202a\u202a\u200c\u206d\u206e\u200f\u202b\u202a\u202e orig, Texture P_1, RenderTexture P_2, Material P_3, bool P_4, int P_5);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D orig_\u206a\u202b\u202b\u200b\u200d\u200e\u202e\u206e\u206b\u206e\u202d\u200d\u202c\u206c\u202b\u200b\u200c\u202b\u202c\u202a\u206f\u206c\u206d\u200e\u206b\u202b\u200f\u200d\u200d\u206c\u206e\u206c\u200d\u206e\u206d\u206f\u206f\u200d\u206c\u202e(Color P_0, TextureFormat P_1, bool P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D hook_\u206a\u202b\u202b\u200b\u200d\u200e\u202e\u206e\u206b\u206e\u202d\u200d\u202c\u206c\u202b\u200b\u200c\u202b\u202c\u202a\u206f\u206c\u206d\u200e\u206b\u202b\u200f\u200d\u200d\u206c\u206e\u206c\u200d\u206e\u206d\u206f\u206f\u200d\u206c\u202e(orig_\u206a\u202b\u202b\u200b\u200d\u200e\u202e\u206e\u206b\u206e\u202d\u200d\u202c\u206c\u202b\u200b\u200c\u202b\u202c\u202a\u206f\u206c\u206d\u200e\u206b\u202b\u200f\u200d\u200d\u206c\u206e\u206c\u200d\u206e\u206d\u206f\u206f\u200d\u206c\u202e orig, Color P_1, TextureFormat P_2, bool P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D orig_\u206f\u206f\u206b\u200e\u202c\u206b\u202c\u200c\u200f\u200c\u202e\u206e\u200c\u202c\u206c\u202c\u202b\u206b\u200f\u202c\u202b\u206a\u200f\u206c\u206f\u200c\u200b\u202e\u206d\u202a\u206a\u206c\u206f\u206b\u206a\u206c\u206d\u202b\u206a\u202b\u202e(int P_0, int P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D hook_\u206f\u206f\u206b\u200e\u202c\u206b\u202c\u200c\u200f\u200c\u202e\u206e\u200c\u202c\u206c\u202c\u202b\u206b\u200f\u202c\u202b\u206a\u200f\u206c\u206f\u200c\u200b\u202e\u206d\u202a\u206a\u206c\u206f\u206b\u206a\u206c\u206d\u202b\u206a\u202b\u202e(orig_\u206f\u206f\u206b\u200e\u202c\u206b\u202c\u200c\u200f\u200c\u202e\u206e\u200c\u202c\u206c\u202c\u202b\u206b\u200f\u202c\u202b\u206a\u200f\u206c\u206f\u200c\u200b\u202e\u206d\u202a\u206a\u206c\u206f\u206b\u206a\u206c\u206d\u202b\u206a\u202b\u202e orig, int P_1, int P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u200c\u206a\u206e\u206f\u200f\u206f\u202a\u200e\u206c\u202e\u202a\u200f\u206e\u202b\u206f\u200e\u200d\u200b\u202c\u202b\u202c\u206b\u200c\u202c\u200d\u202d\u200d\u200e\u202b\u206f\u200f\u206e\u200f\u200b\u206e\u200b\u202b\u202b\u202a\u206d\u202e(RenderTexture P_0, TextureFormat P_1, ref Texture2D P_2, bool P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u200c\u206a\u206e\u206f\u200f\u206f\u202a\u200e\u206c\u202e\u202a\u200f\u206e\u202b\u206f\u200e\u200d\u200b\u202c\u202b\u202c\u206b\u200c\u202c\u200d\u202d\u200d\u200e\u202b\u206f\u200f\u206e\u200f\u200b\u206e\u200b\u202b\u202b\u202a\u206d\u202e(orig_\u200c\u206a\u206e\u206f\u200f\u206f\u202a\u200e\u206c\u202e\u202a\u200f\u206e\u202b\u206f\u200e\u200d\u200b\u202c\u202b\u202c\u206b\u200c\u202c\u200d\u202d\u200d\u200e\u202b\u206f\u200f\u206e\u200f\u200b\u206e\u200b\u202b\u202b\u202a\u206d\u202e orig, RenderTexture P_1, TextureFormat P_2, ref Texture2D P_3, bool P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D orig_\u202d\u200d\u202e\u200b\u202e\u200e\u206b\u206d\u200b\u200f\u206e\u200d\u200e\u200f\u202e\u202a\u202d\u202c\u200e\u200b\u206a\u206e\u202b\u206c\u206f\u206c\u206c\u202c\u202d\u202d\u202c\u200d\u200b\u200e\u200b\u200c\u202d\u200c\u200c\u206c\u202e(Texture2D P_0, bool P_1, int P_2, int P_3, int P_4, int P_5);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D hook_\u202d\u200d\u202e\u200b\u202e\u200e\u206b\u206d\u200b\u200f\u206e\u200d\u200e\u200f\u202e\u202a\u202d\u202c\u200e\u200b\u206a\u206e\u202b\u206c\u206f\u206c\u206c\u202c\u202d\u202d\u202c\u200d\u200b\u200e\u200b\u200c\u202d\u200c\u200c\u206c\u202e(orig_\u202d\u200d\u202e\u200b\u202e\u200e\u206b\u206d\u200b\u200f\u206e\u200d\u200e\u200f\u202e\u202a\u202d\u202c\u200e\u200b\u206a\u206e\u202b\u206c\u206f\u206c\u206c\u202c\u202d\u202d\u202c\u200d\u200b\u200e\u200b\u200c\u202d\u200c\u200c\u206c\u202e orig, Texture2D P_1, bool P_2, int P_3, int P_4, int P_5, int P_6);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D[] orig_\u206f\u202e\u202b\u202b\u200e\u202b\u206e\u202e\u202d\u200e\u206c\u202c\u206c\u206f\u200b\u200b\u200d\u206a\u206f\u206b\u202e\u206e\u202a\u202b\u206b\u206e\u206c\u206f\u202c\u200d\u202d\u202c\u202d\u206b\u200c\u202a\u200e\u206b\u200e\u206e\u202e(Texture2D[] P_0, bool P_1, int P_2, int P_3, int P_4, int P_5);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D[] hook_\u206f\u202e\u202b\u202b\u200e\u202b\u206e\u202e\u202d\u200e\u206c\u202c\u206c\u206f\u200b\u200b\u200d\u206a\u206f\u206b\u202e\u206e\u202a\u202b\u206b\u206e\u206c\u206f\u202c\u200d\u202d\u202c\u202d\u206b\u200c\u202a\u200e\u206b\u200e\u206e\u202e(orig_\u206f\u202e\u202b\u202b\u200e\u202b\u206e\u202e\u202d\u200e\u206c\u202c\u206c\u206f\u200b\u200b\u200d\u206a\u206f\u206b\u202e\u206e\u202a\u202b\u206b\u206e\u206c\u206f\u202c\u200d\u202d\u202c\u202d\u206b\u200c\u202a\u200e\u206b\u200e\u206e\u202e orig, Texture2D[] P_1, bool P_2, int P_3, int P_4, int P_5, int P_6);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D[] orig_\u206f\u206a\u206d\u202c\u202c\u206f\u206f\u200f\u206b\u202a\u206a\u200c\u202a\u202d\u206c\u206d\u206d\u200e\u206d\u200b\u200e\u200b\u202a\u200c\u202d\u200f\u202b\u200e\u206b\u202d\u200d\u202b\u200f\u200b\u200f\u206e\u206f\u206c\u206b\u206d\u202e(Texture2D P_0, bool P_1, int P_2, int P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D[] hook_\u206f\u206a\u206d\u202c\u202c\u206f\u206f\u200f\u206b\u202a\u206a\u200c\u202a\u202d\u206c\u206d\u206d\u200e\u206d\u200b\u200e\u200b\u202a\u200c\u202d\u200f\u202b\u200e\u206b\u202d\u200d\u202b\u200f\u200b\u200f\u206e\u206f\u206c\u206b\u206d\u202e(orig_\u206f\u206a\u206d\u202c\u202c\u206f\u206f\u200f\u206b\u202a\u206a\u200c\u202a\u202d\u206c\u206d\u206d\u200e\u206d\u200b\u200e\u200b\u202a\u200c\u202d\u200f\u202b\u200e\u206b\u202d\u200d\u202b\u200f\u200b\u200f\u206e\u206f\u206c\u206b\u206d\u202e orig, Texture2D P_1, bool P_2, int P_3, int P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D[] orig_\u206a\u206a\u202b\u202b\u200d\u200b\u206f\u200d\u200c\u206a\u206b\u200f\u206c\u202a\u206b\u202a\u200d\u206d\u200f\u206e\u202a\u200e\u206a\u206d\u206b\u200c\u202a\u206c\u206d\u200e\u200f\u206a\u202d\u200d\u202e\u200c\u206d\u202b\u200b\u206d\u202e(Texture2D[] P_0, bool P_1, int P_2, int P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D[] hook_\u206a\u206a\u202b\u202b\u200d\u200b\u206f\u200d\u200c\u206a\u206b\u200f\u206c\u202a\u206b\u202a\u200d\u206d\u200f\u206e\u202a\u200e\u206a\u206d\u206b\u200c\u202a\u206c\u206d\u200e\u200f\u206a\u202d\u200d\u202e\u200c\u206d\u202b\u200b\u206d\u202e(orig_\u206a\u206a\u202b\u202b\u200d\u200b\u206f\u200d\u200c\u206a\u206b\u200f\u206c\u202a\u206b\u202a\u200d\u206d\u200f\u206e\u202a\u200e\u206a\u206d\u206b\u200c\u202a\u206c\u206d\u200e\u200f\u206a\u202d\u200d\u202e\u200c\u206d\u202b\u200b\u206d\u202e orig, Texture2D[] P_1, bool P_2, int P_3, int P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D orig_\u206c\u202c\u206e\u200d\u206e\u200c\u202e\u200f\u200e\u200f\u202b\u200c\u200d\u206f\u202b\u206d\u206d\u206c\u200f\u206f\u202e\u200b\u206b\u200f\u202a\u200e\u202c\u202d\u202b\u206d\u206d\u200b\u202e\u202e\u202d\u202a\u206f\u202a\u202e\u200e\u202e(Texture2D P_0, bool P_1, int P_2, int P_3, int P_4, int P_5);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D hook_\u206c\u202c\u206e\u200d\u206e\u200c\u202e\u200f\u200e\u200f\u202b\u200c\u200d\u206f\u202b\u206d\u206d\u206c\u200f\u206f\u202e\u200b\u206b\u200f\u202a\u200e\u202c\u202d\u202b\u206d\u206d\u200b\u202e\u202e\u202d\u202a\u206f\u202a\u202e\u200e\u202e(orig_\u206c\u202c\u206e\u200d\u206e\u200c\u202e\u200f\u200e\u200f\u202b\u200c\u200d\u206f\u202b\u206d\u206d\u206c\u200f\u206f\u202e\u200b\u206b\u200f\u202a\u200e\u202c\u202d\u202b\u206d\u206d\u200b\u202e\u202e\u202d\u202a\u206f\u202a\u202e\u200e\u202e orig, Texture2D P_1, bool P_2, int P_3, int P_4, int P_5, int P_6);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u206f\u206b\u206c\u200b\u200b\u200e\u200f\u200c\u206a\u200d\u200d\u206e\u206b\u202c\u202d\u206a\u200c\u202e\u200d\u202d\u200b\u202b\u200c\u206a\u200d\u200c\u206f\u206e\u206e\u200d\u206e\u206b\u206f\u206a\u202a\u206e\u206c\u206c\u200f\u200c\u202e(TerrainData P_0, int P_1, out int P_2, out int P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u206f\u206b\u206c\u200b\u200b\u200e\u200f\u200c\u206a\u200d\u200d\u206e\u206b\u202c\u202d\u206a\u200c\u202e\u200d\u202d\u200b\u202b\u200c\u206a\u200d\u200c\u206f\u206e\u206e\u200d\u206e\u206b\u206f\u206a\u202a\u206e\u206c\u206c\u200f\u200c\u202e(orig_\u206f\u206b\u206c\u200b\u200b\u200e\u200f\u200c\u206a\u200d\u200d\u206e\u206b\u202c\u202d\u206a\u200c\u202e\u200d\u202d\u200b\u202b\u200c\u206a\u200d\u200c\u206f\u206e\u206e\u200d\u206e\u206b\u206f\u206a\u202a\u206e\u206c\u206c\u200f\u200c\u202e orig, TerrainData P_1, int P_2, out int P_3, out int P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_\u206a\u200e\u206a\u202a\u200d\u206f\u202b\u206d\u200f\u202b\u206c\u200b\u200e\u202d\u206e\u206e\u206a\u206e\u200d\u202a\u206e\u206b\u200f\u206c\u200b\u200e\u200d\u200b\u202d\u202d\u200c\u206e\u200d\u200e\u206d\u200d\u202e\u202d\u200f\u206b\u202e(int P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_\u206a\u200e\u206a\u202a\u200d\u206f\u202b\u206d\u200f\u202b\u206c\u200b\u200e\u202d\u206e\u206e\u206a\u206e\u200d\u202a\u206e\u206b\u200f\u206c\u200b\u200e\u200d\u200b\u202d\u202d\u200c\u206e\u200d\u200e\u206d\u200d\u202e\u202d\u200f\u206b\u202e(orig_\u206a\u200e\u206a\u202a\u200d\u206f\u202b\u206d\u200f\u202b\u206c\u200b\u200e\u202d\u206e\u206e\u206a\u206e\u200d\u202a\u206e\u206b\u200f\u206c\u200b\u200e\u200d\u200b\u202d\u202d\u200c\u206e\u200d\u200e\u206d\u200d\u202e\u202d\u200f\u206b\u202e orig, int P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ColorSpace orig_\u206e\u202a\u200f\u206c\u206a\u206c\u200d\u200e\u206b\u200b\u200d\u206c\u202c\u202a\u202c\u200d\u202b\u206b\u200e\u206f\u206b\u200b\u200e\u202b\u206e\u200c\u200d\u206e\u202e\u200e\u202c\u200d\u206d\u200c\u200c\u202c\u200e\u202d\u202c\u206c\u202e();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ColorSpace hook_\u206e\u202a\u200f\u206c\u206a\u206c\u200d\u200e\u206b\u200b\u200d\u206c\u202c\u202a\u202c\u200d\u202b\u206b\u200e\u206f\u206b\u200b\u200e\u202b\u206e\u200c\u200d\u206e\u202e\u200e\u202c\u200d\u206d\u200c\u200c\u202c\u200e\u202d\u202c\u206c\u202e(orig_\u206e\u202a\u200f\u206c\u206a\u206c\u200d\u200e\u206b\u200b\u200d\u206c\u202c\u202a\u202c\u200d\u202b\u206b\u200e\u206f\u206b\u200b\u200e\u202b\u206e\u200c\u200d\u206e\u202e\u200e\u202c\u200d\u206d\u200c\u200c\u202c\u200e\u202d\u202c\u206c\u202e orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u206c\u202d\u206f\u206f\u200d\u202c\u206a\u202b\u202c\u206e\u206b\u206d\u200f\u206b\u202d\u206b\u202e\u202b\u200b\u200f\u206c\u206c\u200f\u202e\u202c\u200c\u206c\u202c\u200b\u206a\u200b\u200e\u202b\u206f\u200d\u200b\u200e\u202c\u206c\u202b\u202e(bool P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u206c\u202d\u206f\u206f\u200d\u202c\u206a\u202b\u202c\u206e\u206b\u206d\u200f\u206b\u202d\u206b\u202e\u202b\u200b\u200f\u206c\u206c\u200f\u202e\u202c\u200c\u206c\u202c\u200b\u206a\u200b\u200e\u202b\u206f\u200d\u200b\u200e\u202c\u206c\u202b\u202e(orig_\u206c\u202d\u206f\u206f\u200d\u202c\u206a\u202b\u202c\u206e\u206b\u206d\u200f\u206b\u202d\u206b\u202e\u202b\u200b\u200f\u206c\u206c\u200f\u202e\u202c\u200c\u206c\u202c\u200b\u206a\u200b\u200e\u202b\u206f\u200d\u200b\u200e\u202c\u206c\u202b\u202e orig, bool P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_\u206c\u200b\u206c\u200b\u202d\u206a\u200e\u200b\u200f\u206e\u202b\u200e\u202a\u202a\u206c\u202c\u206f\u206b\u206c\u206a\u206c\u202a\u206a\u200b\u200b\u202e\u202c\u206e\u206d\u202c\u200c\u202a\u206a\u202d\u200d\u202b\u202c\u200d\u200c\u202b\u202e(Object P_0, Object P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_\u206c\u200b\u206c\u200b\u202d\u206a\u200e\u200b\u200f\u206e\u202b\u200e\u202a\u202a\u206c\u202c\u206f\u206b\u206c\u206a\u206c\u202a\u206a\u200b\u200b\u202e\u202c\u206e\u206d\u202c\u200c\u202a\u206a\u202d\u200d\u202b\u202c\u200d\u200c\u202b\u202e(orig_\u206c\u200b\u206c\u200b\u202d\u206a\u200e\u200b\u200f\u206e\u202b\u200e\u202a\u202a\u206c\u202c\u206f\u206b\u206c\u206a\u206c\u202a\u206a\u200b\u200b\u202e\u202c\u206e\u206d\u202c\u200c\u202a\u206a\u202d\u200d\u202b\u202c\u200d\u200c\u202b\u202e orig, Object P_1, Object P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u206c\u200e\u202a\u206a\u200e\u206d\u206c\u202a\u206e\u200d\u200f\u206e\u200b\u200f\u202d\u206c\u200c\u206f\u206c\u202d\u206b\u200f\u200f\u202b\u206f\u200d\u206c\u202e\u206b\u202c\u202b\u200e\u200b\u202c\u206b\u200c\u202c\u200e\u206d\u202e(Texture P_0, RenderTexture P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u206c\u200e\u202a\u206a\u200e\u206d\u206c\u202a\u206e\u200d\u200f\u206e\u200b\u200f\u202d\u206c\u200c\u206f\u206c\u202d\u206b\u200f\u200f\u202b\u206f\u200d\u206c\u202e\u206b\u202c\u202b\u200e\u200b\u202c\u206b\u200c\u202c\u200e\u206d\u202e(orig_\u206c\u200e\u202a\u206a\u200e\u206d\u206c\u202a\u206e\u200d\u200f\u206e\u200b\u200f\u202d\u206c\u200c\u206f\u206c\u202d\u206b\u200f\u200f\u202b\u206f\u200d\u206c\u202e\u206b\u202c\u202b\u200e\u200b\u202c\u206b\u200c\u202c\u200e\u206d\u202e orig, Texture P_1, RenderTexture P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u200f\u206f\u206c\u200d\u200f\u200c\u206c\u200e\u202a\u202a\u206e\u206a\u200b\u202b\u206d\u206f\u206c\u202c\u206f\u200c\u202b\u200f\u206e\u206b\u202c\u206b\u206b\u200f\u206b\u202b\u200f\u200d\u200e\u206e\u206d\u206e\u200b\u200f\u206b\u206d\u202e(Texture P_0, RenderTexture P_1, Material P_2, int P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u200f\u206f\u206c\u200d\u200f\u200c\u206c\u200e\u202a\u202a\u206e\u206a\u200b\u202b\u206d\u206f\u206c\u202c\u206f\u200c\u202b\u200f\u206e\u206b\u202c\u206b\u206b\u200f\u206b\u202b\u200f\u200d\u200e\u206e\u206d\u206e\u200b\u200f\u206b\u206d\u202e(orig_\u200f\u206f\u206c\u200d\u200f\u200c\u206c\u200e\u202a\u202a\u206e\u206a\u200b\u202b\u206d\u206f\u206c\u202c\u206f\u200c\u202b\u200f\u206e\u206b\u202c\u206b\u206b\u200f\u206b\u202b\u200f\u200d\u200e\u206e\u206d\u206e\u200b\u200f\u206b\u206d\u202e orig, Texture P_1, RenderTexture P_2, Material P_3, int P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D orig_\u202b\u206b\u200d\u202e\u200e\u202c\u206f\u200b\u206e\u200f\u200f\u202d\u206a\u200e\u206f\u200e\u206c\u206d\u202a\u206a\u206e\u200e\u206d\u202a\u202c\u202e\u206b\u202a\u202e\u206e\u200b\u200d\u202b\u206b\u200b\u206f\u202c\u202b\u206d\u202d\u202e(int P_0, int P_1, TextureFormat P_2, bool P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D hook_\u202b\u206b\u200d\u202e\u200e\u202c\u206f\u200b\u206e\u200f\u200f\u202d\u206a\u200e\u206f\u200e\u206c\u206d\u202a\u206a\u206e\u200e\u206d\u202a\u202c\u202e\u206b\u202a\u202e\u206e\u200b\u200d\u202b\u206b\u200b\u206f\u202c\u202b\u206d\u202d\u202e(orig_\u202b\u206b\u200d\u202e\u200e\u202c\u206f\u200b\u206e\u200f\u200f\u202d\u206a\u200e\u206f\u200e\u206c\u206d\u202a\u206a\u206e\u200e\u206d\u202a\u202c\u202e\u206b\u202a\u202e\u206e\u200b\u200d\u202b\u206b\u200b\u206f\u202c\u202b\u206d\u202d\u202e orig, int P_1, int P_2, TextureFormat P_3, bool P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u202b\u202a\u202e\u206a\u202b\u202e\u200b\u206b\u200d\u200c\u206f\u200b\u202d\u206b\u200e\u202d\u206b\u200b\u206e\u206b\u202c\u202d\u206b\u206e\u206b\u202b\u202e\u202a\u200c\u200f\u202c\u206d\u202b\u202a\u200f\u202a\u202a\u206d\u202d\u206c\u202e(Texture2D P_0, Color[] P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u202b\u202a\u202e\u206a\u202b\u202e\u200b\u206b\u200d\u200c\u206f\u200b\u202d\u206b\u200e\u202d\u206b\u200b\u206e\u206b\u202c\u202d\u206b\u206e\u206b\u202b\u202e\u202a\u200c\u200f\u202c\u206d\u202b\u202a\u200f\u202a\u202a\u206d\u202d\u206c\u202e(orig_\u202b\u202a\u202e\u206a\u202b\u202e\u200b\u206b\u200d\u200c\u206f\u200b\u202d\u206b\u200e\u202d\u206b\u200b\u206e\u206b\u202c\u202d\u206b\u206e\u206b\u202b\u202e\u202a\u200c\u200f\u202c\u206d\u202b\u202a\u200f\u202a\u202a\u206d\u202d\u206c\u202e orig, Texture2D P_1, Color[] P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u202e\u202d\u206b\u206b\u206e\u200d\u200e\u200d\u202d\u202a\u206c\u206f\u206d\u202c\u200d\u206c\u202e\u200d\u202c\u206b\u202a\u206f\u206d\u202b\u200e\u202d\u200e\u202d\u206a\u200c\u202e\u206c\u202b\u200d\u200b\u206c\u200d\u206f\u206f\u202c\u202e(Texture2D P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u202e\u202d\u206b\u206b\u206e\u200d\u200e\u200d\u202d\u202a\u206c\u206f\u206d\u202c\u200d\u206c\u202e\u200d\u202c\u206b\u202a\u206f\u206d\u202b\u200e\u202d\u200e\u202d\u206a\u200c\u202e\u206c\u202b\u200d\u200b\u206c\u200d\u206f\u206f\u202c\u202e(orig_\u202e\u202d\u206b\u206b\u206e\u200d\u200e\u200d\u202d\u202a\u206c\u206f\u206d\u202c\u200d\u206c\u202e\u200d\u202c\u206b\u202a\u206f\u206d\u202b\u200e\u202d\u200e\u202d\u206a\u200c\u202e\u206c\u202b\u200d\u200b\u206c\u200d\u206f\u206f\u202c\u202e orig, Texture2D P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate RenderTexture orig_\u202c\u206a\u202e\u202d\u200c\u202e\u206a\u202c\u206b\u206e\u200b\u206c\u200d\u206a\u200e\u206a\u206b\u206a\u202d\u206a\u206e\u206b\u202a\u202a\u206b\u202d\u206f\u202b\u202b\u202d\u206c\u206d\u206c\u202d\u206c\u202a\u206b\u202c\u206c\u202b\u202e(int P_0, int P_1, int P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate RenderTexture hook_\u202c\u206a\u202e\u202d\u200c\u202e\u206a\u202c\u206b\u206e\u200b\u206c\u200d\u206a\u200e\u206a\u206b\u206a\u202d\u206a\u206e\u206b\u202a\u202a\u206b\u202d\u206f\u202b\u202b\u202d\u206c\u206d\u206c\u202d\u206c\u202a\u206b\u202c\u206c\u202b\u202e(orig_\u202c\u206a\u202e\u202d\u200c\u202e\u206a\u202c\u206b\u206e\u200b\u206c\u200d\u206a\u200e\u206a\u206b\u206a\u202d\u206a\u206e\u206b\u202a\u202a\u206b\u202d\u206f\u202b\u202b\u202d\u206c\u206d\u206c\u202d\u206c\u202a\u206b\u202c\u206c\u202b\u202e orig, int P_1, int P_2, int P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_\u202a\u202d\u206c\u200b\u200e\u202c\u200d\u206d\u200e\u202c\u206a\u200c\u206f\u202d\u206e\u200d\u202a\u206f\u200b\u200c\u206b\u202c\u206f\u206b\u202d\u200f\u200f\u206b\u206d\u200f\u202e\u200f\u206d\u206d\u206e\u206f\u206f\u206b\u206c\u200e\u202e(RenderTexture P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_\u202a\u202d\u206c\u200b\u200e\u202c\u200d\u206d\u200e\u202c\u206a\u200c\u206f\u202d\u206e\u200d\u202a\u206f\u200b\u200c\u206b\u202c\u206f\u206b\u202d\u200f\u200f\u206b\u206d\u200f\u202e\u200f\u206d\u206d\u206e\u206f\u206f\u206b\u206c\u200e\u202e(orig_\u202a\u202d\u206c\u200b\u200e\u202c\u200d\u206d\u200e\u202c\u206a\u200c\u206f\u202d\u206e\u200d\u202a\u206f\u200b\u200c\u206b\u202c\u206f\u206b\u202d\u200f\u200f\u206b\u206d\u200f\u202e\u200f\u206d\u206d\u206e\u206f\u206f\u206b\u206c\u200e\u202e orig, RenderTexture P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u202a\u200c\u206a\u202c\u200f\u202e\u202b\u200c\u206d\u202d\u200f\u200c\u206d\u206f\u206d\u200e\u206d\u202a\u200c\u202e\u202a\u206e\u206b\u206f\u206e\u202a\u206d\u202a\u200e\u206f\u206f\u202a\u206e\u202e\u200b\u202a\u202a\u202c\u202a\u206f\u202e(RenderTexture P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u202a\u200c\u206a\u202c\u200f\u202e\u202b\u200c\u206d\u202d\u200f\u200c\u206d\u206f\u206d\u200e\u206d\u202a\u200c\u202e\u202a\u206e\u206b\u206f\u206e\u202a\u206d\u202a\u200e\u206f\u206f\u202a\u206e\u202e\u200b\u202a\u202a\u202c\u202a\u206f\u202e(orig_\u202a\u200c\u206a\u202c\u200f\u202e\u202b\u200c\u206d\u202d\u200f\u200c\u206d\u206f\u206d\u200e\u206d\u202a\u200c\u202e\u202a\u206e\u206b\u206f\u206e\u202a\u206d\u202a\u200e\u206f\u206f\u202a\u206e\u202e\u200b\u202a\u202a\u202c\u202a\u206f\u202e orig, RenderTexture P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_\u202b\u200d\u202a\u202d\u206b\u202c\u202d\u202c\u200e\u206b\u206a\u206a\u202e\u206e\u206b\u200d\u202e\u200e\u206e\u200f\u206a\u202e\u202a\u200f\u200c\u200e\u202e\u206e\u206e\u202a\u200c\u200b\u206c\u202e\u206d\u206f\u202c\u206f\u206e\u202a\u202e();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_\u202b\u200d\u202a\u202d\u206b\u202c\u202d\u202c\u200e\u206b\u206a\u206a\u202e\u206e\u206b\u200d\u202e\u200e\u206e\u200f\u206a\u202e\u202a\u200f\u200c\u200e\u202e\u206e\u206e\u202a\u200c\u200b\u206c\u202e\u206d\u206f\u202c\u206f\u206e\u202a\u202e(orig_\u202b\u200d\u202a\u202d\u206b\u202c\u202d\u202c\u200e\u206b\u206a\u206a\u202e\u206e\u206b\u200d\u202e\u200e\u206e\u200f\u206a\u202e\u202a\u200f\u200c\u200e\u202e\u206e\u206e\u202a\u200c\u200b\u206c\u202e\u206d\u206f\u202c\u206f\u206e\u202a\u202e orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u202c\u206f\u202b\u202b\u206b\u200c\u206d\u206d\u202e\u206c\u202c\u202d\u206e\u200b\u202c\u206f\u206c\u200e\u200e\u202b\u200f\u200d\u200c\u206b\u200b\u200d\u202e\u200c\u202a\u206a\u206e\u206e\u202a\u206e\u202e\u206c\u202d\u206e\u200b\u202e\u202e(Object P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u202c\u206f\u202b\u202b\u206b\u200c\u206d\u206d\u202e\u206c\u202c\u202d\u206e\u200b\u202c\u206f\u206c\u200e\u200e\u202b\u200f\u200d\u200c\u206b\u200b\u200d\u202e\u200c\u202a\u206a\u206e\u206e\u202a\u206e\u202e\u206c\u202d\u206e\u200b\u202e\u202e(orig_\u202c\u206f\u202b\u202b\u206b\u200c\u206d\u206d\u202e\u206c\u202c\u202d\u206e\u200b\u202c\u206f\u206c\u200e\u200e\u202b\u200f\u200d\u200c\u206b\u200b\u200d\u202e\u200c\u202a\u206a\u206e\u206e\u202a\u206e\u202e\u206c\u202d\u206e\u200b\u202e\u202e orig, Object P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u202b\u206b\u202a\u202a\u200f\u200f\u200c\u200f\u202c\u202d\u202a\u202c\u200c\u202a\u206f\u206b\u200f\u200e\u200f\u202a\u202b\u200b\u200c\u202c\u206e\u200f\u206e\u202a\u200c\u200e\u202c\u202a\u200b\u202d\u206d\u200e\u206f\u202c\u206e\u202e(Object P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u202b\u206b\u202a\u202a\u200f\u200f\u200c\u200f\u202c\u202d\u202a\u202c\u200c\u202a\u206f\u206b\u200f\u200e\u200f\u202a\u202b\u200b\u200c\u202c\u206e\u200f\u206e\u202a\u200c\u200e\u202c\u202a\u200b\u202d\u206d\u200e\u206f\u202c\u206e\u202e(orig_\u202b\u206b\u202a\u202a\u200f\u200f\u200c\u200f\u202c\u202d\u202a\u202c\u200c\u202a\u206f\u206b\u200f\u200e\u200f\u202a\u202b\u200b\u200c\u202c\u206e\u200f\u206e\u202a\u200c\u200e\u202c\u202a\u200b\u202d\u206d\u200e\u206f\u202c\u206e\u202e orig, Object P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate RenderTexture orig_\u202c\u206c\u200e\u200c\u200e\u206e\u206d\u206c\u206b\u202b\u200b\u206c\u206b\u206f\u202c\u202b\u202b\u200b\u202c\u200e\u206a\u202a\u202e\u202d\u206d\u202b\u202a\u206e\u202a\u206d\u202b\u206a\u206e\u200f\u206b\u202b\u200d\u206b\u200b\u206d\u202e();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate RenderTexture hook_\u202c\u206c\u200e\u200c\u200e\u206e\u206d\u206c\u206b\u202b\u200b\u206c\u206b\u206f\u202c\u202b\u202b\u200b\u202c\u200e\u206a\u202a\u202e\u202d\u206d\u202b\u202a\u206e\u202a\u206d\u202b\u206a\u206e\u200f\u206b\u202b\u200d\u206b\u200b\u206d\u202e(orig_\u202c\u206c\u200e\u200c\u200e\u206e\u206d\u206c\u206b\u202b\u200b\u206c\u206b\u206f\u202c\u202b\u202b\u200b\u202c\u200e\u206a\u202a\u202e\u202d\u206d\u202b\u202a\u206e\u202a\u206d\u202b\u206a\u206e\u200f\u206b\u202b\u200d\u206b\u200b\u206d\u202e orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u206a\u206d\u200e\u206d\u202d\u206c\u202e\u202e\u200b\u200f\u202b\u206c\u206a\u206f\u206f\u200c\u200e\u200f\u200f\u200e\u206f\u202a\u202d\u200e\u202d\u200f\u206d\u206e\u202a\u206f\u200d\u202e\u206e\u202a\u206e\u200d\u200f\u206a\u200f\u206b\u202e(RenderTexture P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u206a\u206d\u200e\u206d\u202d\u206c\u202e\u202e\u200b\u200f\u202b\u206c\u206a\u206f\u206f\u200c\u200e\u200f\u200f\u200e\u206f\u202a\u202d\u200e\u202d\u200f\u206d\u206e\u202a\u206f\u200d\u202e\u206e\u202a\u206e\u200d\u200f\u206a\u200f\u206b\u202e(orig_\u206a\u206d\u200e\u206d\u202d\u206c\u202e\u202e\u200b\u200f\u202b\u206c\u206a\u206f\u206f\u200c\u200e\u200f\u200f\u200e\u206f\u202a\u202d\u200e\u202d\u200f\u206d\u206e\u202a\u206f\u200d\u202e\u206e\u202a\u206e\u200d\u200f\u206a\u200f\u206b\u202e orig, RenderTexture P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_\u206b\u200f\u206e\u200b\u206e\u200f\u206e\u206a\u200b\u200f\u206b\u206b\u206b\u202a\u200c\u206f\u200d\u200e\u202d\u202c\u206d\u206b\u202c\u202a\u200d\u206d\u206c\u202d\u202c\u202d\u202c\u206e\u200c\u202c\u202a\u200e\u206c\u206c\u200b\u202a\u202e(Texture P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_\u206b\u200f\u206e\u200b\u206e\u200f\u206e\u206a\u200b\u200f\u206b\u206b\u206b\u202a\u200c\u206f\u200d\u200e\u202d\u202c\u206d\u206b\u202c\u202a\u200d\u206d\u206c\u202d\u202c\u202d\u202c\u206e\u200c\u202c\u202a\u200e\u206c\u206c\u200b\u202a\u202e(orig_\u206b\u200f\u206e\u200b\u206e\u200f\u206e\u206a\u200b\u200f\u206b\u206b\u206b\u202a\u200c\u206f\u200d\u200e\u202d\u202c\u206d\u206b\u202c\u202a\u200d\u206d\u206c\u202d\u202c\u202d\u202c\u206e\u200c\u202c\u202a\u200e\u206c\u206c\u200b\u202a\u202e orig, Texture P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_\u206c\u202c\u202c\u206c\u200f\u202d\u200d\u200d\u206c\u206f\u202e\u206f\u202e\u206e\u206c\u202d\u202d\u206c\u200d\u202b\u200f\u200e\u200f\u202e\u206c\u200f\u200c\u202e\u202a\u200d\u206d\u206a\u202a\u206c\u206c\u206e\u202e\u200d\u206c\u206a\u202e(Texture P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_\u206c\u202c\u202c\u206c\u200f\u202d\u200d\u200d\u206c\u206f\u202e\u206f\u202e\u206e\u206c\u202d\u202d\u206c\u200d\u202b\u200f\u200e\u200f\u202e\u206c\u200f\u200c\u202e\u202a\u200d\u206d\u206a\u202a\u206c\u206c\u206e\u202e\u200d\u206c\u206a\u202e(orig_\u206c\u202c\u202c\u206c\u200f\u202d\u200d\u200d\u206c\u206f\u202e\u206f\u202e\u206e\u206c\u202d\u202d\u206c\u200d\u202b\u200f\u200e\u200f\u202e\u206c\u200f\u200c\u202e\u202a\u200d\u206d\u206a\u202a\u206c\u206c\u206e\u202e\u200d\u206c\u206a\u202e orig, Texture P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D orig_\u200e\u200e\u206a\u202b\u200f\u202c\u206d\u206f\u202e\u206d\u200d\u206d\u206c\u206c\u206b\u206d\u202d\u202e\u200c\u202e\u200b\u206c\u200d\u206d\u202d\u200c\u206e\u206c\u200c\u206a\u202e\u202c\u202b\u206d\u202c\u206f\u200e\u202e\u202b\u202e\u202e(int P_0, int P_1, TextureFormat P_2, bool P_3, bool P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D hook_\u200e\u200e\u206a\u202b\u200f\u202c\u206d\u206f\u202e\u206d\u200d\u206d\u206c\u206c\u206b\u206d\u202d\u202e\u200c\u202e\u200b\u206c\u200d\u206d\u202d\u200c\u206e\u206c\u200c\u206a\u202e\u202c\u202b\u206d\u202c\u206f\u200e\u202e\u202b\u202e\u202e(orig_\u200e\u200e\u206a\u202b\u200f\u202c\u206d\u206f\u202e\u206d\u200d\u206d\u206c\u206c\u206b\u206d\u202d\u202e\u200c\u202e\u200b\u206c\u200d\u206d\u202d\u200c\u206e\u206c\u200c\u206a\u202e\u202c\u202b\u206d\u202c\u206f\u200e\u202e\u202b\u202e\u202e orig, int P_1, int P_2, TextureFormat P_3, bool P_4, bool P_5);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_\u200f\u202a\u200b\u200f\u202c\u200c\u200e\u206a\u206a\u202e\u202c\u202b\u206d\u206a\u202c\u200b\u202c\u200f\u202c\u200d\u200f\u202e\u206e\u200c\u202d\u206f\u206c\u200b\u206a\u200b\u202a\u200c\u200c\u202b\u206f\u200c\u206c\u206e\u206d\u206f\u202e(Texture2D P_0, int P_1, int P_2, TextureFormat P_3, bool P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_\u200f\u202a\u200b\u200f\u202c\u200c\u200e\u206a\u206a\u202e\u202c\u202b\u206d\u206a\u202c\u200b\u202c\u200f\u202c\u200d\u200f\u202e\u206e\u200c\u202d\u206f\u206c\u200b\u206a\u200b\u202a\u200c\u200c\u202b\u206f\u200c\u206c\u206e\u206d\u206f\u202e(orig_\u200f\u202a\u200b\u200f\u202c\u200c\u200e\u206a\u206a\u202e\u202c\u202b\u206d\u206a\u202c\u200b\u202c\u200f\u202c\u200d\u200f\u202e\u206e\u200c\u202d\u206f\u206c\u200b\u206a\u200b\u202a\u200c\u200c\u202b\u206f\u200c\u206c\u206e\u206d\u206f\u202e orig, Texture2D P_1, int P_2, int P_3, TextureFormat P_4, bool P_5);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u202e\u202c\u206f\u202e\u202c\u206d\u200b\u202b\u206b\u200f\u202e\u206e\u200e\u200c\u202c\u206d\u206b\u206a\u206b\u200b\u200b\u206a\u206e\u206e\u202c\u200d\u206c\u206d\u200e\u200b\u200c\u202b\u206b\u206c\u200d\u206d\u206f\u200d\u206d\u206b\u202e(Texture2D P_0, Rect P_1, int P_2, int P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u202e\u202c\u206f\u202e\u202c\u206d\u200b\u202b\u206b\u200f\u202e\u206e\u200e\u200c\u202c\u206d\u206b\u206a\u206b\u200b\u200b\u206a\u206e\u206e\u202c\u200d\u206c\u206d\u200e\u200b\u200c\u202b\u206b\u206c\u200d\u206d\u206f\u200d\u206d\u206b\u202e(orig_\u202e\u202c\u206f\u202e\u202c\u206d\u200b\u202b\u206b\u200f\u202e\u206e\u200e\u200c\u202c\u206d\u206b\u206a\u206b\u200b\u200b\u206a\u206e\u206e\u202c\u200d\u206c\u206d\u200e\u200b\u200c\u202b\u206b\u206c\u200d\u206d\u206f\u200d\u206d\u206b\u202e orig, Texture2D P_1, Rect P_2, int P_3, int P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_\u202c\u206c\u206b\u202c\u200d\u206e\u206f\u200c\u202b\u200e\u202a\u206e\u200e\u200e\u202a\u200e\u202c\u206a\u202e\u200d\u200c\u200d\u202b\u206a\u200d\u200e\u206d\u200d\u200f\u202c\u202a\u202e\u202c\u206c\u206b\u206f\u206b\u206b\u206f\u206f\u202e();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_\u202c\u206c\u206b\u202c\u200d\u206e\u206f\u200c\u202b\u200e\u202a\u206e\u200e\u200e\u202a\u200e\u202c\u206a\u202e\u200d\u200c\u200d\u202b\u206a\u200d\u200e\u206d\u200d\u200f\u202c\u202a\u202e\u202c\u206c\u206b\u206f\u206b\u206b\u206f\u206f\u202e(orig_\u202c\u206c\u206b\u202c\u200d\u206e\u206f\u200c\u202b\u200e\u202a\u206e\u200e\u200e\u202a\u200e\u202c\u206a\u202e\u200d\u200c\u200d\u202b\u206a\u200d\u200e\u206d\u200d\u200f\u202c\u202a\u202e\u202c\u206c\u206b\u206f\u206b\u206b\u206f\u206f\u202e orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_\u200f\u206c\u202e\u206a\u206a\u202d\u200e\u200d\u200c\u206c\u202d\u200e\u200c\u206d\u206a\u202a\u202c\u202a\u200e\u200b\u206a\u202a\u202d\u200e\u200c\u206e\u202a\u206b\u206e\u200c\u202d\u206c\u206d\u202c\u202e\u202b\u202e\u202b\u200f\u202b\u202e(string P_0, object P_1, object P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_\u200f\u206c\u202e\u206a\u206a\u202d\u200e\u200d\u200c\u206c\u202d\u200e\u200c\u206d\u206a\u202a\u202c\u202a\u200e\u200b\u206a\u202a\u202d\u200e\u200c\u206e\u202a\u206b\u206e\u200c\u202d\u206c\u206d\u202c\u202e\u202b\u202e\u202b\u200f\u202b\u202e(orig_\u200f\u206c\u202e\u206a\u206a\u202d\u200e\u200d\u200c\u206c\u202d\u200e\u200c\u206d\u206a\u202a\u202c\u202a\u200e\u200b\u206a\u202a\u202d\u200e\u200c\u206e\u202a\u206b\u206e\u200c\u202d\u206c\u206d\u202c\u202e\u202b\u202e\u202b\u200f\u202b\u202e orig, string P_1, object P_2, object P_3);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Color[] orig_\u200d\u200e\u202c\u202c\u206b\u202a\u200b\u206f\u206d\u202c\u206b\u206f\u206f\u202e\u202e\u200d\u206c\u202a\u202a\u206f\u200d\u206c\u200d\u206d\u206a\u206e\u202d\u202a\u206d\u206d\u202c\u202a\u206f\u200d\u206f\u202e\u202a\u200b\u200e\u206f\u202e(Texture2D P_0, int P_1, int P_2, int P_3, int P_4);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Color[] hook_\u200d\u200e\u202c\u202c\u206b\u202a\u200b\u206f\u206d\u202c\u206b\u206f\u206f\u202e\u202e\u200d\u206c\u202a\u202a\u206f\u200d\u206c\u200d\u206d\u206a\u206e\u202d\u202a\u206d\u206d\u202c\u202a\u206f\u200d\u206f\u202e\u202a\u200b\u200e\u206f\u202e(orig_\u200d\u200e\u202c\u202c\u206b\u202a\u200b\u206f\u206d\u202c\u206b\u206f\u206f\u202e\u202e\u200d\u206c\u202a\u202a\u206f\u200d\u206c\u200d\u206d\u206a\u206e\u202d\u202a\u206d\u206d\u202c\u202a\u206f\u200d\u206f\u202e\u202a\u200b\u200e\u206f\u202e orig, Texture2D P_1, int P_2, int P_3, int P_4, int P_5);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate TextureFormat orig_\u200b\u206f\u206e\u200d\u206a\u202a\u206a\u206d\u206f\u200f\u200e\u202b\u202e\u200d\u202d\u200e\u202c\u206e\u200f\u200b\u202d\u202c\u202b\u200c\u202d\u206c\u200d\u202b\u206a\u200f\u206e\u202b\u202a\u200c\u206f\u206a\u200e\u202e\u202a\u200d\u202e(Texture2D P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate TextureFormat hook_\u200b\u206f\u206e\u200d\u206a\u202a\u206a\u206d\u206f\u200f\u200e\u202b\u202e\u200d\u202d\u200e\u202c\u206e\u200f\u200b\u202d\u202c\u202b\u200c\u202d\u206c\u200d\u202b\u206a\u200f\u206e\u202b\u202a\u200c\u206f\u206a\u200e\u202e\u202a\u200d\u202e(orig_\u200b\u206f\u206e\u200d\u206a\u202a\u206a\u206d\u206f\u200f\u200e\u202b\u202e\u200d\u202d\u200e\u202c\u206e\u200f\u200b\u202d\u202c\u202b\u200c\u202d\u206c\u200d\u202b\u206a\u200f\u206e\u202b\u202a\u200c\u206f\u206a\u200e\u202e\u202a\u200d\u202e orig, Texture2D P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u206d\u200d\u206b\u200c\u200e\u206b\u202e\u202e\u206d\u202e\u206c\u202d\u206d\u200e\u206b\u206a\u206f\u202b\u202a\u202c\u206a\u202e\u206a\u202c\u206a\u200e\u202b\u200c\u200c\u200e\u202a\u206f\u200b\u200b\u206f\u200f\u200c\u206a\u202c\u200d\u202e(Texture P_0, TextureWrapMode P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u206d\u200d\u206b\u200c\u200e\u206b\u202e\u202e\u206d\u202e\u206c\u202d\u206d\u200e\u206b\u206a\u206f\u202b\u202a\u202c\u206a\u202e\u206a\u202c\u206a\u200e\u202b\u200c\u200c\u200e\u202a\u206f\u200b\u200b\u206f\u200f\u200c\u206a\u202c\u200d\u202e(orig_\u206d\u200d\u206b\u200c\u200e\u206b\u202e\u202e\u206d\u202e\u206c\u202d\u206d\u200e\u206b\u206a\u206f\u202b\u202a\u202c\u206a\u202e\u206a\u202c\u206a\u200e\u202b\u200c\u200c\u200e\u202a\u206f\u200b\u200b\u206f\u200f\u200c\u206a\u202c\u200d\u202e orig, Texture P_1, TextureWrapMode P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate FilterMode orig_\u200e\u200e\u206f\u200c\u206d\u202c\u202d\u202b\u202e\u206c\u200d\u200e\u206a\u202e\u206c\u202c\u206e\u200b\u206d\u200b\u202d\u200f\u206a\u202d\u206e\u202b\u202c\u202c\u206f\u206e\u200d\u206d\u200d\u202d\u200d\u202c\u206a\u206f\u200d\u202a\u202e(Texture P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate FilterMode hook_\u200e\u200e\u206f\u200c\u206d\u202c\u202d\u202b\u202e\u206c\u200d\u200e\u206a\u202e\u206c\u202c\u206e\u200b\u206d\u200b\u202d\u200f\u206a\u202d\u206e\u202b\u202c\u202c\u206f\u206e\u200d\u206d\u200d\u202d\u200d\u202c\u206a\u206f\u200d\u202a\u202e(orig_\u200e\u200e\u206f\u200c\u206d\u202c\u202d\u202b\u202e\u206c\u200d\u200e\u206a\u202e\u206c\u202c\u206e\u200b\u206d\u200b\u202d\u200f\u206a\u202d\u206e\u202b\u202c\u202c\u206f\u206e\u200d\u206d\u200d\u202d\u200d\u202c\u206a\u206f\u200d\u202a\u202e orig, Texture P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u202c\u206d\u200f\u200c\u206e\u202c\u200b\u202b\u206f\u206a\u200c\u202e\u206a\u202b\u202a\u200b\u206f\u202b\u206b\u202a\u206c\u202b\u202e\u202b\u202e\u206b\u202d\u202b\u206c\u202d\u206c\u202a\u200f\u200e\u202d\u206a\u206f\u202b\u206d\u206a\u202e(Texture P_0, FilterMode P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u202c\u206d\u200f\u200c\u206e\u202c\u200b\u202b\u206f\u206a\u200c\u202e\u206a\u202b\u202a\u200b\u206f\u202b\u206b\u202a\u206c\u202b\u202e\u202b\u202e\u206b\u202d\u202b\u206c\u202d\u206c\u202a\u200f\u200e\u202d\u206a\u206f\u202b\u206d\u206a\u202e(orig_\u202c\u206d\u200f\u200c\u206e\u202c\u200b\u202b\u206f\u206a\u200c\u202e\u206a\u202b\u202a\u200b\u206f\u202b\u206b\u202a\u206c\u202b\u202e\u202b\u202e\u206b\u202d\u202b\u206c\u202d\u206c\u202a\u200f\u200e\u202d\u206a\u206f\u202b\u206d\u206a\u202e orig, Texture P_1, FilterMode P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_\u206e\u202e\u200f\u206b\u200e\u200c\u206d\u202a\u206b\u200d\u202e\u206a\u200c\u206e\u206f\u200e\u206e\u200d\u200d\u202d\u200c\u206f\u200c\u200b\u202d\u202a\u206f\u202b\u206e\u206c\u200b\u206b\u202d\u206b\u200f\u200b\u206b\u206b\u200e\u206d\u202e(Object P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_\u206e\u202e\u200f\u206b\u200e\u200c\u206d\u202a\u206b\u200d\u202e\u206a\u200c\u206e\u206f\u200e\u206e\u200d\u200d\u202d\u200c\u206f\u200c\u200b\u202d\u202a\u206f\u202b\u206e\u206c\u200b\u206b\u202d\u206b\u200f\u200b\u206b\u206b\u200e\u206d\u202e(orig_\u206e\u202e\u200f\u206b\u200e\u200c\u206d\u202a\u206b\u200d\u202e\u206a\u200c\u206e\u206f\u200e\u206e\u200d\u200d\u202d\u200c\u206f\u200c\u200b\u202d\u202a\u206f\u202b\u206e\u206c\u200b\u206b\u202d\u206b\u200f\u200b\u206b\u206b\u200e\u206d\u202e orig, Object P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_\u200c\u200f\u206d\u206b\u200d\u202e\u202c\u200f\u202b\u200f\u200f\u206b\u202a\u202a\u202d\u202b\u206e\u202e\u202d\u200e\u200f\u200d\u206b\u200f\u200c\u202e\u200b\u202c\u202c\u200e\u206f\u206e\u200d\u200b\u206e\u202c\u206d\u200e\u206a\u202e\u202e(string P_0, string P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_\u200c\u200f\u206d\u206b\u200d\u202e\u202c\u200f\u202b\u200f\u200f\u206b\u202a\u202a\u202d\u202b\u206e\u202e\u202d\u200e\u200f\u200d\u206b\u200f\u200c\u202e\u200b\u202c\u202c\u200e\u206f\u206e\u200d\u200b\u206e\u202c\u206d\u200e\u206a\u202e\u202e(orig_\u200c\u200f\u206d\u206b\u200d\u202e\u202c\u200f\u202b\u200f\u200f\u206b\u202a\u202a\u202d\u202b\u206e\u202e\u202d\u200e\u200f\u200d\u206b\u200f\u200c\u202e\u200b\u202c\u202c\u200e\u206f\u206e\u200d\u200b\u206e\u202c\u206d\u200e\u206a\u202e\u202e orig, string P_1, string P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_\u206e\u206b\u206b\u206b\u206c\u200b\u202e\u200e\u202b\u200d\u206b\u200c\u202b\u202c\u202c\u206f\u202a\u200e\u202e\u206c\u202c\u206b\u202c\u202c\u200b\u202a\u200b\u202c\u200d\u206c\u200b\u206d\u202e\u200e\u202d\u206d\u202b\u200d\u200c\u206b\u202e(Object P_0, string P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_\u206e\u206b\u206b\u206b\u206c\u200b\u202e\u200e\u202b\u200d\u206b\u200c\u202b\u202c\u202c\u206f\u202a\u200e\u202e\u206c\u202c\u206b\u202c\u202c\u200b\u202a\u200b\u202c\u200d\u206c\u200b\u206d\u202e\u200e\u202d\u206d\u202b\u200d\u200c\u206b\u202e(orig_\u206e\u206b\u206b\u206b\u206c\u200b\u202e\u200e\u202b\u200d\u206b\u200c\u202b\u202c\u202c\u206f\u202a\u200e\u202e\u206c\u202c\u206b\u202c\u202c\u200b\u202a\u200b\u202c\u200d\u206c\u200b\u206d\u202e\u200e\u202d\u206d\u202b\u200d\u200c\u206b\u202e orig, Object P_1, string P_2);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_\u202d\u200e\u200e\u200e\u200d\u206c\u200c\u206b\u200c\u200c\u202a\u202d\u202a\u200d\u206b\u200e\u206f\u202a\u206f\u206c\u202c\u206b\u206f\u206a\u202e\u200b\u206b\u202a\u202a\u206d\u202b\u206f\u206b\u200f\u200e\u200d\u202d\u200d\u202e\u200f\u202e(TerrainData P_0);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_\u202d\u200e\u200e\u200e\u200d\u206c\u200c\u206b\u200c\u200c\u202a\u202d\u202a\u200d\u206b\u200e\u206f\u202a\u206f\u206c\u202c\u206b\u206f\u206a\u202e\u200b\u206b\u202a\u202a\u206d\u202b\u206f\u206b\u200f\u200e\u200d\u202d\u200d\u202e\u200f\u202e(orig_\u202d\u200e\u200e\u200e\u200d\u206c\u200c\u206b\u200c\u200c\u202a\u202d\u202a\u200d\u206b\u200e\u206f\u202a\u206f\u206c\u202c\u206b\u206f\u206a\u202e\u200b\u206b\u202a\u202a\u206d\u202b\u206f\u206b\u200f\u200e\u200d\u202d\u200d\u202e\u200f\u202e orig, TerrainData P_1);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_\u206e\u200c\u206b\u202e\u202b\u200f\u206c\u202a\u200b\u206b\u202b\u206c\u206b\u206e\u206e\u206e\u206c\u206c\u206b\u202b\u200c\u202a\u206a\u206d\u206a\u206b\u206d\u200e\u206c\u202e\u206e\u200e\u206a\u200e\u200c\u200b\u206b\u206f\u200d\u206e\u202e();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_\u206e\u200c\u206b\u202e\u202b\u200f\u206c\u202a\u200b\u206b\u202b\u206c\u206b\u206e\u206e\u206e\u206c\u206c\u206b\u202b\u200c\u202a\u206a\u206d\u206a\u206b\u206d\u200e\u206c\u202e\u206e\u200e\u206a\u200e\u200c\u200b\u206b\u206f\u200d\u206e\u202e(orig_\u206e\u200c\u206b\u202e\u202b\u200f\u206c\u202a\u200b\u206b\u202b\u206c\u206b\u206e\u206e\u206e\u206c\u206c\u206b\u202b\u200c\u202a\u206a\u206d\u206a\u206b\u206d\u200e\u206c\u202e\u206e\u200e\u206a\u200e\u200c\u200b\u206b\u206f\u200d\u206e\u202e orig);

		public static class \u206b\u206a\u200c\u206b\u206a\u202a\u200d\u202a\u200f\u202b\u200b\u206b\u200d\u202c\u206c\u206c\u202a\u206e\u200c\u206d\u202a\u206b\u206c\u200e\u200c\u202b\u206e\u206e\u200b\u206f\u200f\u200e\u202e\u206b\u202d\u200f\u200b\u202a\u206d\u202c\u202e
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_ctor(object self, TerrainData P_1, bool P_2, bool P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_ctor(orig_ctor orig, object self, TerrainData P_2, bool P_3, bool P_4);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] orig_\u200d\u202d\u206a\u202d\u206e\u206e\u206e\u200f\u206c\u206c\u202a\u200f\u200f\u202a\u206a\u202e\u206f\u206f\u206c\u202e\u206c\u200c\u206b\u202e\u206a\u200f\u206b\u200c\u200f\u200d\u200e\u202b\u200f\u200c\u206c\u206d\u202c\u206f\u202a\u200e\u202e(object self, int P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] hook_\u200d\u202d\u206a\u202d\u206e\u206e\u206e\u200f\u206c\u206c\u202a\u200f\u200f\u202a\u206a\u202e\u206f\u206f\u206c\u202e\u206c\u200c\u206b\u202e\u206a\u200f\u206b\u200c\u200f\u200d\u200e\u202b\u200f\u200c\u206c\u206d\u202c\u206f\u202a\u200e\u202e(orig_\u200d\u202d\u206a\u202d\u206e\u206e\u206e\u200f\u206c\u206c\u202a\u200f\u200f\u202a\u206a\u202e\u206f\u206f\u206c\u202e\u206c\u200c\u206b\u202e\u206a\u200f\u206b\u200c\u200f\u200d\u200e\u202b\u200f\u200c\u206c\u206d\u202c\u206f\u202a\u200e\u202e orig, object self, int P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] orig_\u202b\u200f\u206d\u202b\u202e\u206b\u206c\u202d\u206d\u200e\u202c\u206d\u206f\u202b\u200f\u202a\u200c\u206c\u206e\u206b\u202c\u202c\u200b\u200c\u202c\u200f\u206c\u202a\u202b\u206c\u200d\u202c\u202b\u200c\u206b\u202b\u200f\u200b\u206c\u206e\u202e(object self, int P_1, int P_2, int P_3, int P_4, int P_5);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] hook_\u202b\u200f\u206d\u202b\u202e\u206b\u206c\u202d\u206d\u200e\u202c\u206d\u206f\u202b\u200f\u202a\u200c\u206c\u206e\u206b\u202c\u202c\u200b\u200c\u202c\u200f\u206c\u202a\u202b\u206c\u200d\u202c\u202b\u200c\u206b\u202b\u200f\u200b\u206c\u206e\u202e(orig_\u202b\u200f\u206d\u202b\u202e\u206b\u206c\u202d\u206d\u200e\u202c\u206d\u206f\u202b\u200f\u202a\u200c\u206c\u206e\u206b\u202c\u202c\u200b\u200c\u202c\u200f\u206c\u202a\u202b\u206c\u200d\u202c\u202b\u200c\u206b\u202b\u200f\u200b\u206c\u206e\u202e orig, object self, int P_2, int P_3, int P_4, int P_5, int P_6);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] orig_\u206e\u202e\u206d\u206f\u200c\u202d\u206d\u202d\u200b\u200b\u200c\u206c\u206f\u202d\u200b\u206e\u202d\u200c\u202a\u206b\u202e\u202c\u202a\u202e\u206c\u200b\u202c\u200d\u202b\u200e\u206a\u202e\u206f\u202e\u202b\u202d\u206e\u206d\u200c\u200d\u202e(object self, int P_1, int P_2, int P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] hook_\u206e\u202e\u206d\u206f\u200c\u202d\u206d\u202d\u200b\u200b\u200c\u206c\u206f\u202d\u200b\u206e\u202d\u200c\u202a\u206b\u202e\u202c\u202a\u202e\u206c\u200b\u202c\u200d\u202b\u200e\u206a\u202e\u206f\u202e\u202b\u202d\u206e\u206d\u200c\u200d\u202e(orig_\u206e\u202e\u206d\u206f\u200c\u202d\u206d\u202d\u200b\u200b\u200c\u206c\u206f\u202d\u200b\u206e\u202d\u200c\u202a\u206b\u202e\u202c\u202a\u202e\u206c\u200b\u202c\u200d\u202b\u200e\u206a\u202e\u206f\u202e\u202b\u202d\u206e\u206d\u200c\u200d\u202e orig, object self, int P_2, int P_3, int P_4);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D orig_\u206e\u206e\u200e\u206d\u200d\u200d\u200b\u206f\u206f\u200b\u206b\u206c\u206c\u202a\u206e\u206e\u206d\u202e\u206f\u202d\u206c\u206b\u206f\u202d\u202a\u202b\u206d\u206d\u202d\u200d\u200f\u202e\u202e\u206b\u200d\u206c\u200e\u206a\u200f\u202a\u202e(object self, int P_1, bool P_2, bool P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D hook_\u206e\u206e\u200e\u206d\u200d\u200d\u200b\u206f\u206f\u200b\u206b\u206c\u206c\u202a\u206e\u206e\u206d\u202e\u206f\u202d\u206c\u206b\u206f\u202d\u202a\u202b\u206d\u206d\u202d\u200d\u200f\u202e\u202e\u206b\u200d\u206c\u200e\u206a\u200f\u202a\u202e(orig_\u206e\u206e\u200e\u206d\u200d\u200d\u200b\u206f\u206f\u200b\u206b\u206c\u206c\u202a\u206e\u206e\u206d\u202e\u206f\u202d\u206c\u206b\u206f\u202d\u202a\u202b\u206d\u206d\u202d\u200d\u200f\u202e\u202e\u206b\u200d\u206c\u200e\u206a\u200f\u202a\u202e orig, object self, int P_2, bool P_3, bool P_4);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D orig_\u206d\u200c\u200d\u206c\u202a\u206c\u200e\u202b\u200d\u206e\u202b\u200d\u202a\u202d\u206b\u202b\u200b\u206a\u200f\u206d\u200f\u200f\u206a\u206b\u202a\u206c\u202a\u200e\u200e\u200e\u202c\u202b\u206e\u200c\u202d\u206b\u202e\u200b\u200b\u206f\u202e(object self, int P_1, bool P_2, bool P_3, int P_4, int P_5, int P_6, int P_7);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D hook_\u206d\u200c\u200d\u206c\u202a\u206c\u200e\u202b\u200d\u206e\u202b\u200d\u202a\u202d\u206b\u202b\u200b\u206a\u200f\u206d\u200f\u200f\u206a\u206b\u202a\u206c\u202a\u200e\u200e\u200e\u202c\u202b\u206e\u200c\u202d\u206b\u202e\u200b\u200b\u206f\u202e(orig_\u206d\u200c\u200d\u206c\u202a\u206c\u200e\u202b\u200d\u206e\u202b\u200d\u202a\u202d\u206b\u202b\u200b\u206a\u200f\u206d\u200f\u200f\u206a\u206b\u202a\u206c\u202a\u200e\u200e\u200e\u202c\u202b\u206e\u200c\u202d\u206b\u202e\u200b\u200b\u206f\u202e orig, object self, int P_2, bool P_3, bool P_4, int P_5, int P_6, int P_7, int P_8);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] orig_\u206c\u202d\u200c\u206d\u202d\u202c\u206a\u206a\u202e\u206d\u206c\u206e\u200b\u206d\u202c\u202b\u202d\u206a\u200c\u206f\u206a\u202e\u202d\u206f\u200f\u206b\u200f\u202e\u202d\u200c\u202a\u200f\u200b\u202d\u202a\u206c\u202c\u206c\u206b\u202a\u202e(object self, int P_1, bool P_2, bool P_3, int P_4, int P_5);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] hook_\u206c\u202d\u200c\u206d\u202d\u202c\u206a\u206a\u202e\u206d\u206c\u206e\u200b\u206d\u202c\u202b\u202d\u206a\u200c\u206f\u206a\u202e\u202d\u206f\u200f\u206b\u200f\u202e\u202d\u200c\u202a\u200f\u200b\u202d\u202a\u206c\u202c\u206c\u206b\u202a\u202e(orig_\u206c\u202d\u200c\u206d\u202d\u202c\u206a\u206a\u202e\u206d\u206c\u206e\u200b\u206d\u202c\u202b\u202d\u206a\u200c\u206f\u206a\u202e\u202d\u206f\u200f\u206b\u200f\u202e\u202d\u200c\u202a\u200f\u200b\u202d\u202a\u206c\u202c\u206c\u206b\u202a\u202e orig, object self, int P_2, bool P_3, bool P_4, int P_5, int P_6);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D orig_\u200f\u202a\u206e\u206e\u202d\u202c\u206d\u200d\u202b\u202b\u200c\u202b\u200e\u200b\u202b\u206b\u206e\u202d\u202c\u206e\u206f\u202a\u202c\u206f\u200b\u202e\u206c\u200e\u206c\u202a\u200c\u206c\u200e\u202d\u206d\u206e\u202c\u200c\u202d\u206c\u202e(object self, int P_1, bool P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D hook_\u200f\u202a\u206e\u206e\u202d\u202c\u206d\u200d\u202b\u202b\u200c\u202b\u200e\u200b\u202b\u206b\u206e\u202d\u202c\u206e\u206f\u202a\u202c\u206f\u200b\u202e\u206c\u200e\u206c\u202a\u200c\u206c\u200e\u202d\u206d\u206e\u202c\u200c\u202d\u206c\u202e(orig_\u200f\u202a\u206e\u206e\u202d\u202c\u206d\u200d\u202b\u202b\u200c\u202b\u200e\u200b\u202b\u206b\u206e\u202d\u202c\u206e\u206f\u202a\u202c\u206f\u200b\u202e\u206c\u200e\u206c\u202a\u200c\u206c\u200e\u202d\u206d\u206e\u202c\u200c\u202d\u206c\u202e orig, object self, int P_2, bool P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D orig_\u200d\u200b\u206a\u202b\u200f\u202b\u202c\u200c\u200e\u206d\u206c\u206d\u206b\u202a\u202d\u202b\u202d\u200d\u202a\u206c\u200d\u206d\u206a\u202d\u202e\u202b\u206c\u200b\u206f\u202e\u206e\u202e\u200d\u206a\u202b\u202a\u202d\u206a\u202e\u206a\u202e(object self, int P_1, bool P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D hook_\u200d\u200b\u206a\u202b\u200f\u202b\u202c\u200c\u200e\u206d\u206c\u206d\u206b\u202a\u202d\u202b\u202d\u200d\u202a\u206c\u200d\u206d\u206a\u202d\u202e\u202b\u206c\u200b\u206f\u202e\u206e\u202e\u200d\u206a\u202b\u202a\u202d\u206a\u202e\u206a\u202e(orig_\u200d\u200b\u206a\u202b\u200f\u202b\u202c\u200c\u200e\u206d\u206c\u206d\u206b\u202a\u202d\u202b\u202d\u200d\u202a\u206c\u200d\u206d\u206a\u202d\u202e\u202b\u206c\u200b\u206f\u202e\u206e\u202e\u200d\u206a\u202b\u202a\u202d\u206a\u202e\u206a\u202e orig, object self, int P_2, bool P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D orig_\u202e\u202e\u202c\u206e\u206c\u202d\u200e\u206e\u200c\u202c\u206b\u206a\u202a\u200f\u200d\u202c\u206c\u206c\u202d\u200e\u200e\u200f\u206a\u202c\u200f\u200b\u206b\u200d\u202d\u200c\u206d\u202e\u200c\u200d\u206a\u200e\u206b\u202d\u200d\u200e\u202e(object self, int P_1, bool P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D hook_\u202e\u202e\u202c\u206e\u206c\u202d\u200e\u206e\u200c\u202c\u206b\u206a\u202a\u200f\u200d\u202c\u206c\u206c\u202d\u200e\u200e\u200f\u206a\u202c\u200f\u200b\u206b\u200d\u202d\u200c\u206d\u202e\u200c\u200d\u206a\u200e\u206b\u202d\u200d\u200e\u202e(orig_\u202e\u202e\u202c\u206e\u206c\u202d\u200e\u206e\u200c\u202c\u206b\u206a\u202a\u200f\u200d\u202c\u206c\u206c\u202d\u200e\u200e\u200f\u206a\u202c\u200f\u200b\u206b\u200d\u202d\u200c\u206d\u202e\u200c\u200d\u206a\u200e\u206b\u202d\u200d\u200e\u202e orig, object self, int P_2, bool P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D orig_\u202e\u206e\u202d\u206e\u200b\u200e\u202b\u206c\u206f\u200c\u202c\u200d\u200c\u200f\u202a\u200c\u200c\u200f\u200b\u202e\u206e\u206e\u202e\u202b\u200d\u200c\u206e\u206a\u206a\u200c\u202c\u200b\u200b\u206f\u206f\u206b\u206c\u202b\u206e\u206c\u202e(object self, int P_1, bool P_2, int P_3, int P_4, int P_5, int P_6);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D hook_\u202e\u206e\u202d\u206e\u200b\u200e\u202b\u206c\u206f\u200c\u202c\u200d\u200c\u200f\u202a\u200c\u200c\u200f\u200b\u202e\u206e\u206e\u202e\u202b\u200d\u200c\u206e\u206a\u206a\u200c\u202c\u200b\u200b\u206f\u206f\u206b\u206c\u202b\u206e\u206c\u202e(orig_\u202e\u206e\u202d\u206e\u200b\u200e\u202b\u206c\u206f\u200c\u202c\u200d\u200c\u200f\u202a\u200c\u200c\u200f\u200b\u202e\u206e\u206e\u202e\u202b\u200d\u200c\u206e\u206a\u206a\u200c\u202c\u200b\u200b\u206f\u206f\u206b\u206c\u202b\u206e\u206c\u202e orig, object self, int P_2, bool P_3, int P_4, int P_5, int P_6, int P_7);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] orig_\u200f\u200c\u202e\u202c\u202c\u206c\u202c\u206e\u202e\u200d\u200b\u200d\u200f\u200f\u202b\u200e\u202e\u200e\u200f\u202d\u202d\u200f\u202a\u206d\u202a\u200b\u206c\u200b\u206c\u206c\u206e\u200e\u202e\u206a\u202d\u200b\u202c\u206a\u200f\u200d\u202e(object self, int P_1, bool P_2, int P_3, int P_4);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] hook_\u200f\u200c\u202e\u202c\u202c\u206c\u202c\u206e\u202e\u200d\u200b\u200d\u200f\u200f\u202b\u200e\u202e\u200e\u200f\u202d\u202d\u200f\u202a\u206d\u202a\u200b\u206c\u200b\u206c\u206c\u206e\u200e\u202e\u206a\u202d\u200b\u202c\u206a\u200f\u200d\u202e(orig_\u200f\u200c\u202e\u202c\u202c\u206c\u202c\u206e\u202e\u200d\u200b\u200d\u200f\u200f\u202b\u200e\u202e\u200e\u200f\u202d\u202d\u200f\u202a\u206d\u202a\u200b\u206c\u200b\u206c\u206c\u206e\u200e\u202e\u206a\u202d\u200b\u202c\u206a\u200f\u200d\u202e orig, object self, int P_2, bool P_3, int P_4, int P_5);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D orig_\u206b\u206e\u200b\u202c\u202a\u202b\u202d\u202a\u200d\u200f\u206b\u200f\u206b\u200f\u202b\u202d\u202a\u200f\u200e\u206a\u202c\u202e\u202a\u206c\u200d\u202a\u202a\u200f\u200d\u200f\u200c\u206a\u206e\u206e\u202b\u206e\u206b\u200f\u206d\u200c\u202e(object self, int P_1, bool P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D hook_\u206b\u206e\u200b\u202c\u202a\u202b\u202d\u202a\u200d\u200f\u206b\u200f\u206b\u200f\u202b\u202d\u202a\u200f\u200e\u206a\u202c\u202e\u202a\u206c\u200d\u202a\u202a\u200f\u200d\u200f\u200c\u206a\u206e\u206e\u202b\u206e\u206b\u200f\u206d\u200c\u202e(orig_\u206b\u206e\u200b\u202c\u202a\u202b\u202d\u202a\u200d\u200f\u206b\u200f\u206b\u200f\u202b\u202d\u202a\u200f\u200e\u206a\u202c\u202e\u202a\u206c\u200d\u202a\u202a\u200f\u200d\u200f\u200c\u206a\u206e\u206e\u202b\u206e\u206b\u200f\u206d\u200c\u202e orig, object self, int P_2, bool P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D orig_\u200c\u206e\u200e\u200d\u200b\u202e\u200f\u206e\u202c\u206a\u206f\u206c\u202b\u206d\u202c\u202e\u206e\u206e\u206a\u202d\u200f\u202d\u200f\u202d\u202a\u200d\u202d\u200e\u200b\u206a\u202c\u206d\u200c\u206d\u206e\u200c\u200d\u200c\u202d\u200f\u202e(object self, int P_1, bool P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D hook_\u200c\u206e\u200e\u200d\u200b\u202e\u200f\u206e\u202c\u206a\u206f\u206c\u202b\u206d\u202c\u202e\u206e\u206e\u206a\u202d\u200f\u202d\u200f\u202d\u202a\u200d\u202d\u200e\u200b\u206a\u202c\u206d\u200c\u206d\u206e\u200c\u200d\u200c\u202d\u200f\u202e(orig_\u200c\u206e\u200e\u200d\u200b\u202e\u200f\u206e\u202c\u206a\u206f\u206c\u202b\u206d\u202c\u202e\u206e\u206e\u206a\u202d\u200f\u202d\u200f\u202d\u202a\u200d\u202d\u200e\u200b\u206a\u202c\u206d\u200c\u206d\u206e\u200c\u200d\u200c\u202d\u200f\u202e orig, object self, int P_2, bool P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D orig_\u200d\u202c\u206b\u200e\u202b\u200b\u202d\u206c\u206f\u202c\u202d\u206a\u202e\u200b\u202b\u202e\u202a\u200f\u206a\u202a\u200c\u206a\u202d\u200c\u206b\u202b\u206c\u206c\u200b\u206c\u200f\u202e\u200f\u200e\u200f\u206e\u200e\u206d\u200f\u200e\u202e(object self, int P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D hook_\u200d\u202c\u206b\u200e\u202b\u200b\u202d\u206c\u206f\u202c\u202d\u206a\u202e\u200b\u202b\u202e\u202a\u200f\u206a\u202a\u200c\u206a\u202d\u200c\u206b\u202b\u206c\u206c\u200b\u206c\u200f\u202e\u200f\u200e\u200f\u206e\u200e\u206d\u200f\u200e\u202e(orig_\u200d\u202c\u206b\u200e\u202b\u200b\u202d\u206c\u206f\u202c\u202d\u206a\u202e\u200b\u202b\u202e\u202a\u200f\u206a\u202a\u200c\u206a\u202d\u200c\u206b\u202b\u206c\u206c\u200b\u206c\u200f\u202e\u200f\u200e\u200f\u206e\u200e\u206d\u200f\u200e\u202e orig, object self, int P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D orig_\u200c\u202c\u206d\u200e\u206f\u206a\u202d\u206a\u206e\u202c\u202b\u206d\u200c\u206f\u202c\u200c\u200f\u200c\u202d\u200f\u200b\u206b\u200f\u206b\u202a\u200d\u200e\u202c\u202b\u200e\u200e\u202b\u206e\u200b\u200e\u206c\u202a\u200f\u200d\u206a\u202e(object self, int P_1, int P_2, int P_3, int P_4, int P_5);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D hook_\u200c\u202c\u206d\u200e\u206f\u206a\u202d\u206a\u206e\u202c\u202b\u206d\u200c\u206f\u202c\u200c\u200f\u200c\u202d\u200f\u200b\u206b\u200f\u206b\u202a\u200d\u200e\u202c\u202b\u200e\u200e\u202b\u206e\u200b\u200e\u206c\u202a\u200f\u200d\u206a\u202e(orig_\u200c\u202c\u206d\u200e\u206f\u206a\u202d\u206a\u206e\u202c\u202b\u206d\u200c\u206f\u202c\u200c\u200f\u200c\u202d\u200f\u200b\u206b\u200f\u206b\u202a\u200d\u200e\u202c\u202b\u200e\u200e\u202b\u206e\u200b\u200e\u206c\u202a\u200f\u200d\u206a\u202e orig, object self, int P_2, int P_3, int P_4, int P_5, int P_6);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] orig_\u200e\u200f\u206f\u202d\u202e\u200d\u202b\u202d\u206d\u206b\u200b\u202d\u200e\u202a\u200b\u200b\u206d\u200e\u200b\u200c\u202e\u202c\u202d\u202a\u202c\u202e\u200e\u206a\u206d\u202e\u206f\u200d\u200e\u206c\u200c\u202c\u202b\u202c\u202c\u202b\u202e(object self, int P_1, int P_2, int P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] hook_\u200e\u200f\u206f\u202d\u202e\u200d\u202b\u202d\u206d\u206b\u200b\u202d\u200e\u202a\u200b\u200b\u206d\u200e\u200b\u200c\u202e\u202c\u202d\u202a\u202c\u202e\u200e\u206a\u206d\u202e\u206f\u200d\u200e\u206c\u200c\u202c\u202b\u202c\u202c\u202b\u202e(orig_\u200e\u200f\u206f\u202d\u202e\u200d\u202b\u202d\u206d\u206b\u200b\u202d\u200e\u202a\u200b\u200b\u206d\u200e\u200b\u200c\u202e\u202c\u202d\u202a\u202c\u202e\u200e\u206a\u206d\u202e\u206f\u200d\u200e\u206c\u200c\u202c\u202b\u202c\u202c\u202b\u202e orig, object self, int P_2, int P_3, int P_4);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Vector2 orig_\u200b\u206a\u206b\u206c\u206b\u200d\u200f\u206d\u206d\u202a\u206f\u200b\u206c\u206f\u202b\u200c\u200b\u200c\u206e\u206a\u202d\u206d\u200d\u200c\u202a\u202b\u200b\u206e\u200d\u202d\u202c\u206a\u200d\u202e\u202b\u206f\u206d\u200b\u206c\u202e\u202e(object self);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Vector2 hook_\u200b\u206a\u206b\u206c\u206b\u200d\u200f\u206d\u206d\u202a\u206f\u200b\u206c\u206f\u202b\u200c\u200b\u200c\u206e\u206a\u202d\u206d\u200d\u200c\u202a\u202b\u200b\u206e\u200d\u202d\u202c\u206a\u200d\u202e\u202b\u206f\u206d\u200b\u206c\u202e\u202e(orig_\u200b\u206a\u206b\u206c\u206b\u200d\u200f\u206d\u206d\u202a\u206f\u200b\u206c\u206f\u202b\u200c\u200b\u200c\u206e\u206a\u202d\u206d\u200d\u200c\u202a\u202b\u200b\u206e\u200d\u202d\u202c\u206a\u200d\u202e\u202b\u206f\u206d\u200b\u206c\u202e\u202e orig, object self);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool orig_\u200c\u202a\u206b\u200d\u200f\u206e\u200c\u200c\u206e\u202a\u200b\u206b\u206a\u206d\u200c\u200c\u200b\u202b\u202e\u200f\u200f\u206f\u206b\u200d\u200b\u202d\u206c\u206d\u200f\u206a\u206f\u200f\u206b\u200c\u206f\u202e\u200d\u206f\u206d\u206d\u202e(Object P_0, Object P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool hook_\u200c\u202a\u206b\u200d\u200f\u206e\u200c\u200c\u206e\u202a\u200b\u206b\u206a\u206d\u200c\u200c\u200b\u202b\u202e\u200f\u200f\u206f\u206b\u200d\u200b\u202d\u206c\u206d\u200f\u206a\u206f\u200f\u206b\u200c\u206f\u202e\u200d\u206f\u206d\u206d\u202e(orig_\u200c\u202a\u206b\u200d\u200f\u206e\u200c\u200c\u206e\u202a\u200b\u206b\u206a\u206d\u200c\u200c\u200b\u202b\u202e\u200f\u200f\u206f\u206b\u200d\u200b\u202d\u206c\u206d\u200f\u206a\u206f\u200f\u206b\u200c\u206f\u202e\u200d\u206f\u206d\u206d\u202e orig, Object P_1, Object P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] orig_\u202c\u206c\u200c\u206f\u206f\u206e\u200b\u200d\u206b\u202b\u206c\u200c\u202b\u206b\u206e\u202b\u202d\u206c\u206a\u206d\u206b\u202b\u200d\u206d\u202d\u206c\u200f\u206f\u202c\u202d\u206d\u202a\u206e\u200e\u200b\u202e\u202b\u200b\u200b\u206c\u202e(TerrainData P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture2D[] hook_\u202c\u206c\u200c\u206f\u206f\u206e\u200b\u200d\u206b\u202b\u206c\u200c\u202b\u206b\u206e\u202b\u202d\u206c\u206a\u206d\u206b\u202b\u200d\u206d\u202d\u206c\u200f\u206f\u202c\u202d\u206d\u202a\u206e\u200e\u200b\u202e\u202b\u200b\u200b\u206c\u202e(orig_\u202c\u206c\u200c\u206f\u206f\u206e\u200b\u200d\u206b\u202b\u206c\u200c\u202b\u206b\u206e\u202b\u202d\u206c\u206a\u206d\u206b\u202b\u200d\u206d\u202d\u206c\u200f\u206f\u202c\u202d\u206d\u202a\u206e\u200e\u200b\u202e\u202b\u200b\u200b\u206c\u202e orig, TerrainData P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate string orig_\u200d\u202d\u206b\u206f\u206d\u200b\u202b\u202e\u206f\u200f\u200f\u202e\u200d\u200b\u200f\u202d\u206f\u206f\u206f\u206c\u206f\u206e\u200b\u202a\u200f\u206f\u206e\u206c\u200f\u206a\u200d\u202c\u202d\u202b\u206a\u200e\u200b\u206e\u206c\u202e\u202e(Object P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate string hook_\u200d\u202d\u206b\u206f\u206d\u200b\u202b\u202e\u206f\u200f\u200f\u202e\u200d\u200b\u200f\u202d\u206f\u206f\u206f\u206c\u206f\u206e\u200b\u202a\u200f\u206f\u206e\u206c\u200f\u206a\u200d\u202c\u202d\u202b\u206a\u200e\u200b\u206e\u206c\u202e\u202e(orig_\u200d\u202d\u206b\u206f\u206d\u200b\u202b\u202e\u206f\u200f\u200f\u202e\u200d\u200b\u200f\u202d\u206f\u206f\u206f\u206c\u206f\u206e\u200b\u202a\u200f\u206f\u206e\u206c\u200f\u206a\u200d\u202c\u202d\u202b\u206a\u200e\u200b\u206e\u206c\u202e\u202e orig, Object P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool orig_\u206b\u202c\u206e\u206c\u206f\u206d\u200d\u202c\u200e\u206b\u202a\u202d\u206b\u202c\u206d\u206b\u206a\u206a\u206a\u202b\u202c\u206a\u206a\u206d\u206d\u202c\u202d\u206f\u202c\u200b\u206c\u200f\u206a\u200e\u202b\u200c\u200e\u202c\u202c\u206e\u202e(string P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool hook_\u206b\u202c\u206e\u206c\u206f\u206d\u200d\u202c\u200e\u206b\u202a\u202d\u206b\u202c\u206d\u206b\u206a\u206a\u206a\u202b\u202c\u206a\u206a\u206d\u206d\u202c\u202d\u206f\u202c\u200b\u206c\u200f\u206a\u200e\u202b\u200c\u200e\u202c\u202c\u206e\u202e(orig_\u206b\u202c\u206e\u206c\u206f\u206d\u200d\u202c\u200e\u206b\u202a\u202d\u206b\u202c\u206d\u206b\u206a\u206a\u206a\u202b\u202c\u206a\u206a\u206d\u206d\u202c\u202d\u206f\u202c\u200b\u206c\u200f\u206a\u200e\u202b\u200c\u200e\u202c\u202c\u206e\u202e orig, string P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate string orig_\u200e\u206c\u202d\u202a\u206a\u202a\u202e\u206c\u202e\u206d\u200c\u206a\u200f\u206a\u206c\u202e\u200b\u202e\u200f\u200f\u200b\u202e\u200b\u202e\u202a\u200e\u200c\u202a\u200d\u202d\u206f\u206c\u200b\u200f\u200f\u206e\u206d\u200e\u206b\u206d\u202e(string P_0, string P_1, string P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate string hook_\u200e\u206c\u202d\u202a\u206a\u202a\u202e\u206c\u202e\u206d\u200c\u206a\u200f\u206a\u206c\u202e\u200b\u202e\u200f\u200f\u200b\u202e\u200b\u202e\u202a\u200e\u200c\u202a\u200d\u202d\u206f\u206c\u200b\u200f\u200f\u206e\u206d\u200e\u206b\u206d\u202e(orig_\u200e\u206c\u202d\u202a\u206a\u202a\u202e\u206c\u202e\u206d\u200c\u206a\u200f\u206a\u206c\u202e\u200b\u202e\u200f\u200f\u200b\u202e\u200b\u202e\u202a\u200e\u200c\u202a\u200d\u202d\u206f\u206c\u200b\u200f\u200f\u206e\u206d\u200e\u206b\u206d\u202e orig, string P_1, string P_2, string P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Shader orig_\u202b\u202b\u202e\u202c\u206e\u202c\u206e\u200e\u202b\u200c\u206d\u206d\u200c\u206d\u200b\u206a\u200f\u202a\u200f\u200e\u200e\u206e\u200e\u206d\u206a\u200d\u200e\u202d\u206f\u202a\u202e\u200b\u200e\u200e\u206c\u206b\u200e\u202b\u200f\u202d\u202e(string P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Shader hook_\u202b\u202b\u202e\u202c\u206e\u202c\u206e\u200e\u202b\u200c\u206d\u206d\u200c\u206d\u200b\u206a\u200f\u202a\u200f\u200e\u200e\u206e\u200e\u206d\u206a\u200d\u200e\u202d\u206f\u202a\u202e\u200b\u200e\u200e\u206c\u206b\u200e\u202b\u200f\u202d\u202e(orig_\u202b\u202b\u202e\u202c\u206e\u202c\u206e\u200e\u202b\u200c\u206d\u206d\u200c\u206d\u200b\u206a\u200f\u202a\u200f\u200e\u200e\u206e\u200e\u206d\u206a\u200d\u200e\u202d\u206f\u202a\u202e\u200b\u200e\u200e\u206c\u206b\u200e\u202b\u200f\u202d\u202e orig, string P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Material orig_\u206d\u206f\u202b\u206d\u202e\u206d\u202d\u202a\u200f\u202c\u200e\u206d\u200d\u202e\u200f\u206f\u200c\u202b\u202d\u206e\u202c\u206d\u200d\u206d\u202d\u200f\u202c\u206f\u202c\u202a\u206b\u206b\u206b\u202b\u202a\u206c\u200f\u206a\u206b\u206e\u202e(Shader P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Material hook_\u206d\u206f\u202b\u206d\u202e\u206d\u202d\u202a\u200f\u202c\u200e\u206d\u200d\u202e\u200f\u206f\u200c\u202b\u202d\u206e\u202c\u206d\u200d\u206d\u202d\u200f\u202c\u206f\u202c\u202a\u206b\u206b\u206b\u202b\u202a\u206c\u200f\u206a\u206b\u206e\u202e(orig_\u206d\u206f\u202b\u206d\u202e\u206d\u202d\u202a\u200f\u202c\u200e\u206d\u200d\u202e\u200f\u206f\u200c\u202b\u202d\u206e\u202c\u206d\u200d\u206d\u202d\u200f\u202c\u206f\u202c\u202a\u206b\u206b\u206b\u202b\u202a\u206c\u200f\u206a\u206b\u206e\u202e orig, Shader P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_\u200f\u202c\u202c\u200b\u200f\u202b\u202c\u202c\u202b\u200d\u202c\u202d\u206b\u202e\u206e\u200f\u202c\u200e\u200f\u206d\u206e\u202b\u200c\u202d\u200c\u206b\u202d\u202d\u202b\u206f\u206f\u202c\u206b\u202d\u202b\u200c\u206d\u206b\u206f\u206c\u202e(Material P_0, string P_1, float P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_\u200f\u202c\u202c\u200b\u200f\u202b\u202c\u202c\u202b\u200d\u202c\u202d\u206b\u202e\u206e\u200f\u202c\u200e\u200f\u206d\u206e\u202b\u200c\u202d\u200c\u206b\u202d\u202d\u202b\u206f\u206f\u202c\u206b\u202d\u202b\u200c\u206d\u206b\u206f\u206c\u202e(orig_\u200f\u202c\u202c\u200b\u200f\u202b\u202c\u202c\u202b\u200d\u202c\u202d\u206b\u202e\u206e\u200f\u202c\u200e\u200f\u206d\u206e\u202b\u200c\u202d\u200c\u206b\u202d\u202d\u202b\u206f\u206f\u202c\u206b\u202d\u202b\u200c\u206d\u206b\u206f\u206c\u202e orig, Material P_1, string P_2, float P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate int orig_\u206a\u206b\u202e\u206a\u200d\u200e\u200b\u202a\u206a\u206c\u202c\u200f\u202d\u206d\u202e\u202c\u202a\u202b\u200f\u202d\u206e\u206a\u206c\u206e\u206e\u202c\u202e\u206c\u200d\u200b\u202e\u202c\u206a\u202d\u200b\u200c\u206c\u206a\u202d\u202e(TerrainData P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate int hook_\u206a\u206b\u202e\u206a\u200d\u200e\u200b\u202a\u206a\u206c\u202c\u200f\u202d\u206d\u202e\u202c\u202a\u202b\u200f\u202d\u206e\u206a\u206c\u206e\u206e\u202c\u202e\u206c\u200d\u200b\u202e\u202c\u206a\u202d\u200b\u200c\u206c\u206a\u202d\u202e(orig_\u206a\u206b\u202e\u206a\u200d\u200e\u200b\u202a\u206a\u206c\u202c\u200f\u202d\u206d\u202e\u202c\u202a\u202b\u200f\u202d\u206e\u206a\u206c\u206e\u206e\u202c\u202e\u206c\u200d\u200b\u202e\u202c\u206a\u202d\u200b\u200c\u206c\u206a\u202d\u202e orig, TerrainData P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate RenderTexture orig_\u202b\u200c\u202c\u206c\u206a\u202a\u206c\u202b\u202d\u200c\u206d\u206f\u206b\u200e\u200b\u202b\u206e\u206b\u200d\u200c\u200f\u200b\u206d\u202d\u200d\u202a\u202d\u200f\u206c\u206b\u200d\u202b\u202a\u206d\u200d\u206b\u206d\u200f\u202a\u206b\u202e(int P_0, int P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate RenderTexture hook_\u202b\u200c\u202c\u206c\u206a\u202a\u206c\u202b\u202d\u200c\u206d\u206f\u206b\u200e\u200b\u202b\u206e\u206b\u200d\u200c\u200f\u200b\u206d\u202d\u200d\u202a\u202d\u200f\u206c\u206b\u200d\u202b\u202a\u206d\u200d\u206b\u206d\u200f\u202a\u206b\u202e(orig_\u202b\u200c\u202c\u206c\u206a\u202a\u206c\u202b\u202d\u200c\u206d\u206f\u206b\u200e\u200b\u202b\u206e\u206b\u200d\u200c\u200f\u200b\u206d\u202d\u200d\u202a\u202d\u200f\u206c\u206b\u200d\u202b\u202a\u206d\u200d\u206b\u206d\u200f\u202a\u206b\u202e orig, int P_1, int P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool orig_\u200c\u200b\u202e\u202c\u202c\u206e\u202c\u200c\u202e\u202a\u202d\u200d\u206e\u206a\u200e\u206b\u202b\u202a\u206b\u202c\u202e\u206d\u200d\u200c\u200d\u200f\u206c\u200c\u206d\u200b\u200c\u202e\u206b\u206b\u206f\u200e\u202c\u202a\u200e\u202e\u202e(RenderTexture P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool hook_\u200c\u200b\u202e\u202c\u202c\u206e\u202c\u200c\u202e\u202a\u202d\u200d\u206e\u206a\u200e\u206b\u202b\u202a\u206b\u202c\u202e\u206d\u200d\u200c\u200d\u200f\u206c\u200c\u206d\u200b\u200c\u202e\u206b\u206b\u206f\u200e\u202c\u202a\u200e\u202e\u202e(orig_\u200c\u200b\u202e\u202c\u202c\u206e\u202c\u200c\u202e\u202a\u202d\u200d\u206e\u206a\u200e\u206b\u202b\u202a\u206b\u202c\u202e\u206d\u200d\u200c\u200d\u200f\u206c\u200c\u206d\u200b\u200c\u202e\u206b\u206b\u206f\u200e\u202c\u202a\u200e\u202e\u202e orig, RenderTexture P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate TextureFormat orig_\u206e\u202e\u206c\u206a\u202e\u206f\u206f\u206a\u206e\u200c\u206b\u206b\u206c\u202a\u200f\u202e\u206f\u200f\u200d\u200e\u206e\u202c\u206d\u206f\u200d\u200e\u206c\u202c\u206b\u206a\u206d\u202e\u202e\u200f\u202b\u206c\u202a\u206f\u200b\u206e\u202e(Texture2D P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate TextureFormat hook_\u206e\u202e\u206c\u206a\u202e\u206f\u206f\u206a\u206e\u200c\u206b\u206b\u206c\u202a\u200f\u202e\u206f\u200f\u200d\u200e\u206e\u202c\u206d\u206f\u200d\u200e\u206c\u202c\u206b\u206a\u206d\u202e\u202e\u200f\u202b\u206c\u202a\u206f\u200b\u206e\u202e(orig_\u206e\u202e\u206c\u206a\u202e\u206f\u206f\u206a\u206e\u200c\u206b\u206b\u206c\u202a\u200f\u202e\u206f\u200f\u200d\u200e\u206e\u202c\u206d\u206f\u200d\u200e\u206c\u202c\u206b\u206a\u206d\u202e\u202e\u200f\u202b\u206c\u202a\u206f\u200b\u206e\u202e orig, Texture2D P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_\u206a\u200f\u200f\u202a\u206e\u202d\u202e\u206f\u200e\u200b\u200d\u200f\u206c\u202d\u206e\u206c\u202a\u202e\u206b\u200c\u206b\u206d\u202b\u202c\u206b\u200b\u202d\u206c\u200f\u202d\u202c\u202c\u202a\u206f\u200f\u206f\u202a\u200c\u202b\u200d\u202e(Texture P_0, TextureWrapMode P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_\u206a\u200f\u200f\u202a\u206e\u202d\u202e\u206f\u200e\u200b\u200d\u200f\u206c\u202d\u206e\u206c\u202a\u202e\u206b\u200c\u206b\u206d\u202b\u202c\u206b\u200b\u202d\u206c\u200f\u202d\u202c\u202c\u202a\u206f\u200f\u206f\u202a\u200c\u202b\u200d\u202e(orig_\u206a\u200f\u200f\u202a\u206e\u202d\u202e\u206f\u200e\u200b\u200d\u200f\u206c\u202d\u206e\u206c\u202a\u202e\u206b\u200c\u206b\u206d\u202b\u202c\u206b\u200b\u202d\u206c\u200f\u202d\u202c\u202c\u202a\u206f\u200f\u206f\u202a\u200c\u202b\u200d\u202e orig, Texture P_1, TextureWrapMode P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate string orig_\u200b\u206e\u202c\u200d\u200d\u200b\u206d\u200d\u202b\u200f\u202a\u200e\u206b\u206d\u206b\u202b\u200e\u206a\u200b\u200c\u202e\u202c\u206a\u200f\u200d\u206c\u200d\u206d\u202b\u200d\u202d\u206a\u202e\u206a\u206d\u206b\u200f\u200e\u200f\u206c\u202e(string P_0, string P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate string hook_\u200b\u206e\u202c\u200d\u200d\u200b\u206d\u200d\u202b\u200f\u202a\u200e\u206b\u206d\u206b\u202b\u200e\u206a\u200b\u200c\u202e\u202c\u206a\u200f\u200d\u206c\u200d\u206d\u202b\u200d\u202d\u206a\u202e\u206a\u206d\u206b\u200f\u200e\u200f\u206c\u202e(orig_\u200b\u206e\u202c\u200d\u200d\u200b\u206d\u200d\u202b\u200f\u202a\u200e\u206b\u206d\u206b\u202b\u200e\u206a\u200b\u200c\u202e\u202c\u206a\u200f\u200d\u206c\u200d\u206d\u202b\u200d\u202d\u206a\u202e\u206a\u206d\u206b\u200f\u200e\u200f\u206c\u202e orig, string P_1, string P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_\u202d\u206e\u200d\u200f\u202c\u200e\u206e\u200f\u206b\u202d\u200e\u202a\u200f\u202a\u202c\u202c\u206c\u200b\u200f\u206f\u206a\u206a\u206a\u202b\u206b\u206e\u206d\u200c\u202c\u200b\u200d\u206e\u202c\u200c\u200e\u200b\u202b\u200d\u206f\u200c\u202e(Object P_0, string P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_\u202d\u206e\u200d\u200f\u202c\u200e\u206e\u200f\u206b\u202d\u200e\u202a\u200f\u202a\u202c\u202c\u206c\u200b\u200f\u206f\u206a\u206a\u206a\u202b\u206b\u206e\u206d\u200c\u202c\u200b\u200d\u206e\u202c\u200c\u200e\u200b\u202b\u200d\u206f\u200c\u202e(orig_\u202d\u206e\u200d\u200f\u202c\u200e\u206e\u200f\u206b\u202d\u200e\u202a\u200f\u202a\u202c\u202c\u206c\u200b\u200f\u206f\u206a\u206a\u206a\u202b\u206b\u206e\u206d\u200c\u202c\u200b\u200d\u206e\u202c\u200c\u200e\u200b\u202b\u200d\u206f\u200c\u202e orig, Object P_1, string P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_\u200b\u206b\u202a\u206c\u206e\u202c\u200c\u202d\u206e\u206c\u200e\u200f\u200d\u202d\u200e\u206a\u202b\u206a\u202b\u202b\u206c\u200d\u206c\u206a\u200b\u202a\u202c\u206b\u206b\u200e\u200d\u206e\u206e\u206d\u202b\u206e\u206c\u206f\u200b\u202d\u202e(RenderTexture P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_\u200b\u206b\u202a\u206c\u206e\u202c\u200c\u202d\u206e\u206c\u200e\u200f\u200d\u202d\u200e\u206a\u202b\u206a\u202b\u202b\u206c\u200d\u206c\u206a\u200b\u202a\u202c\u206b\u206b\u200e\u200d\u206e\u206e\u206d\u202b\u206e\u206c\u206f\u200b\u202d\u202e(orig_\u200b\u206b\u202a\u206c\u206e\u202c\u200c\u202d\u206e\u206c\u200e\u200f\u200d\u202d\u200e\u206a\u202b\u206a\u202b\u202b\u206c\u200d\u206c\u206a\u200b\u202a\u202c\u206b\u206b\u200e\u200d\u206e\u206e\u206d\u202b\u206e\u206c\u206f\u200b\u202d\u202e orig, RenderTexture P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool orig_\u202e\u202d\u200e\u202e\u200b\u202b\u202a\u200c\u202b\u202a\u206d\u206a\u206b\u206d\u206a\u206a\u202c\u202c\u206d\u206b\u206e\u206e\u206f\u200d\u206a\u200d\u206c\u202c\u206a\u206f\u206c\u206a\u200e\u206d\u200f\u206f\u206a\u202a\u200f\u200e\u202e();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool hook_\u202e\u202d\u200e\u202e\u200b\u202b\u202a\u200c\u202b\u202a\u206d\u206a\u206b\u206d\u206a\u206a\u202c\u202c\u206d\u206b\u206e\u206e\u206f\u200d\u206a\u200d\u206c\u202c\u206a\u206f\u206c\u206a\u200e\u206d\u200f\u206f\u206a\u202a\u200f\u200e\u202e(orig_\u202e\u202d\u200e\u202e\u200b\u202b\u202a\u200c\u202b\u202a\u206d\u206a\u206b\u206d\u206a\u206a\u202c\u202c\u206d\u206b\u206e\u206e\u206f\u200d\u206a\u200d\u206c\u202c\u206a\u206f\u206c\u206a\u200e\u206d\u200f\u206f\u206a\u202a\u200f\u200e\u202e orig);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_\u206b\u206f\u200e\u206e\u202c\u200d\u206a\u206d\u206c\u206e\u206e\u206d\u206a\u206f\u202a\u202c\u200f\u206a\u200d\u206f\u206e\u202a\u200d\u206d\u206b\u200e\u200d\u206b\u202c\u202e\u200e\u200d\u206f\u200e\u202d\u200e\u206f\u200c\u206d\u202d\u202e(Object P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_\u206b\u206f\u200e\u206e\u202c\u200d\u206a\u206d\u206c\u206e\u206e\u206d\u206a\u206f\u202a\u202c\u200f\u206a\u200d\u206f\u206e\u202a\u200d\u206d\u206b\u200e\u200d\u206b\u202c\u202e\u200e\u200d\u206f\u200e\u202d\u200e\u206f\u200c\u206d\u202d\u202e(orig_\u206b\u206f\u200e\u206e\u202c\u200d\u206a\u206d\u206c\u206e\u206e\u206d\u206a\u206f\u202a\u202c\u200f\u206a\u200d\u206f\u206e\u202a\u200d\u206d\u206b\u200e\u200d\u206b\u202c\u202e\u200e\u200d\u206f\u200e\u202d\u200e\u206f\u200c\u206d\u202d\u202e orig, Object P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_\u206b\u206e\u200e\u202a\u206f\u202e\u206f\u200e\u200f\u206c\u202e\u206d\u206c\u206c\u202b\u200c\u202b\u202e\u206b\u202d\u206a\u202a\u202b\u200b\u202d\u200d\u206e\u206f\u206b\u200f\u202e\u206d\u202e\u200f\u200b\u206e\u202c\u202c\u202a\u202c\u202e(Object P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_\u206b\u206e\u200e\u202a\u206f\u202e\u206f\u200e\u200f\u206c\u202e\u206d\u206c\u206c\u202b\u200c\u202b\u202e\u206b\u202d\u206a\u202a\u202b\u200b\u202d\u200d\u206e\u206f\u206b\u200f\u202e\u206d\u202e\u200f\u200b\u206e\u202c\u202c\u202a\u202c\u202e(orig_\u206b\u206e\u200e\u202a\u206f\u202e\u206f\u200e\u200f\u206c\u202e\u206d\u206c\u206c\u202b\u200c\u202b\u202e\u206b\u202d\u206a\u202a\u202b\u200b\u202d\u200d\u206e\u206f\u206b\u200f\u202e\u206d\u202e\u200f\u200b\u206e\u202c\u202c\u202a\u202c\u202e orig, Object P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate ColorSpace orig_\u206a\u202b\u202c\u200b\u206f\u202e\u200c\u206b\u200f\u202b\u206e\u206e\u200b\u202b\u202a\u206f\u202a\u202c\u206f\u200b\u206c\u200d\u206e\u200c\u202b\u202a\u206f\u206e\u200b\u200d\u202e\u200e\u202c\u206b\u200e\u206e\u202d\u206a\u202b\u200e\u202e();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate ColorSpace hook_\u206a\u202b\u202c\u200b\u206f\u202e\u200c\u206b\u200f\u202b\u206e\u206e\u200b\u202b\u202a\u206f\u202a\u202c\u206f\u200b\u206c\u200d\u206e\u200c\u202b\u202a\u206f\u206e\u200b\u200d\u202e\u200e\u202c\u206b\u200e\u206e\u202d\u206a\u202b\u200e\u202e(orig_\u206a\u202b\u202c\u200b\u206f\u202e\u200c\u206b\u200f\u202b\u206e\u206e\u200b\u202b\u202a\u206f\u202a\u202c\u206f\u200b\u206c\u200d\u206e\u200c\u202b\u202a\u206f\u206e\u200b\u200d\u202e\u200e\u202c\u206b\u200e\u206e\u202d\u206a\u202b\u200e\u202e orig);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate RenderTexture orig_\u202d\u206b\u202d\u202d\u202c\u200f\u200c\u200e\u202d\u200b\u202c\u200b\u206e\u206c\u206d\u206c\u202e\u206b\u206a\u206e\u206a\u200d\u202c\u202b\u200d\u206d\u206f\u206c\u206b\u202b\u206c\u202e\u206e\u200b\u206a\u200f\u200f\u206f\u206a\u202a\u202e(TerrainData P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate RenderTexture hook_\u202d\u206b\u202d\u202d\u202c\u200f\u200c\u200e\u202d\u200b\u202c\u200b\u206e\u206c\u206d\u206c\u202e\u206b\u206a\u206e\u206a\u200d\u202c\u202b\u200d\u206d\u206f\u206c\u206b\u202b\u206c\u202e\u206e\u200b\u206a\u200f\u200f\u206f\u206a\u202a\u202e(orig_\u202d\u206b\u202d\u202d\u202c\u200f\u200c\u200e\u202d\u200b\u202c\u200b\u206e\u206c\u206d\u206c\u202e\u206b\u206a\u206e\u206a\u200d\u202c\u202b\u200d\u206d\u206f\u206c\u206b\u202b\u206c\u202e\u206e\u200b\u206a\u200f\u200f\u206f\u206a\u202a\u202e orig, TerrainData P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_\u206f\u200f\u206f\u200b\u206e\u202b\u202c\u206a\u200e\u200b\u200f\u206d\u206b\u200e\u200f\u200e\u206c\u202d\u206a\u206f\u200b\u200d\u206a\u206b\u206d\u202a\u202d\u206c\u206b\u206f\u202d\u200b\u200c\u202d\u202a\u206d\u206e\u206c\u202b\u202d\u202e(Material P_0, string P_1, Vector4 P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_\u206f\u200f\u206f\u200b\u206e\u202b\u202c\u206a\u200e\u200b\u200f\u206d\u206b\u200e\u200f\u200e\u206c\u202d\u206a\u206f\u200b\u200d\u206a\u206b\u206d\u202a\u202d\u206c\u206b\u206f\u202d\u200b\u200c\u202d\u202a\u206d\u206e\u206c\u202b\u202d\u202e(orig_\u206f\u200f\u206f\u200b\u206e\u202b\u202c\u206a\u200e\u200b\u200f\u206d\u206b\u200e\u200f\u200e\u206c\u202d\u206a\u206f\u200b\u200d\u206a\u206b\u206d\u202a\u202d\u206c\u206b\u206f\u202d\u200b\u200c\u202d\u202a\u206d\u206e\u206c\u202b\u202d\u202e orig, Material P_1, string P_2, Vector4 P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate int orig_\u206b\u206a\u200e\u202d\u206b\u202d\u200b\u202a\u206f\u200e\u200d\u202e\u206d\u200b\u206a\u202a\u200f\u202d\u206f\u202b\u202a\u200b\u206b\u200b\u200d\u200b\u202e\u202d\u206c\u206e\u202b\u202e\u202a\u200e\u202b\u200c\u202a\u200b\u200c\u206b\u202e(Texture P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate int hook_\u206b\u206a\u200e\u202d\u206b\u202d\u200b\u202a\u206f\u200e\u200d\u202e\u206d\u200b\u206a\u202a\u200f\u202d\u206f\u202b\u202a\u200b\u206b\u200b\u200d\u200b\u202e\u202d\u206c\u206e\u202b\u202e\u202a\u200e\u202b\u200c\u202a\u200b\u200c\u206b\u202e(orig_\u206b\u206a\u200e\u202d\u206b\u202d\u200b\u202a\u206f\u200e\u200d\u202e\u206d\u200b\u206a\u202a\u200f\u202d\u206f\u202b\u202a\u200b\u206b\u200b\u200d\u200b\u202e\u202d\u206c\u206e\u202b\u202e\u202a\u200e\u202b\u200c\u202a\u200b\u200c\u206b\u202e orig, Texture P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate RenderTextureFormat orig_\u206c\u206c\u200e\u202a\u202d\u202b\u206d\u202b\u202b\u200b\u200e\u202b\u202e\u200d\u200d\u202e\u206b\u206a\u206d\u206d\u206e\u200b\u200d\u206b\u202c\u200c\u202b\u202e\u202d\u202d\u206c\u200d\u200c\u202c\u202b\u200c\u200b\u206a\u202d\u202a\u202e(RenderTexture P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate RenderTextureFormat hook_\u206c\u206c\u200e\u202a\u202d\u202b\u206d\u202b\u202b\u200b\u200e\u202b\u202e\u200d\u200d\u202e\u206b\u206a\u206d\u206d\u206e\u200b\u200d\u206b\u202c\u200c\u202b\u202e\u202d\u202d\u206c\u200d\u200c\u202c\u202b\u200c\u200b\u206a\u202d\u202a\u202e(orig_\u206c\u206c\u200e\u202a\u202d\u202b\u206d\u202b\u202b\u200b\u200e\u202b\u202e\u200d\u200d\u202e\u206b\u206a\u206d\u206d\u206e\u200b\u200d\u206b\u202c\u200c\u202b\u202e\u202d\u202d\u206c\u200d\u200c\u202c\u202b\u200c\u200b\u206a\u202d\u202a\u202e orig, RenderTexture P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool orig_\u202e\u206b\u206b\u206c\u202c\u206b\u206e\u200f\u206f\u200c\u206b\u206a\u202d\u206c\u200c\u200f\u200f\u200f\u202a\u200b\u202c\u206f\u206d\u200d\u202a\u200f\u206a\u202e\u202e\u200f\u206b\u202e\u206a\u202d\u206d\u202b\u200e\u206a\u206d\u202b\u202e(RenderTextureFormat P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool hook_\u202e\u206b\u206b\u206c\u202c\u206b\u206e\u200f\u206f\u200c\u206b\u206a\u202d\u206c\u200c\u200f\u200f\u200f\u202a\u200b\u202c\u206f\u206d\u200d\u202a\u200f\u206a\u202e\u202e\u200f\u206b\u202e\u206a\u202d\u206d\u202b\u200e\u206a\u206d\u202b\u202e(orig_\u202e\u206b\u206b\u206c\u202c\u206b\u206e\u200f\u206f\u200c\u206b\u206a\u202d\u206c\u200c\u200f\u200f\u200f\u202a\u200b\u202c\u206f\u206d\u200d\u202a\u200f\u206a\u202e\u202e\u200f\u206b\u202e\u206a\u202d\u206d\u202b\u200e\u206a\u206d\u202b\u202e orig, RenderTextureFormat P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool orig_\u200b\u202d\u200c\u206c\u202e\u200f\u200e\u200d\u202b\u202d\u206c\u200f\u206b\u202c\u200d\u200f\u202c\u206f\u202c\u200d\u202a\u206f\u202b\u202d\u200e\u202e\u206e\u202c\u206f\u200d\u200f\u206e\u206c\u206d\u202d\u206a\u206f\u206e\u202c\u202d\u202e(TextureFormat P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool hook_\u200b\u202d\u200c\u206c\u202e\u200f\u200e\u200d\u202b\u202d\u206c\u200f\u206b\u202c\u200d\u200f\u202c\u206f\u202c\u200d\u202a\u206f\u202b\u202d\u200e\u202e\u206e\u202c\u206f\u200d\u200f\u206e\u206c\u206d\u202d\u206a\u206f\u206e\u202c\u202d\u202e(orig_\u200b\u202d\u200c\u206c\u202e\u200f\u200e\u200d\u202b\u202d\u206c\u200f\u206b\u202c\u200d\u200f\u202c\u206f\u202c\u200d\u202a\u206f\u202b\u202d\u200e\u202e\u206e\u202c\u206f\u200d\u200f\u206e\u206c\u206d\u202d\u206a\u206f\u206e\u202c\u202d\u202e orig, TextureFormat P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate RenderTexture orig_\u206b\u200b\u202c\u206a\u200b\u200d\u200e\u206c\u206c\u202c\u200e\u206d\u202a\u202c\u202a\u206a\u202d\u206b\u202d\u202c\u206b\u206d\u206c\u202d\u202c\u200e\u206e\u206b\u206e\u206b\u202a\u202a\u202a\u202e\u202d\u202c\u206f\u206f\u206f\u200d\u202e(int P_0, int P_1, int P_2, RenderTextureFormat P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate RenderTexture hook_\u206b\u200b\u202c\u206a\u200b\u200d\u200e\u206c\u206c\u202c\u200e\u206d\u202a\u202c\u202a\u206a\u202d\u206b\u202d\u202c\u206b\u206d\u206c\u202d\u202c\u200e\u206e\u206b\u206e\u206b\u202a\u202a\u202a\u202e\u202d\u202c\u206f\u206f\u206f\u200d\u202e(orig_\u206b\u200b\u202c\u206a\u200b\u200d\u200e\u206c\u206c\u202c\u200e\u206d\u202a\u202c\u202a\u206a\u202d\u206b\u202d\u202c\u206b\u206d\u206c\u202d\u202c\u200e\u206e\u206b\u206e\u206b\u202a\u202a\u202a\u202e\u202d\u202c\u206f\u206f\u206f\u200d\u202e orig, int P_1, int P_2, int P_3, RenderTextureFormat P_4);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture orig_\u200b\u206a\u200e\u206d\u206f\u200f\u200c\u202c\u206a\u206f\u206c\u206f\u200f\u206e\u206c\u200d\u200c\u202c\u202b\u200d\u202a\u206c\u206c\u200c\u206c\u206c\u200b\u200f\u202a\u202d\u206c\u200d\u202e\u200e\u200d\u206e\u202c\u200d\u206b\u202e(TerrainData P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Texture hook_\u200b\u206a\u200e\u206d\u206f\u200f\u200c\u202c\u206a\u206f\u206c\u206f\u200f\u206e\u206c\u200d\u200c\u202c\u202b\u200d\u202a\u206c\u206c\u200c\u206c\u206c\u200b\u200f\u202a\u202d\u206c\u200d\u202e\u200e\u200d\u206e\u202c\u200d\u206b\u202e(orig_\u200b\u206a\u200e\u206d\u206f\u200f\u200c\u202c\u206a\u206f\u206c\u206f\u200f\u206e\u206c\u200d\u200c\u202c\u202b\u200d\u202a\u206c\u206c\u200c\u206c\u206c\u200b\u200f\u202a\u202d\u206c\u200d\u202e\u200e\u200d\u206e\u202c\u200d\u206b\u202e orig, TerrainData P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool orig_\u202c\u202d\u202c\u200f\u200e\u206f\u206c\u200f\u206d\u200d\u200d\u202b\u202d\u206d\u200f\u200d\u200d\u202e\u200b\u206d\u200c\u202c\u200e\u200c\u200d\u200e\u200e\u206d\u200f\u200d\u200d\u206c\u206d\u206c\u200c\u206e\u206e\u200f\u202c\u202a\u202e(TerrainData P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool hook_\u202c\u202d\u202c\u200f\u200e\u206f\u206c\u200f\u206d\u200d\u200d\u202b\u202d\u206d\u200f\u200d\u200d\u202e\u200b\u206d\u200c\u202c\u200e\u200c\u200d\u200e\u200e\u206d\u200f\u200d\u200d\u206c\u206d\u206c\u200c\u206e\u206e\u200f\u202c\u202a\u202e(orig_\u202c\u202d\u202c\u200f\u200e\u206f\u206c\u200f\u206d\u200d\u200d\u202b\u202d\u206d\u200f\u200d\u200d\u202e\u200b\u206d\u200c\u202c\u200e\u200c\u200d\u200e\u200e\u206d\u200f\u200d\u200d\u206c\u206d\u206c\u200c\u206e\u206e\u200f\u202c\u202a\u202e orig, TerrainData P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_\u200f\u206a\u200c\u206b\u200c\u202d\u200f\u206c\u200d\u200b\u206d\u200f\u202c\u200c\u200b\u202c\u206b\u206a\u206a\u202d\u202a\u200d\u206e\u202b\u206c\u206b\u202e\u206a\u202b\u206d\u200d\u200d\u206d\u206e\u206c\u200f\u202e\u200f\u200d\u206e\u202e(TerrainData P_0, bool P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_\u200f\u206a\u200c\u206b\u200c\u202d\u200f\u206c\u200d\u200b\u206d\u200f\u202c\u200c\u200b\u202c\u206b\u206a\u206a\u202d\u202a\u200d\u206e\u202b\u206c\u206b\u202e\u206a\u202b\u206d\u200d\u200d\u206d\u206e\u206c\u200f\u202e\u200f\u200d\u206e\u202e(orig_\u200f\u206a\u200c\u206b\u200c\u202d\u200f\u206c\u200d\u200b\u206d\u200f\u202c\u200c\u200b\u202c\u206b\u206a\u206a\u202d\u202a\u200d\u206e\u202b\u206c\u206b\u202e\u206a\u202b\u206d\u200d\u200d\u206d\u206e\u206c\u200f\u202e\u200f\u200d\u206e\u202e orig, TerrainData P_1, bool P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate RenderTexture orig_\u206b\u206d\u206b\u206d\u206c\u206d\u206d\u206d\u206e\u202a\u202b\u200b\u202d\u206e\u206e\u202e\u202c\u206e\u200b\u206f\u200b\u202d\u206a\u200f\u206b\u200c\u200c\u200e\u202c\u206f\u202e\u202d\u202c\u206d\u206a\u206a\u206e\u202e\u200c\u200f\u202e(int P_0, int P_1, int P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate RenderTexture hook_\u206b\u206d\u206b\u206d\u206c\u206d\u206d\u206d\u206e\u202a\u202b\u200b\u202d\u206e\u206e\u202e\u202c\u206e\u200b\u206f\u200b\u202d\u206a\u200f\u206b\u200c\u200c\u200e\u202c\u206f\u202e\u202d\u202c\u206d\u206a\u206a\u206e\u202e\u200c\u200f\u202e(orig_\u206b\u206d\u206b\u206d\u206c\u206d\u206d\u206d\u206e\u202a\u202b\u200b\u202d\u206e\u206e\u202e\u202c\u206e\u200b\u206f\u200b\u202d\u206a\u200f\u206b\u200c\u200c\u200e\u202c\u206f\u202e\u202d\u202c\u206d\u206a\u206a\u206e\u202e\u200c\u200f\u202e orig, int P_1, int P_2, int P_3);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_\u202a\u200f\u202c\u206a\u206a\u200d\u206b\u200c\u202b\u206c\u206c\u200b\u200c\u206a\u200b\u202a\u202e\u202e\u200d\u206b\u202e\u206e\u202a\u202a\u202e\u200f\u202e\u200d\u206e\u202e\u200d\u202c\u200d\u202c\u202a\u200c\u202a\u202e\u200e\u200c\u202e(Texture P_0, RenderTexture P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_\u202a\u200f\u202c\u206a\u206a\u200d\u206b\u200c\u202b\u206c\u206c\u200b\u200c\u206a\u200b\u202a\u202e\u202e\u200d\u206b\u202e\u206e\u202a\u202a\u202e\u200f\u202e\u200d\u206e\u202e\u200d\u202c\u200d\u202c\u202a\u200c\u202a\u202e\u200e\u200c\u202e(orig_\u202a\u200f\u202c\u206a\u206a\u200d\u206b\u200c\u202b\u206c\u206c\u200b\u200c\u206a\u200b\u202a\u202e\u202e\u200d\u206b\u202e\u206e\u202a\u202a\u202e\u200f\u202e\u200d\u206e\u202e\u200d\u202c\u200d\u202c\u202a\u200c\u202a\u202e\u200e\u200c\u202e orig, Texture P_1, RenderTexture P_2);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Color[] orig_\u200f\u206a\u206e\u202c\u202b\u206e\u200d\u206a\u200e\u202a\u206e\u200c\u206c\u206e\u200b\u200b\u200e\u202d\u206e\u200c\u206d\u202d\u200e\u200b\u202b\u200d\u202a\u200b\u202c\u202a\u200f\u206e\u202d\u206b\u200f\u206e\u206b\u202b\u202b\u206c\u202e(Texture2D P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate Color[] hook_\u200f\u206a\u206e\u202c\u202b\u206e\u200d\u206a\u200e\u202a\u206e\u200c\u206c\u206e\u200b\u200b\u200e\u202d\u206e\u200c\u206d\u202d\u200e\u200b\u202b\u200d\u202a\u200b\u202c\u202a\u200f\u206e\u202d\u206b\u200f\u206e\u206b\u202b\u202b\u206c\u202e(orig_\u200f\u206a\u206e\u202c\u202b\u206e\u200d\u206a\u200e\u202a\u206e\u200c\u206c\u206e\u200b\u200b\u200e\u202d\u206e\u200c\u206d\u202d\u200e\u200b\u202b\u200d\u202a\u200b\u202c\u202a\u200f\u206e\u202d\u206b\u200f\u206e\u206b\u202b\u202b\u206c\u202e orig, Texture2D P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate float orig_\u202e\u206d\u206c\u206a\u200c\u202b\u206c\u202a\u200f\u202c\u206c\u202b\u200b\u202e\u206f\u202d\u200b\u200f\u202a\u202b\u200f\u206c\u206c\u202c\u200b\u202d\u200c\u202d\u206d\u206b\u202d\u200c\u200b\u202c\u202d\u200e\u202e\u206e\u200e\u202d\u202e(IEnumerable<float> P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate float hook_\u202e\u206d\u206c\u206a\u200c\u202b\u206c\u202a\u200f\u202c\u206c\u202b\u200b\u202e\u206f\u202d\u200b\u200f\u202a\u202b\u200f\u206c\u206c\u202c\u200b\u202d\u200c\u202d\u206d\u206b\u202d\u200c\u200b\u202c\u202d\u200e\u202e\u206e\u200e\u202d\u202e(orig_\u202e\u206d\u206c\u206a\u200c\u202b\u206c\u202a\u200f\u202c\u206c\u202b\u200b\u202e\u206f\u202d\u200b\u200f\u202a\u202b\u200f\u206c\u206c\u202c\u200b\u202d\u200c\u202d\u206d\u206b\u202d\u200c\u200b\u202c\u202d\u200e\u202e\u206e\u200e\u202d\u202e orig, IEnumerable<float> P_1);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate float orig_\u206c\u206b\u206c\u202a\u206e\u206a\u202e\u200f\u202d\u202e\u202b\u202e\u200c\u202e\u206d\u206c\u200d\u202b\u206a\u200b\u202a\u206b\u206a\u206c\u202c\u202d\u200d\u206b\u206d\u206f\u200d\u206b\u202e\u200c\u206f\u200f\u200f\u202d\u206d\u206e\u202e(IEnumerable<float> P_0);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate float hook_\u206c\u206b\u206c\u202a\u206e\u206a\u202e\u200f\u202d\u202e\u202b\u202e\u200c\u202e\u206d\u206c\u200d\u202b\u206a\u200b\u202a\u206b\u206a\u206c\u202c\u202d\u200d\u206b\u206d\u206f\u200d\u206b\u202e\u200c\u206f\u200f\u200f\u202d\u206d\u206e\u202e(orig_\u206c\u206b\u206c\u202a\u206e\u206a\u202e\u200f\u202d\u202e\u202b\u202e\u200c\u202e\u206d\u206c\u200d\u202b\u206a\u200b\u202a\u206b\u206a\u206c\u202c\u202d\u200d\u206b\u206d\u206f\u200d\u206b\u202e\u200c\u206f\u200f\u200f\u202d\u206d\u206e\u202e orig, IEnumerable<float> P_1);

			public static class \u206f\u202d\u200c\u206d\u200c\u200f\u206d\u206e\u202b\u200b\u202d\u206f\u206e\u200e\u206d\u206d\u206b\u206c\u206d\u200d\u202d\u202c\u200b\u206f\u200e\u202e\u206c\u206f\u202b\u202d\u206a\u200c\u202a\u200b\u200e\u206a\u200f\u200b\u200c\u202c\u202e
			{
				[EditorBrowsable(EditorBrowsableState.Never)]
				public delegate void orig_cctor();

				[EditorBrowsable(EditorBrowsableState.Never)]
				public delegate void hook_cctor(orig_cctor orig);

				[EditorBrowsable(EditorBrowsableState.Never)]
				public delegate void orig_ctor(object self);

				[EditorBrowsable(EditorBrowsableState.Never)]
				public delegate void hook_ctor(orig_ctor orig, object self);

				[EditorBrowsable(EditorBrowsableState.Never)]
				public delegate float orig_\u206b\u200e\u200d\u206f\u206e\u206f\u206a\u202a\u200b\u200d\u200e\u206f\u202c\u202e\u202e\u206d\u202e\u200e\u200c\u202a\u200c\u200d\u202d\u200f\u202d\u200b\u202d\u202d\u202e\u206b\u206f\u206d\u200d\u202a\u202d\u200f\u202d\u202c\u202d\u206b\u202e(object self, Color P_1);

				[EditorBrowsable(EditorBrowsableState.Never)]
				public delegate float hook_\u206b\u200e\u200d\u206f\u206e\u206f\u206a\u202a\u200b\u200d\u200e\u206f\u202c\u202e\u202e\u206d\u202e\u200e\u200c\u202a\u200c\u200d\u202d\u200f\u202d\u200b\u202d\u202d\u202e\u206b\u206f\u206d\u200d\u202a\u202d\u200f\u202d\u202c\u202d\u206b\u202e(orig_\u206b\u200e\u200d\u206f\u206e\u206f\u206a\u202a\u200b\u200d\u200e\u206f\u202c\u202e\u202e\u206d\u202e\u200e\u200c\u202a\u200c\u200d\u202d\u200f\u202d\u200b\u202d\u202d\u202e\u206b\u206f\u206d\u200d\u202a\u202d\u200f\u202d\u202c\u202d\u206b\u202e orig, object self, Color P_2);

				[EditorBrowsable(EditorBrowsableState.Never)]
				public delegate float orig_\u206d\u202d\u200c\u202e\u200c\u206b\u202d\u200c\u202a\u206b\u202d\u206c\u200e\u206b\u200b\u206c\u200e\u200c\u200f\u206c\u200d\u200d\u200b\u206a\u202d\u202d\u202

BooBoo Building/BepInEx/plugins/MMHOOK/MMHOOK_Assembly-CSharp.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using DigitalRuby.ThunderAndLightning;
using Discord;
using Dissonance;
using Dissonance.Integrations.Unity_NFGO;
using DunGen;
using DunGen.Adapters;
using DunGen.Analysis;
using DunGen.Editor;
using DunGen.Graph;
using DunGen.Tags;
using GameNetcodeStuff;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On;
using On.DigitalRuby.ThunderAndLightning;
using On.Dissonance.Integrations.Unity_NFGO;
using On.DunGen;
using On.DunGen.Adapters;
using On.DunGen.Analysis;
using On.DunGen.Editor;
using On.DunGen.Graph;
using On.DunGen.Tags;
using On.GameNetcodeStuff;
using On.__GEN;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.AI.Navigation;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Video;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On
{
	public static class AlarmButton
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_PushAlarmButton(AlarmButton self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_PushAlarmButton(orig_PushAlarmButton orig, AlarmButton self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(AlarmButton self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, AlarmButton self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AlarmButton self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AlarmButton self);

		public static event hook_PushAlarmButton PushAlarmButton
		{
			add
			{
				HookEndpointManager.Add<hook_PushAlarmButton>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_PushAlarmButton>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class AlarmButton
	{
		public static event Manipulator PushAlarmButton
		{
			add
			{
				HookEndpointManager.Modify<On.AlarmButton.hook_PushAlarmButton>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AlarmButton.hook_PushAlarmButton>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.AlarmButton.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AlarmButton.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.AlarmButton.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AlarmButton.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class AnimatedItem
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_EquipItem(AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_EquipItem(orig_EquipItem orig, AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DiscardItem(AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DiscardItem(orig_DiscardItem orig, AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_PocketItem(AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_PocketItem(orig_PocketItem orig, AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___initializeVariables(AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___initializeVariables(orig___initializeVariables orig, AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig___getTypeName(AnimatedItem self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook___getTypeName(orig___getTypeName orig, AnimatedItem self);

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_EquipItem EquipItem
		{
			add
			{
				HookEndpointManager.Add<hook_EquipItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_EquipItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DiscardItem DiscardItem
		{
			add
			{
				HookEndpointManager.Add<hook_DiscardItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DiscardItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_PocketItem PocketItem
		{
			add
			{
				HookEndpointManager.Add<hook_PocketItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_PocketItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___initializeVariables __initializeVariables
		{
			add
			{
				HookEndpointManager.Add<hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___getTypeName __getTypeName
		{
			add
			{
				HookEndpointManager.Add<hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class AnimatedItem
	{
		public static event Manipulator Start
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedItem.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedItem.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator EquipItem
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedItem.hook_EquipItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedItem.hook_EquipItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator DiscardItem
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedItem.hook_DiscardItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedItem.hook_DiscardItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator PocketItem
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedItem.hook_PocketItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedItem.hook_PocketItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedItem.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedItem.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedItem.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedItem.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator __initializeVariables
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedItem.hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedItem.hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator __getTypeName
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedItem.hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedItem.hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class AnimatedTextureUV
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(AnimatedTextureUV self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, AnimatedTextureUV self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(AnimatedTextureUV self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, AnimatedTextureUV self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IEnumerator orig_AnimateUV(AnimatedTextureUV self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IEnumerator hook_AnimateUV(orig_AnimateUV orig, AnimatedTextureUV self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AnimatedTextureUV self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AnimatedTextureUV self);

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AnimateUV AnimateUV
		{
			add
			{
				HookEndpointManager.Add<hook_AnimateUV>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AnimateUV>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class AnimatedTextureUV
	{
		public static event Manipulator OnEnable
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedTextureUV.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedTextureUV.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedTextureUV.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedTextureUV.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AnimateUV
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedTextureUV.hook_AnimateUV>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedTextureUV.hook_AnimateUV>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.AnimatedTextureUV.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimatedTextureUV.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class AnimationStopPoints
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetAnimationStopPosition1(AnimationStopPoints self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetAnimationStopPosition1(orig_SetAnimationStopPosition1 orig, AnimationStopPoints self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetAnimationGo(AnimationStopPoints self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetAnimationGo(orig_SetAnimationGo orig, AnimationStopPoints self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetAnimationStopPosition2(AnimationStopPoints self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetAnimationStopPosition2(orig_SetAnimationStopPosition2 orig, AnimationStopPoints self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AnimationStopPoints self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AnimationStopPoints self);

		public static event hook_SetAnimationStopPosition1 SetAnimationStopPosition1
		{
			add
			{
				HookEndpointManager.Add<hook_SetAnimationStopPosition1>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetAnimationStopPosition1>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetAnimationGo SetAnimationGo
		{
			add
			{
				HookEndpointManager.Add<hook_SetAnimationGo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetAnimationGo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetAnimationStopPosition2 SetAnimationStopPosition2
		{
			add
			{
				HookEndpointManager.Add<hook_SetAnimationStopPosition2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetAnimationStopPosition2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class AnimationStopPoints
	{
		public static event Manipulator SetAnimationStopPosition1
		{
			add
			{
				HookEndpointManager.Modify<On.AnimationStopPoints.hook_SetAnimationStopPosition1>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimationStopPoints.hook_SetAnimationStopPosition1>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetAnimationGo
		{
			add
			{
				HookEndpointManager.Modify<On.AnimationStopPoints.hook_SetAnimationGo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimationStopPoints.hook_SetAnimationGo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetAnimationStopPosition2
		{
			add
			{
				HookEndpointManager.Modify<On.AnimationStopPoints.hook_SetAnimationStopPosition2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimationStopPoints.hook_SetAnimationStopPosition2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.AnimationStopPoints.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimationStopPoints.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class AudioReverbPresets
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AudioReverbPresets self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AudioReverbPresets self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class AudioReverbPresets
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.AudioReverbPresets.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AudioReverbPresets.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class AutoParentToShip
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LateUpdate(AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LateUpdate(orig_LateUpdate orig, AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartSuckingOutOfShip(AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartSuckingOutOfShip(orig_StartSuckingOutOfShip orig, AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IEnumerator orig_SuckObjectOutOfShip(AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IEnumerator hook_SuckObjectOutOfShip(orig_SuckObjectOutOfShip orig, AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_MoveToOffset(AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_MoveToOffset(orig_MoveToOffset orig, AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___initializeVariables(AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___initializeVariables(orig___initializeVariables orig, AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig___getTypeName(AutoParentToShip self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook___getTypeName(orig___getTypeName orig, AutoParentToShip self);

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LateUpdate LateUpdate
		{
			add
			{
				HookEndpointManager.Add<hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartSuckingOutOfShip StartSuckingOutOfShip
		{
			add
			{
				HookEndpointManager.Add<hook_StartSuckingOutOfShip>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartSuckingOutOfShip>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SuckObjectOutOfShip SuckObjectOutOfShip
		{
			add
			{
				HookEndpointManager.Add<hook_SuckObjectOutOfShip>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SuckObjectOutOfShip>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_MoveToOffset MoveToOffset
		{
			add
			{
				HookEndpointManager.Add<hook_MoveToOffset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_MoveToOffset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___initializeVariables __initializeVariables
		{
			add
			{
				HookEndpointManager.Add<hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___getTypeName __getTypeName
		{
			add
			{
				HookEndpointManager.Add<hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class AutoParentToShip
	{
		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.AutoParentToShip.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AutoParentToShip.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LateUpdate
		{
			add
			{
				HookEndpointManager.Modify<On.AutoParentToShip.hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AutoParentToShip.hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator StartSuckingOutOfShip
		{
			add
			{
				HookEndpointManager.Modify<On.AutoParentToShip.hook_StartSuckingOutOfShip>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AutoParentToShip.hook_StartSuckingOutOfShip>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SuckObjectOutOfShip
		{
			add
			{
				HookEndpointManager.Modify<On.AutoParentToShip.hook_SuckObjectOutOfShip>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AutoParentToShip.hook_SuckObjectOutOfShip>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator MoveToOffset
		{
			add
			{
				HookEndpointManager.Modify<On.AutoParentToShip.hook_MoveToOffset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AutoParentToShip.hook_MoveToOffset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.AutoParentToShip.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AutoParentToShip.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator __initializeVariables
		{
			add
			{
				HookEndpointManager.Modify<On.AutoParentToShip.hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AutoParentToShip.hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator __getTypeName
		{
			add
			{
				HookEndpointManager.Modify<On.AutoParentToShip.hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AutoParentToShip.hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class BaboonBirdAI
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SyncInitialValuesServerRpc(BaboonBirdAI self, int syncLeadershipLevel, Vector3 campPosition);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SyncInitialValuesServerRpc(orig_SyncInitialValuesServerRpc orig, BaboonBirdAI self, int syncLeadershipLevel, Vector3 campPosition);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SyncInitialValuesClientRpc(BaboonBirdAI self, int syncLeadershipLevel, Vector3 campPosition);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SyncInitialValuesClientRpc(orig_SyncInitialValuesClientRpc orig, BaboonBirdAI self, int syncLeadershipLevel, Vector3 campPosition);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LateUpdate(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LateUpdate(orig_LateUpdate orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnCollideWithPlayer(BaboonBirdAI self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnCollideWithPlayer(orig_OnCollideWithPlayer orig, BaboonBirdAI self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnCollideWithEnemy(BaboonBirdAI self, Collider other, EnemyAI enemyScript);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnCollideWithEnemy(orig_OnCollideWithEnemy orig, BaboonBirdAI self, Collider other, EnemyAI enemyScript);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_HitEnemy(BaboonBirdAI self, int force, PlayerControllerB playerWhoHit, bool playHitSFX);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_HitEnemy(orig_HitEnemy orig, BaboonBirdAI self, int force, PlayerControllerB playerWhoHit, bool playHitSFX);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_KillEnemy(BaboonBirdAI self, bool destroy);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_KillEnemy(orig_KillEnemy orig, BaboonBirdAI self, bool destroy);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StopKillAnimation(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StopKillAnimation(orig_StopKillAnimation orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StabPlayerDeathAnimServerRpc(BaboonBirdAI self, int playerObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StabPlayerDeathAnimServerRpc(orig_StabPlayerDeathAnimServerRpc orig, BaboonBirdAI self, int playerObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StabPlayerDeathAnimClientRpc(BaboonBirdAI self, int playerObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StabPlayerDeathAnimClientRpc(orig_StabPlayerDeathAnimClientRpc orig, BaboonBirdAI self, int playerObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IEnumerator orig_killPlayerAnimation(BaboonBirdAI self, int playerObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IEnumerator hook_killPlayerAnimation(orig_killPlayerAnimation orig, BaboonBirdAI self, int playerObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_InteractWithScrap(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_InteractWithScrap(orig_InteractWithScrap orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CanGrabScrap(BaboonBirdAI self, GrabbableObject scrap);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CanGrabScrap(orig_CanGrabScrap orig, BaboonBirdAI self, GrabbableObject scrap);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DropHeldItemAndSync(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DropHeldItemAndSync(orig_DropHeldItemAndSync orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DropScrapServerRpc(BaboonBirdAI self, NetworkObjectReference item, Vector3 targetFloorPosition, int clientWhoSentRPC);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DropScrapServerRpc(orig_DropScrapServerRpc orig, BaboonBirdAI self, NetworkObjectReference item, Vector3 targetFloorPosition, int clientWhoSentRPC);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DropScrapClientRpc(BaboonBirdAI self, NetworkObjectReference item, Vector3 targetFloorPosition, int clientWhoSentRPC);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DropScrapClientRpc(orig_DropScrapClientRpc orig, BaboonBirdAI self, NetworkObjectReference item, Vector3 targetFloorPosition, int clientWhoSentRPC);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DropScrap(BaboonBirdAI self, NetworkObject item, Vector3 targetFloorPosition);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DropScrap(orig_DropScrap orig, BaboonBirdAI self, NetworkObject item, Vector3 targetFloorPosition);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_GrabItemAndSync(BaboonBirdAI self, NetworkObject item);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_GrabItemAndSync(orig_GrabItemAndSync orig, BaboonBirdAI self, NetworkObject item);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_GrabScrapServerRpc(BaboonBirdAI self, NetworkObjectReference item, int clientWhoSentRPC);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_GrabScrapServerRpc(orig_GrabScrapServerRpc orig, BaboonBirdAI self, NetworkObjectReference item, int clientWhoSentRPC);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_GrabScrapClientRpc(BaboonBirdAI self, NetworkObjectReference item, int clientWhoSentRPC);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_GrabScrapClientRpc(orig_GrabScrapClientRpc orig, BaboonBirdAI self, NetworkObjectReference item, int clientWhoSentRPC);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_GrabScrap(BaboonBirdAI self, NetworkObject item);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_GrabScrap(orig_GrabScrap orig, BaboonBirdAI self, NetworkObject item);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ReachedNodeInSearch(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ReachedNodeInSearch(orig_ReachedNodeInSearch orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DoAIInterval(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DoAIInterval(orig_DoAIInterval orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StopFocusingThreat(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StopFocusingThreat(orig_StopFocusingThreat orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StopFocusingThreatServerRpc(BaboonBirdAI self, bool enterScoutingMode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StopFocusingThreatServerRpc(orig_StopFocusingThreatServerRpc orig, BaboonBirdAI self, bool enterScoutingMode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StopFocusingThreatClientRpc(BaboonBirdAI self, bool enterScoutingMode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StopFocusingThreatClientRpc(orig_StopFocusingThreatClientRpc orig, BaboonBirdAI self, bool enterScoutingMode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetAggressiveMode(BaboonBirdAI self, int mode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetAggressiveMode(orig_SetAggressiveMode orig, BaboonBirdAI self, int mode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetAggressiveModeServerRpc(BaboonBirdAI self, int mode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetAggressiveModeServerRpc(orig_SetAggressiveModeServerRpc orig, BaboonBirdAI self, int mode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetAggressiveModeClientRpc(BaboonBirdAI self, int mode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetAggressiveModeClientRpc(orig_SetAggressiveModeClientRpc orig, BaboonBirdAI self, int mode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetThreatInView(BaboonBirdAI self, bool inView);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetThreatInView(orig_SetThreatInView orig, BaboonBirdAI self, bool inView);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetThreatInViewServerRpc(BaboonBirdAI self, bool inView);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetThreatInViewServerRpc(orig_SetThreatInViewServerRpc orig, BaboonBirdAI self, bool inView);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetThreatInViewClientRpc(BaboonBirdAI self, bool inView);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetThreatInViewClientRpc(orig_SetThreatInViewClientRpc orig, BaboonBirdAI self, bool inView);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_EnemyEnterRestModeServerRpc(BaboonBirdAI self, bool sleep, bool atCamp);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_EnemyEnterRestModeServerRpc(orig_EnemyEnterRestModeServerRpc orig, BaboonBirdAI self, bool sleep, bool atCamp);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_EnemyEnterRestModeClientRpc(BaboonBirdAI self, bool sleep, bool atCamp);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_EnemyEnterRestModeClientRpc(orig_EnemyEnterRestModeClientRpc orig, BaboonBirdAI self, bool sleep, bool atCamp);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_EnemyGetUpServerRpc(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_EnemyGetUpServerRpc(orig_EnemyGetUpServerRpc orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_EnemyGetUpClientRpc(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_EnemyGetUpClientRpc(orig_EnemyGetUpClientRpc orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDrawGizmos(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDrawGizmos(orig_OnDrawGizmos orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DetectNoise(BaboonBirdAI self, Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot, int noiseID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DetectNoise(orig_DetectNoise orig, BaboonBirdAI self, Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot, int noiseID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AnimateLooking(BaboonBirdAI self, Vector3 lookAtPosition);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AnimateLooking(orig_AnimateLooking orig, BaboonBirdAI self, Vector3 lookAtPosition);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetComfortableDistanceToThreat(BaboonBirdAI self, Threat focusedThreat);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetComfortableDistanceToThreat(orig_GetComfortableDistanceToThreat orig, BaboonBirdAI self, Threat focusedThreat);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ReactToThreat(BaboonBirdAI self, Threat closestThreat);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ReactToThreat(orig_ReactToThreat orig, BaboonBirdAI self, Threat closestThreat);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartFocusOnThreatServerRpc(BaboonBirdAI self, NetworkObjectReference netObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartFocusOnThreatServerRpc(orig_StartFocusOnThreatServerRpc orig, BaboonBirdAI self, NetworkObjectReference netObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartFocusOnThreatClientRpc(BaboonBirdAI self, NetworkObjectReference netObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartFocusOnThreatClientRpc(orig_StartFocusOnThreatClientRpc orig, BaboonBirdAI self, NetworkObjectReference netObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_ReactToOtherBaboonSighted(BaboonBirdAI self, BaboonBirdAI otherBaboon);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_ReactToOtherBaboonSighted(orig_ReactToOtherBaboonSighted orig, BaboonBirdAI self, BaboonBirdAI otherBaboon);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DoLOSCheck(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DoLOSCheck(orig_DoLOSCheck orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_PingBaboonInterest(BaboonBirdAI self, Vector3 interestPosition, int pingImportance);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_PingBaboonInterest(orig_PingBaboonInterest orig, BaboonBirdAI self, Vector3 interestPosition, int pingImportance);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_PingBirdInterestServerRpc(BaboonBirdAI self, Vector3 lookPosition, float timeToPeek);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_PingBirdInterestServerRpc(orig_PingBirdInterestServerRpc orig, BaboonBirdAI self, Vector3 lookPosition, float timeToPeek);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_PingBirdInterestClientRpc(BaboonBirdAI self, Vector3 lookPosition, float timeToPeek);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_PingBirdInterestClientRpc(orig_PingBirdInterestClientRpc orig, BaboonBirdAI self, Vector3 lookPosition, float timeToPeek);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_JoinScoutingGroup(BaboonBirdAI self, BaboonBirdAI otherBaboon);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_JoinScoutingGroup(orig_JoinScoutingGroup orig, BaboonBirdAI self, BaboonBirdAI otherBaboon);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartScoutingGroup(BaboonBirdAI self, BaboonBirdAI firstMember, bool syncWithClients);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartScoutingGroup(orig_StartScoutingGroup orig, BaboonBirdAI self, BaboonBirdAI firstMember, bool syncWithClients);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LeaveCurrentScoutingGroup(BaboonBirdAI self, bool sync);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LeaveCurrentScoutingGroup(orig_LeaveCurrentScoutingGroup orig, BaboonBirdAI self, bool sync);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LeaveScoutingGroupServerRpc(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LeaveScoutingGroupServerRpc(orig_LeaveScoutingGroupServerRpc orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LeaveScoutingGroupClientRpc(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LeaveScoutingGroupClientRpc(orig_LeaveScoutingGroupClientRpc orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartScoutingGroupServerRpc(BaboonBirdAI self, NetworkObjectReference leaderNetworkObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartScoutingGroupServerRpc(orig_StartScoutingGroupServerRpc orig, BaboonBirdAI self, NetworkObjectReference leaderNetworkObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartScoutingGroupClientRpc(BaboonBirdAI self, NetworkObjectReference leaderNetworkObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartScoutingGroupClientRpc(orig_StartScoutingGroupClientRpc orig, BaboonBirdAI self, NetworkObjectReference leaderNetworkObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_JoinScoutingGroupServerRpc(BaboonBirdAI self, NetworkObjectReference otherBaboonNetworkObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_JoinScoutingGroupServerRpc(orig_JoinScoutingGroupServerRpc orig, BaboonBirdAI self, NetworkObjectReference otherBaboonNetworkObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_JoinScoutingGroupClientRpc(BaboonBirdAI self, NetworkObjectReference otherBaboonNetworkObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_JoinScoutingGroupClientRpc(orig_JoinScoutingGroupClientRpc orig, BaboonBirdAI self, NetworkObjectReference otherBaboonNetworkObject);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CallToOtherBaboon(BaboonBirdAI self, BaboonBirdAI otherBaboon);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CallToOtherBaboon(orig_CallToOtherBaboon orig, BaboonBirdAI self, BaboonBirdAI otherBaboon);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartMiscAnimation(BaboonBirdAI self, int anim);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartMiscAnimation(orig_StartMiscAnimation orig, BaboonBirdAI self, int anim);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartMiscAnimationServerRpc(BaboonBirdAI self, int miscAnimationId);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartMiscAnimationServerRpc(orig_StartMiscAnimationServerRpc orig, BaboonBirdAI self, int miscAnimationId);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartMiscAnimationClientRpc(BaboonBirdAI self, int miscAnimationId);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartMiscAnimationClientRpc(orig_StartMiscAnimationClientRpc orig, BaboonBirdAI self, int miscAnimationId);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CalculateAnimationDirection(BaboonBirdAI self, float maxSpeed);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CalculateAnimationDirection(orig_CalculateAnimationDirection orig, BaboonBirdAI self, float maxSpeed);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___initializeVariables(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___initializeVariables(orig___initializeVariables orig, BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_InitializeRPCS_BaboonBirdAI();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_InitializeRPCS_BaboonBirdAI(orig_InitializeRPCS_BaboonBirdAI orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_3452382367(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_3452382367(orig___rpc_handler_3452382367 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_3856685904(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_3856685904(orig___rpc_handler_3856685904 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_2476579270(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_2476579270(orig___rpc_handler_2476579270 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_3749667856(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_3749667856(orig___rpc_handler_3749667856 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1418775270(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1418775270(orig___rpc_handler_1418775270 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1865475504(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1865475504(orig___rpc_handler_1865475504 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_869682226(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_869682226(orig___rpc_handler_869682226 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1564051222(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1564051222(orig___rpc_handler_1564051222 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1546030380(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1546030380(orig___rpc_handler_1546030380 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_3360048400(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_3360048400(orig___rpc_handler_3360048400 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_443869275(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_443869275(orig___rpc_handler_443869275 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1782649174(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1782649174(orig___rpc_handler_1782649174 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_3428942850(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_3428942850(orig___rpc_handler_3428942850 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_2073937320(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_2073937320(orig___rpc_handler_2073937320 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1806580287(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1806580287(orig___rpc_handler_1806580287 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1567928363(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1567928363(orig___rpc_handler_1567928363 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_3614203845(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_3614203845(orig___rpc_handler_3614203845 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1155909339(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1155909339(orig___rpc_handler_1155909339 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_3933590138(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_3933590138(orig___rpc_handler_3933590138 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_991811456(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_991811456(orig___rpc_handler_991811456 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1670979535(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1670979535(orig___rpc_handler_1670979535 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_2348332192(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_2348332192(orig___rpc_handler_2348332192 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_2459653399(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_2459653399(orig___rpc_handler_2459653399 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_696889160(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_696889160(orig___rpc_handler_696889160 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_3367846835(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_3367846835(orig___rpc_handler_3367846835 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1737299197(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1737299197(orig___rpc_handler_1737299197 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1775372234(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1775372234(orig___rpc_handler_1775372234 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1078565091(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1078565091(orig___rpc_handler_1078565091 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_1580405641(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_1580405641(orig___rpc_handler_1580405641 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___rpc_handler_3995026000(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___rpc_handler_3995026000(orig___rpc_handler_3995026000 orig, NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig___getTypeName(BaboonBirdAI self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook___getTypeName(orig___getTypeName orig, BaboonBirdAI self);

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SyncInitialValuesServerRpc SyncInitialValuesServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_SyncInitialValuesServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SyncInitialValuesServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SyncInitialValuesClientRpc SyncInitialValuesClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_SyncInitialValuesClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SyncInitialValuesClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LateUpdate LateUpdate
		{
			add
			{
				HookEndpointManager.Add<hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnCollideWithPlayer OnCollideWithPlayer
		{
			add
			{
				HookEndpointManager.Add<hook_OnCollideWithPlayer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnCollideWithPlayer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnCollideWithEnemy OnCollideWithEnemy
		{
			add
			{
				HookEndpointManager.Add<hook_OnCollideWithEnemy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnCollideWithEnemy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_HitEnemy HitEnemy
		{
			add
			{
				HookEndpointManager.Add<hook_HitEnemy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_HitEnemy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_KillEnemy KillEnemy
		{
			add
			{
				HookEndpointManager.Add<hook_KillEnemy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_KillEnemy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StopKillAnimation StopKillAnimation
		{
			add
			{
				HookEndpointManager.Add<hook_StopKillAnimation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StopKillAnimation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StabPlayerDeathAnimServerRpc StabPlayerDeathAnimServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_StabPlayerDeathAnimServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StabPlayerDeathAnimServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StabPlayerDeathAnimClientRpc StabPlayerDeathAnimClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_StabPlayerDeathAnimClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StabPlayerDeathAnimClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_killPlayerAnimation killPlayerAnimation
		{
			add
			{
				HookEndpointManager.Add<hook_killPlayerAnimation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_killPlayerAnimation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_InteractWithScrap InteractWithScrap
		{
			add
			{
				HookEndpointManager.Add<hook_InteractWithScrap>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_InteractWithScrap>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CanGrabScrap CanGrabScrap
		{
			add
			{
				HookEndpointManager.Add<hook_CanGrabScrap>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CanGrabScrap>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DropHeldItemAndSync DropHeldItemAndSync
		{
			add
			{
				HookEndpointManager.Add<hook_DropHeldItemAndSync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DropHeldItemAndSync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DropScrapServerRpc DropScrapServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_DropScrapServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DropScrapServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DropScrapClientRpc DropScrapClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_DropScrapClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DropScrapClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DropScrap DropScrap
		{
			add
			{
				HookEndpointManager.Add<hook_DropScrap>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DropScrap>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GrabItemAndSync GrabItemAndSync
		{
			add
			{
				HookEndpointManager.Add<hook_GrabItemAndSync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GrabItemAndSync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GrabScrapServerRpc GrabScrapServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_GrabScrapServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GrabScrapServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GrabScrapClientRpc GrabScrapClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_GrabScrapClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GrabScrapClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GrabScrap GrabScrap
		{
			add
			{
				HookEndpointManager.Add<hook_GrabScrap>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GrabScrap>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ReachedNodeInSearch ReachedNodeInSearch
		{
			add
			{
				HookEndpointManager.Add<hook_ReachedNodeInSearch>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ReachedNodeInSearch>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DoAIInterval DoAIInterval
		{
			add
			{
				HookEndpointManager.Add<hook_DoAIInterval>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DoAIInterval>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StopFocusingThreat StopFocusingThreat
		{
			add
			{
				HookEndpointManager.Add<hook_StopFocusingThreat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StopFocusingThreat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StopFocusingThreatServerRpc StopFocusingThreatServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_StopFocusingThreatServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StopFocusingThreatServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StopFocusingThreatClientRpc StopFocusingThreatClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_StopFocusingThreatClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StopFocusingThreatClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetAggressiveMode SetAggressiveMode
		{
			add
			{
				HookEndpointManager.Add<hook_SetAggressiveMode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetAggressiveMode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetAggressiveModeServerRpc SetAggressiveModeServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_SetAggressiveModeServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetAggressiveModeServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetAggressiveModeClientRpc SetAggressiveModeClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_SetAggressiveModeClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetAggressiveModeClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetThreatInView SetThreatInView
		{
			add
			{
				HookEndpointManager.Add<hook_SetThreatInView>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetThreatInView>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetThreatInViewServerRpc SetThreatInViewServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_SetThreatInViewServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetThreatInViewServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetThreatInViewClientRpc SetThreatInViewClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_SetThreatInViewClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetThreatInViewClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_EnemyEnterRestModeServerRpc EnemyEnterRestModeServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_EnemyEnterRestModeServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_EnemyEnterRestModeServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_EnemyEnterRestModeClientRpc EnemyEnterRestModeClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_EnemyEnterRestModeClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_EnemyEnterRestModeClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_EnemyGetUpServerRpc EnemyGetUpServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_EnemyGetUpServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_EnemyGetUpServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_EnemyGetUpClientRpc EnemyGetUpClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_EnemyGetUpClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_EnemyGetUpClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDrawGizmos OnDrawGizmos
		{
			add
			{
				HookEndpointManager.Add<hook_OnDrawGizmos>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDrawGizmos>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DetectNoise DetectNoise
		{
			add
			{
				HookEndpointManager.Add<hook_DetectNoise>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DetectNoise>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AnimateLooking AnimateLooking
		{
			add
			{
				HookEndpointManager.Add<hook_AnimateLooking>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AnimateLooking>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetComfortableDistanceToThreat GetComfortableDistanceToThreat
		{
			add
			{
				HookEndpointManager.Add<hook_GetComfortableDistanceToThreat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetComfortableDistanceToThreat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ReactToThreat ReactToThreat
		{
			add
			{
				HookEndpointManager.Add<hook_ReactToThreat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ReactToThreat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartFocusOnThreatServerRpc StartFocusOnThreatServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_StartFocusOnThreatServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartFocusOnThreatServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartFocusOnThreatClientRpc StartFocusOnThreatClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_StartFocusOnThreatClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartFocusOnThreatClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ReactToOtherBaboonSighted ReactToOtherBaboonSighted
		{
			add
			{
				HookEndpointManager.Add<hook_ReactToOtherBaboonSighted>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ReactToOtherBaboonSighted>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DoLOSCheck DoLOSCheck
		{
			add
			{
				HookEndpointManager.Add<hook_DoLOSCheck>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DoLOSCheck>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_PingBaboonInterest PingBaboonInterest
		{
			add
			{
				HookEndpointManager.Add<hook_PingBaboonInterest>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_PingBaboonInterest>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_PingBirdInterestServerRpc PingBirdInterestServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_PingBirdInterestServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_PingBirdInterestServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_PingBirdInterestClientRpc PingBirdInterestClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_PingBirdInterestClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_PingBirdInterestClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_JoinScoutingGroup JoinScoutingGroup
		{
			add
			{
				HookEndpointManager.Add<hook_JoinScoutingGroup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_JoinScoutingGroup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartScoutingGroup StartScoutingGroup
		{
			add
			{
				HookEndpointManager.Add<hook_StartScoutingGroup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartScoutingGroup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LeaveCurrentScoutingGroup LeaveCurrentScoutingGroup
		{
			add
			{
				HookEndpointManager.Add<hook_LeaveCurrentScoutingGroup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LeaveCurrentScoutingGroup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LeaveScoutingGroupServerRpc LeaveScoutingGroupServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_LeaveScoutingGroupServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LeaveScoutingGroupServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LeaveScoutingGroupClientRpc LeaveScoutingGroupClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_LeaveScoutingGroupClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LeaveScoutingGroupClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartScoutingGroupServerRpc StartScoutingGroupServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_StartScoutingGroupServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartScoutingGroupServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartScoutingGroupClientRpc StartScoutingGroupClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_StartScoutingGroupClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartScoutingGroupClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_JoinScoutingGroupServerRpc JoinScoutingGroupServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_JoinScoutingGroupServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_JoinScoutingGroupServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_JoinScoutingGroupClientRpc JoinScoutingGroupClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_JoinScoutingGroupClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_JoinScoutingGroupClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CallToOtherBaboon CallToOtherBaboon
		{
			add
			{
				HookEndpointManager.Add<hook_CallToOtherBaboon>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CallToOtherBaboon>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartMiscAnimation StartMiscAnimation
		{
			add
			{
				HookEndpointManager.Add<hook_StartMiscAnimation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartMiscAnimation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartMiscAnimationServerRpc StartMiscAnimationServerRpc
		{
			add
			{
				HookEndpointManager.Add<hook_StartMiscAnimationServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartMiscAnimationServerRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartMiscAnimationClientRpc StartMiscAnimationClientRpc
		{
			add
			{
				HookEndpointManager.Add<hook_StartMiscAnimationClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartMiscAnimationClientRpc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CalculateAnimationDirection CalculateAnimationDirection
		{
			add
			{
				HookEndpointManager.Add<hook_CalculateAnimationDirection>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CalculateAnimationDirection>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___initializeVariables __initializeVariables
		{
			add
			{
				HookEndpointManager.Add<hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_InitializeRPCS_BaboonBirdAI InitializeRPCS_BaboonBirdAI
		{
			add
			{
				HookEndpointManager.Add<hook_InitializeRPCS_BaboonBirdAI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_InitializeRPCS_BaboonBirdAI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_3452382367 __rpc_handler_3452382367
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_3452382367>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_3452382367>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_3856685904 __rpc_handler_3856685904
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_3856685904>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_3856685904>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_2476579270 __rpc_handler_2476579270
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_2476579270>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_2476579270>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_3749667856 __rpc_handler_3749667856
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_3749667856>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_3749667856>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_1418775270 __rpc_handler_1418775270
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_1418775270>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_1418775270>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_1865475504 __rpc_handler_1865475504
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_1865475504>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_1865475504>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_869682226 __rpc_handler_869682226
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_869682226>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_869682226>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_1564051222 __rpc_handler_1564051222
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_1564051222>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_1564051222>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_1546030380 __rpc_handler_1546030380
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_1546030380>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_1546030380>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_3360048400 __rpc_handler_3360048400
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_3360048400>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_3360048400>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_443869275 __rpc_handler_443869275
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_443869275>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_443869275>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_1782649174 __rpc_handler_1782649174
		{
			add
			{
				HookEndpointManager.Add<hook___rpc_handler_1782649174>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___rpc_handler_1782649174>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___rpc_handler_3428942850 __rpc_handler_3428942850

BooBoo Building/BepInEx/plugins/MMHOOK/MMHOOK_ClientNetworkTransform.dll

Decompiled 9 months ago
using System;
using System.ComponentModel;
using System.Reflection;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On;
using On.Unity.Netcode.Samples;
using On.__GEN;
using Unity.Netcode.Samples;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On
{
	public static class UnitySourceGeneratedAssemblyMonoScriptTypes_v1
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType orig_Get();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType hook_Get(orig_Get orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, object self);

		public static event hook_Get Get
		{
			add
			{
				HookEndpointManager.Add<hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class UnitySourceGeneratedAssemblyMonoScriptTypes_v1
	{
		public static event Manipulator Get
		{
			add
			{
				HookEndpointManager.Modify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Unity.Netcode.Samples
{
	public static class ClientNetworkTransform
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnNetworkSpawn(ClientNetworkTransform self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnNetworkSpawn(orig_OnNetworkSpawn orig, ClientNetworkTransform self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(ClientNetworkTransform self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, ClientNetworkTransform self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ClientNetworkTransform self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ClientNetworkTransform self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig___initializeVariables(ClientNetworkTransform self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook___initializeVariables(orig___initializeVariables orig, ClientNetworkTransform self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig___getTypeName(ClientNetworkTransform self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook___getTypeName(orig___getTypeName orig, ClientNetworkTransform self);

		public static event hook_OnNetworkSpawn OnNetworkSpawn
		{
			add
			{
				HookEndpointManager.Add<hook_OnNetworkSpawn>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnNetworkSpawn>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___initializeVariables __initializeVariables
		{
			add
			{
				HookEndpointManager.Add<hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook___getTypeName __getTypeName
		{
			add
			{
				HookEndpointManager.Add<hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Unity.Netcode.Samples
{
	public static class ClientNetworkTransform
	{
		public static event Manipulator OnNetworkSpawn
		{
			add
			{
				HookEndpointManager.Modify<On.Unity.Netcode.Samples.ClientNetworkTransform.hook_OnNetworkSpawn>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Unity.Netcode.Samples.ClientNetworkTransform.hook_OnNetworkSpawn>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.Unity.Netcode.Samples.ClientNetworkTransform.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Unity.Netcode.Samples.ClientNetworkTransform.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Unity.Netcode.Samples.ClientNetworkTransform.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Unity.Netcode.Samples.ClientNetworkTransform.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator __initializeVariables
		{
			add
			{
				HookEndpointManager.Modify<On.Unity.Netcode.Samples.ClientNetworkTransform.hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Unity.Netcode.Samples.ClientNetworkTransform.hook___initializeVariables>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator __getTypeName
		{
			add
			{
				HookEndpointManager.Modify<On.Unity.Netcode.Samples.ClientNetworkTransform.hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Unity.Netcode.Samples.ClientNetworkTransform.hook___getTypeName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.__GEN
{
	public static class NetworkVariableSerializationHelper
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_InitializeSerialization();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_InitializeSerialization(orig_InitializeSerialization orig);

		public static event hook_InitializeSerialization InitializeSerialization
		{
			add
			{
				HookEndpointManager.Add<hook_InitializeSerialization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_InitializeSerialization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.__GEN
{
	public static class NetworkVariableSerializationHelper
	{
		public static event Manipulator InitializeSerialization
		{
			add
			{
				HookEndpointManager.Modify<On.__GEN.NetworkVariableSerializationHelper.hook_InitializeSerialization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.__GEN.NetworkVariableSerializationHelper.hook_InitializeSerialization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace BepHookGen
{
	public class size6144
	{
	}
}

BooBoo Building/BepInEx/plugins/MMHOOK/MMHOOK_DissonanceVoip.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Dissonance;
using Dissonance.Audio;
using Dissonance.Audio.Capture;
using Dissonance.Audio.Codecs;
using Dissonance.Audio.Playback;
using Dissonance.Config;
using Dissonance.Datastructures;
using Dissonance.Networking;
using Dissonance.VAD;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using NAudio.Wave;
using On;
using On.Dissonance;
using On.Dissonance.Audio;
using On.Dissonance.Audio.Capture;
using On.Dissonance.Audio.Codecs;
using On.Dissonance.Audio.Codecs.Identity;
using On.Dissonance.Audio.Codecs.Opus;
using On.Dissonance.Audio.Codecs.Silence;
using On.Dissonance.Audio.Playback;
using On.Dissonance.Config;
using On.Dissonance.Datastructures;
using On.Dissonance.Extensions;
using On.Dissonance.Networking;
using On.Dissonance.Networking.Client;
using On.Dissonance.Threading;
using On.NAudio.Dsp;
using On.NAudio.Wave;
using UnityEngine;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On
{
	public static class UnitySourceGeneratedAssemblyMonoScriptTypes_v1
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType orig_Get();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType hook_Get(orig_Get orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, object self);

		public static event hook_Get Get
		{
			add
			{
				HookEndpointManager.Add<hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class UnitySourceGeneratedAssemblyMonoScriptTypes_v1
	{
		public static event Manipulator Get
		{
			add
			{
				HookEndpointManager.Modify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.NAudio.Dsp
{
	public static class WdlResampler
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetMode(object self, bool interp, int filtercnt, bool sinc, int sinc_size, int sinc_interpsize);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetMode(orig_SetMode orig, object self, bool interp, int filtercnt, bool sinc, int sinc_size, int sinc_interpsize);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetFilterParms(object self, float filterpos, float filterq);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetFilterParms(orig_SetFilterParms orig, object self, float filterpos, float filterq);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetFeedMode(object self, bool wantInputDriven);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetFeedMode(orig_SetFeedMode orig, object self, bool wantInputDriven);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Reset(object self, double fracpos);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Reset(orig_Reset orig, object self, double fracpos);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetRates(object self, double rate_in, double rate_out);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetRates(orig_SetRates orig, object self, double rate_in, double rate_out);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate double orig_GetCurrentLatency(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate double hook_GetCurrentLatency(orig_GetCurrentLatency orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_ResamplePrepare(object self, int out_samples, int nch, out float[] inbuffer, out int inbufferOffset);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_ResamplePrepare(orig_ResamplePrepare orig, object self, int out_samples, int nch, out float[] inbuffer, out int inbufferOffset);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_ResampleOut(object self, float[] outBuffer, int outBufferIndex, int nsamples_in, int nsamples_out, int nch);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_ResampleOut(orig_ResampleOut orig, object self, float[] outBuffer, int outBufferIndex, int nsamples_in, int nsamples_out, int nch);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_BuildLowPass(object self, double filtpos);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_BuildLowPass(orig_BuildLowPass orig, object self, double filtpos);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SincSample(object self, float[] outBuffer, int outBufferIndex, float[] inBuffer, int inBufferIndex, double fracpos, int nch, float[] filter, int filterIndex, int filtsz);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SincSample(orig_SincSample orig, object self, float[] outBuffer, int outBufferIndex, float[] inBuffer, int inBufferIndex, double fracpos, int nch, float[] filter, int filterIndex, int filtsz);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SincSample1(object self, float[] outBuffer, int outBufferIndex, float[] inBuffer, int inBufferIndex, double fracpos, float[] filter, int filterIndex, int filtsz);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SincSample1(orig_SincSample1 orig, object self, float[] outBuffer, int outBufferIndex, float[] inBuffer, int inBufferIndex, double fracpos, float[] filter, int filterIndex, int filtsz);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SincSample2(object self, float[] outptr, int outBufferIndex, float[] inBuffer, int inBufferIndex, double fracpos, float[] filter, int filterIndex, int filtsz);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SincSample2(orig_SincSample2 orig, object self, float[] outptr, int outBufferIndex, float[] inBuffer, int inBufferIndex, double fracpos, float[] filter, int filterIndex, int filtsz);

		public static class WDL_Resampler_IIRFilter
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_ctor(object self);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_ctor(orig_ctor orig, object self);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_Reset(object self);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_Reset(orig_Reset orig, object self);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_setParms(object self, double fpos, double Q);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_setParms(orig_setParms orig, object self, double fpos, double Q);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_Apply(object self, float[] inBuffer, int inIndex, float[] outBuffer, int outIndex, int ns, int span, int w);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_Apply(orig_Apply orig, object self, float[] inBuffer, int inIndex, float[] outBuffer, int outIndex, int ns, int span, int w);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate double orig_denormal_filter_float(object self, float x);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate double hook_denormal_filter_float(orig_denormal_filter_float orig, object self, float x);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate double orig_denormal_filter_double(object self, double x);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate double hook_denormal_filter_double(orig_denormal_filter_double orig, object self, double x);

			public static event hook_ctor ctor
			{
				add
				{
					HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_Reset Reset
			{
				add
				{
					HookEndpointManager.Add<hook_Reset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_Reset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_setParms setParms
			{
				add
				{
					HookEndpointManager.Add<hook_setParms>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_setParms>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_Apply Apply
			{
				add
				{
					HookEndpointManager.Add<hook_Apply>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_Apply>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_denormal_filter_float denormal_filter_float
			{
				add
				{
					HookEndpointManager.Add<hook_denormal_filter_float>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_denormal_filter_float>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_denormal_filter_double denormal_filter_double
			{
				add
				{
					HookEndpointManager.Add<hook_denormal_filter_double>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_denormal_filter_double>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetMode SetMode
		{
			add
			{
				HookEndpointManager.Add<hook_SetMode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetMode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetFilterParms SetFilterParms
		{
			add
			{
				HookEndpointManager.Add<hook_SetFilterParms>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetFilterParms>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetFeedMode SetFeedMode
		{
			add
			{
				HookEndpointManager.Add<hook_SetFeedMode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetFeedMode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Reset Reset
		{
			add
			{
				HookEndpointManager.Add<hook_Reset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Reset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetRates SetRates
		{
			add
			{
				HookEndpointManager.Add<hook_SetRates>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetRates>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetCurrentLatency GetCurrentLatency
		{
			add
			{
				HookEndpointManager.Add<hook_GetCurrentLatency>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCurrentLatency>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ResamplePrepare ResamplePrepare
		{
			add
			{
				HookEndpointManager.Add<hook_ResamplePrepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ResamplePrepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ResampleOut ResampleOut
		{
			add
			{
				HookEndpointManager.Add<hook_ResampleOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ResampleOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BuildLowPass BuildLowPass
		{
			add
			{
				HookEndpointManager.Add<hook_BuildLowPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BuildLowPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SincSample SincSample
		{
			add
			{
				HookEndpointManager.Add<hook_SincSample>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SincSample>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SincSample1 SincSample1
		{
			add
			{
				HookEndpointManager.Add<hook_SincSample1>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SincSample1>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SincSample2 SincSample2
		{
			add
			{
				HookEndpointManager.Add<hook_SincSample2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SincSample2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.NAudio.Dsp
{
	public static class WdlResampler
	{
		public static class WDL_Resampler_IIRFilter
		{
			public static event Manipulator ctor
			{
				add
				{
					HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator Reset
			{
				add
				{
					HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_Reset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_Reset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator setParms
			{
				add
				{
					HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_setParms>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_setParms>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator Apply
			{
				add
				{
					HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_Apply>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_Apply>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator denormal_filter_float
			{
				add
				{
					HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_denormal_filter_float>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_denormal_filter_float>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator denormal_filter_double
			{
				add
				{
					HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_denormal_filter_double>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.WDL_Resampler_IIRFilter.hook_denormal_filter_double>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetMode
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_SetMode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_SetMode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetFilterParms
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_SetFilterParms>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_SetFilterParms>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetFeedMode
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_SetFeedMode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_SetFeedMode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Reset
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_Reset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_Reset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetRates
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_SetRates>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_SetRates>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetCurrentLatency
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_GetCurrentLatency>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_GetCurrentLatency>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ResamplePrepare
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_ResamplePrepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_ResamplePrepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ResampleOut
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_ResampleOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_ResampleOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator BuildLowPass
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_BuildLowPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_BuildLowPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SincSample
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_SincSample>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_SincSample>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SincSample1
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_SincSample1>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_SincSample1>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SincSample2
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Dsp.WdlResampler.hook_SincSample2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Dsp.WdlResampler.hook_SincSample2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.NAudio.Wave
{
	public static class WaveFileWriter
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor_Stream_WaveFormat(Stream self, Stream outStream, WaveFormat format);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor_Stream_WaveFormat(orig_ctor_Stream_WaveFormat orig, Stream self, Stream outStream, WaveFormat format);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor_string_WaveFormat(Stream self, string filename, WaveFormat format);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor_string_WaveFormat(orig_ctor_string_WaveFormat orig, Stream self, string filename, WaveFormat format);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_WriteDataChunkHeader(Stream self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_WriteDataChunkHeader(orig_WriteDataChunkHeader orig, Stream self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CreateFactChunk(Stream self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CreateFactChunk(orig_CreateFactChunk orig, Stream self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_HasFactChunk(Stream self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_HasFactChunk(orig_HasFactChunk orig, Stream self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_Read(Stream self, byte[] buffer, int offset, int count);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_Read(orig_Read orig, Stream self, byte[] buffer, int offset, int count);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate long orig_Seek(Stream self, long offset, SeekOrigin origin);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate long hook_Seek(orig_Seek orig, Stream self, long offset, SeekOrigin origin);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetLength(Stream self, long value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetLength(orig_SetLength orig, Stream self, long value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Write(Stream self, byte[] data, int offset, int count);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Write(orig_Write orig, Stream self, byte[] data, int offset, int count);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_WriteSample(Stream self, float sample);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_WriteSample(orig_WriteSample orig, Stream self, float sample);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_WriteSamples(Stream self, float[] samples, int offset, int count);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_WriteSamples(orig_WriteSamples orig, Stream self, float[] samples, int offset, int count);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Flush(Stream self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Flush(orig_Flush orig, Stream self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Dispose(Stream self, bool disposing);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Dispose(orig_Dispose orig, Stream self, bool disposing);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateHeader(Stream self, BinaryWriter writer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateHeader(orig_UpdateHeader orig, Stream self, BinaryWriter writer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateDataChunk(Stream self, BinaryWriter writer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateDataChunk(orig_UpdateDataChunk orig, Stream self, BinaryWriter writer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateRiffChunk(Stream self, BinaryWriter writer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateRiffChunk(orig_UpdateRiffChunk orig, Stream self, BinaryWriter writer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateFactChunk(Stream self, BinaryWriter writer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateFactChunk(orig_UpdateFactChunk orig, Stream self, BinaryWriter writer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Finalize(Stream self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Finalize(orig_Finalize orig, Stream self);

		public static event hook_ctor_Stream_WaveFormat ctor_Stream_WaveFormat
		{
			add
			{
				HookEndpointManager.Add<hook_ctor_Stream_WaveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor_Stream_WaveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor_string_WaveFormat ctor_string_WaveFormat
		{
			add
			{
				HookEndpointManager.Add<hook_ctor_string_WaveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor_string_WaveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_WriteDataChunkHeader WriteDataChunkHeader
		{
			add
			{
				HookEndpointManager.Add<hook_WriteDataChunkHeader>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_WriteDataChunkHeader>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CreateFactChunk CreateFactChunk
		{
			add
			{
				HookEndpointManager.Add<hook_CreateFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CreateFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_HasFactChunk HasFactChunk
		{
			add
			{
				HookEndpointManager.Add<hook_HasFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_HasFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Read Read
		{
			add
			{
				HookEndpointManager.Add<hook_Read>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Read>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Seek Seek
		{
			add
			{
				HookEndpointManager.Add<hook_Seek>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Seek>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetLength SetLength
		{
			add
			{
				HookEndpointManager.Add<hook_SetLength>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetLength>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Write Write
		{
			add
			{
				HookEndpointManager.Add<hook_Write>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Write>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_WriteSample WriteSample
		{
			add
			{
				HookEndpointManager.Add<hook_WriteSample>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_WriteSample>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_WriteSamples WriteSamples
		{
			add
			{
				HookEndpointManager.Add<hook_WriteSamples>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_WriteSamples>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Flush Flush
		{
			add
			{
				HookEndpointManager.Add<hook_Flush>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Flush>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Dispose Dispose
		{
			add
			{
				HookEndpointManager.Add<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateHeader UpdateHeader
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateHeader>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateHeader>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateDataChunk UpdateDataChunk
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateDataChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateDataChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateRiffChunk UpdateRiffChunk
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateRiffChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateRiffChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateFactChunk UpdateFactChunk
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public new static event hook_Finalize Finalize
		{
			add
			{
				HookEndpointManager.Add<hook_Finalize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Finalize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.NAudio.Wave
{
	public static class WaveFileWriter
	{
		public static event Manipulator ctor_Stream_WaveFormat
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_ctor_Stream_WaveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_ctor_Stream_WaveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor_string_WaveFormat
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_ctor_string_WaveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_ctor_string_WaveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator WriteDataChunkHeader
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_WriteDataChunkHeader>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_WriteDataChunkHeader>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CreateFactChunk
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_CreateFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_CreateFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator HasFactChunk
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_HasFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_HasFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Read
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_Read>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_Read>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Seek
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_Seek>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_Seek>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetLength
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_SetLength>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_SetLength>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Write
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_Write>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_Write>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator WriteSample
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_WriteSample>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_WriteSample>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator WriteSamples
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_WriteSamples>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_WriteSamples>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Flush
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_Flush>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_Flush>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Dispose
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator UpdateHeader
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_UpdateHeader>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_UpdateHeader>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator UpdateDataChunk
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_UpdateDataChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_UpdateDataChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator UpdateRiffChunk
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_UpdateRiffChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_UpdateRiffChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator UpdateFactChunk
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_UpdateFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_UpdateFactChunk>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public new static event Manipulator Finalize
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFileWriter.hook_Finalize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFileWriter.hook_Finalize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.NAudio.Wave
{
	public static class WaveFormat
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(WaveFormat self, int sampleRate, int channels);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, WaveFormat self, int sampleRate, int channels);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_Equals(WaveFormat self, WaveFormat other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_Equals(orig_Equals orig, WaveFormat self, WaveFormat other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetHashCode(WaveFormat self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetHashCode(orig_GetHashCode orig, WaveFormat self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_ToString(WaveFormat self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_ToString(orig_ToString orig, WaveFormat self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public new static event hook_Equals Equals
		{
			add
			{
				HookEndpointManager.Add<hook_Equals>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Equals>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public new static event hook_GetHashCode GetHashCode
		{
			add
			{
				HookEndpointManager.Add<hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public new static event hook_ToString ToString
		{
			add
			{
				HookEndpointManager.Add<hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.NAudio.Wave
{
	public static class WaveFormat
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFormat.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFormat.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public new static event Manipulator Equals
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFormat.hook_Equals>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFormat.hook_Equals>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public new static event Manipulator GetHashCode
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFormat.hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFormat.hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public new static event Manipulator ToString
		{
			add
			{
				HookEndpointManager.Modify<On.NAudio.Wave.WaveFormat.hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.NAudio.Wave.WaveFormat.hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Dissonance
{
	public static class BaseCommsTrigger
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDestroy(BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDestroy(orig_OnDestroy orig, BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_TokensModified(BaseCommsTrigger self, string token);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_TokensModified(orig_TokensModified orig, BaseCommsTrigger self, string token);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_ContainsToken(BaseCommsTrigger self, string token);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_ContainsToken(orig_ContainsToken orig, BaseCommsTrigger self, string token);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_AddToken(BaseCommsTrigger self, string token);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_AddToken(orig_AddToken orig, BaseCommsTrigger self, string token);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_RemoveToken(BaseCommsTrigger self, string token);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_RemoveToken(orig_RemoveToken orig, BaseCommsTrigger self, string token);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ColliderTriggerChanged(BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ColliderTriggerChanged(orig_ColliderTriggerChanged orig, BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnTriggerEnter2D(BaseCommsTrigger self, Collider2D other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnTriggerEnter2D(orig_OnTriggerEnter2D orig, BaseCommsTrigger self, Collider2D other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnTriggerExit2D(BaseCommsTrigger self, Collider2D other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnTriggerExit2D(orig_OnTriggerExit2D orig, BaseCommsTrigger self, Collider2D other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnTriggerEnter(BaseCommsTrigger self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnTriggerEnter(orig_OnTriggerEnter orig, BaseCommsTrigger self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnTriggerExit(BaseCommsTrigger self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnTriggerExit(orig_OnTriggerExit orig, BaseCommsTrigger self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_ColliderTriggerFilter(BaseCommsTrigger self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_ColliderTriggerFilter(orig_ColliderTriggerFilter orig, BaseCommsTrigger self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_ColliderTriggerFilter2D(BaseCommsTrigger self, Collider2D other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_ColliderTriggerFilter2D(orig_ColliderTriggerFilter2D orig, BaseCommsTrigger self, Collider2D other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DissonanceComms orig_FindLocalVoiceComm(BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DissonanceComms hook_FindLocalVoiceComm(orig_FindLocalVoiceComm orig, BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckVoiceComm(BaseCommsTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckVoiceComm(orig_CheckVoiceComm orig, BaseCommsTrigger self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDestroy OnDestroy
		{
			add
			{
				HookEndpointManager.Add<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_TokensModified TokensModified
		{
			add
			{
				HookEndpointManager.Add<hook_TokensModified>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_TokensModified>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ContainsToken ContainsToken
		{
			add
			{
				HookEndpointManager.Add<hook_ContainsToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ContainsToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddToken AddToken
		{
			add
			{
				HookEndpointManager.Add<hook_AddToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_RemoveToken RemoveToken
		{
			add
			{
				HookEndpointManager.Add<hook_RemoveToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RemoveToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ColliderTriggerChanged ColliderTriggerChanged
		{
			add
			{
				HookEndpointManager.Add<hook_ColliderTriggerChanged>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ColliderTriggerChanged>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnTriggerEnter2D OnTriggerEnter2D
		{
			add
			{
				HookEndpointManager.Add<hook_OnTriggerEnter2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnTriggerEnter2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnTriggerExit2D OnTriggerExit2D
		{
			add
			{
				HookEndpointManager.Add<hook_OnTriggerExit2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnTriggerExit2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnTriggerEnter OnTriggerEnter
		{
			add
			{
				HookEndpointManager.Add<hook_OnTriggerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnTriggerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnTriggerExit OnTriggerExit
		{
			add
			{
				HookEndpointManager.Add<hook_OnTriggerExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnTriggerExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ColliderTriggerFilter ColliderTriggerFilter
		{
			add
			{
				HookEndpointManager.Add<hook_ColliderTriggerFilter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ColliderTriggerFilter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ColliderTriggerFilter2D ColliderTriggerFilter2D
		{
			add
			{
				HookEndpointManager.Add<hook_ColliderTriggerFilter2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ColliderTriggerFilter2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_FindLocalVoiceComm FindLocalVoiceComm
		{
			add
			{
				HookEndpointManager.Add<hook_FindLocalVoiceComm>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_FindLocalVoiceComm>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CheckVoiceComm CheckVoiceComm
		{
			add
			{
				HookEndpointManager.Add<hook_CheckVoiceComm>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckVoiceComm>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Dissonance
{
	public static class BaseCommsTrigger
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Start
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnEnable
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDestroy
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator TokensModified
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_TokensModified>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_TokensModified>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ContainsToken
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_ContainsToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_ContainsToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AddToken
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_AddToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_AddToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator RemoveToken
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_RemoveToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_RemoveToken>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ColliderTriggerChanged
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_ColliderTriggerChanged>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_ColliderTriggerChanged>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnTriggerEnter2D
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_OnTriggerEnter2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_OnTriggerEnter2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnTriggerExit2D
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_OnTriggerExit2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_OnTriggerExit2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnTriggerEnter
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_OnTriggerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_OnTriggerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnTriggerExit
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_OnTriggerExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_OnTriggerExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ColliderTriggerFilter
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_ColliderTriggerFilter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_ColliderTriggerFilter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ColliderTriggerFilter2D
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_ColliderTriggerFilter2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_ColliderTriggerFilter2D>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator FindLocalVoiceComm
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_FindLocalVoiceComm>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_FindLocalVoiceComm>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CheckVoiceComm
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.BaseCommsTrigger.hook_CheckVoiceComm>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.BaseCommsTrigger.hook_CheckVoiceComm>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Dissonance
{
	public static class ChannelProperties
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ChannelProperties self, object defaultPriority);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ChannelProperties self, object defaultPriority);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Dissonance
{
	public static class ChannelProperties
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.ChannelProperties.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.ChannelProperties.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Dissonance
{
	public static class PlayerChannel
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ref PlayerChannel self, ushort subscriptionId, string playerId, PlayerChannels channels, ChannelProperties properties);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ref PlayerChannel self, ushort subscriptionId, string playerId, PlayerChannels channels, ChannelProperties properties);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Dispose(ref PlayerChannel self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Dispose(orig_Dispose orig, ref PlayerChannel self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CheckValidProperties(ref PlayerChannel self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CheckValidProperties(orig_CheckValidProperties orig, ref PlayerChannel self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_Equals_PlayerChannel(ref PlayerChannel self, PlayerChannel other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_Equals_PlayerChannel(orig_Equals_PlayerChannel orig, ref PlayerChannel self, PlayerChannel other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_Equals_object(ref PlayerChannel self, object obj);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_Equals_object(orig_Equals_object orig, ref PlayerChannel self, object obj);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetHashCode(ref PlayerChannel self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetHashCode(orig_GetHashCode orig, ref PlayerChannel self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Dispose Dispose
		{
			add
			{
				HookEndpointManager.Add<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CheckValidProperties CheckValidProperties
		{
			add
			{
				HookEndpointManager.Add<hook_CheckValidProperties>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckValidProperties>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Equals_PlayerChannel Equals_PlayerChannel
		{
			add
			{
				HookEndpointManager.Add<hook_Equals_PlayerChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Equals_PlayerChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Equals_object Equals_object
		{
			add
			{
				HookEndpointManager.Add<hook_Equals_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Equals_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public new static event hook_GetHashCode GetHashCode
		{
			add
			{
				HookEndpointManager.Add<hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Dissonance
{
	public static class PlayerChannel
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.PlayerChannel.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.PlayerChannel.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Dispose
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.PlayerChannel.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.PlayerChannel.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CheckValidProperties
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.PlayerChannel.hook_CheckValidProperties>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.PlayerChannel.hook_CheckValidProperties>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Equals_PlayerChannel
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.PlayerChannel.hook_Equals_PlayerChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.PlayerChannel.hook_Equals_PlayerChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Equals_object
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.PlayerChannel.hook_Equals_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.PlayerChannel.hook_Equals_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public new static event Manipulator GetHashCode
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.PlayerChannel.hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.PlayerChannel.hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Dissonance
{
	public static class PlayerChannels
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(PlayerChannels self, object priorityProvider);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, PlayerChannels self, object priorityProvider);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate PlayerChannel orig_CreateChannel(PlayerChannels self, ushort subscriptionId, string channelId, ChannelProperties properties);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate PlayerChannel hook_CreateChannel(orig_CreateChannel orig, PlayerChannels self, ushort subscriptionId, string channelId, ChannelProperties properties);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CreateChannel CreateChannel
		{
			add
			{
				HookEndpointManager.Add<hook_CreateChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CreateChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Dissonance
{
	public static class PlayerChannels
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.PlayerChannels.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.PlayerChannels.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CreateChannel
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.PlayerChannels.hook_CreateChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.PlayerChannels.hook_CreateChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Dissonance
{
	public static class RemoteChannel
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ref RemoteChannel self, string targetName, ChannelType type, PlaybackOptions options);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ref RemoteChannel self, string targetName, ChannelType type, PlaybackOptions options);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Dissonance
{
	public static class RemoteChannel
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.RemoteChannel.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.RemoteChannel.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Dissonance
{
	public static class RoomChannel
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ref RoomChannel self, ushort subscriptionId, string roomId, RoomChannels channels, ChannelProperties properties);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ref RoomChannel self, ushort subscriptionId, string roomId, RoomChannels channels, ChannelProperties properties);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Dispose(ref RoomChannel self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Dispose(orig_Dispose orig, ref RoomChannel self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CheckValidProperties(ref RoomChannel self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CheckValidProperties(orig_CheckValidProperties orig, ref RoomChannel self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_Equals_RoomChannel(ref RoomChannel self, RoomChannel other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_Equals_RoomChannel(orig_Equals_RoomChannel orig, ref RoomChannel self, RoomChannel other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_Equals_object(ref RoomChannel self, object obj);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_Equals_object(orig_Equals_object orig, ref RoomChannel self, object obj);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetHashCode(ref RoomChannel self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetHashCode(orig_GetHashCode orig, ref RoomChannel self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Dispose Dispose
		{
			add
			{
				HookEndpointManager.Add<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CheckValidProperties CheckValidProperties
		{
			add
			{
				HookEndpointManager.Add<hook_CheckValidProperties>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckValidProperties>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Equals_RoomChannel Equals_RoomChannel
		{
			add
			{
				HookEndpointManager.Add<hook_Equals_RoomChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Equals_RoomChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Equals_object Equals_object
		{
			add
			{
				HookEndpointManager.Add<hook_Equals_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Equals_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public new static event hook_GetHashCode GetHashCode
		{
			add
			{
				HookEndpointManager.Add<hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Dissonance
{
	public static class RoomChannel
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.RoomChannel.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.RoomChannel.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Dispose
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.RoomChannel.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.RoomChannel.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CheckValidProperties
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.RoomChannel.hook_CheckValidProperties>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.RoomChannel.hook_CheckValidProperties>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Equals_RoomChannel
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.RoomChannel.hook_Equals_RoomChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.RoomChannel.hook_Equals_RoomChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Equals_object
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.RoomChannel.hook_Equals_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.RoomChannel.hook_Equals_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public new static event Manipulator GetHashCode
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.RoomChannel.hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.RoomChannel.hook_GetHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.RoomChannel.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.RoomChannel.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Dissonance
{
	public static class RoomChannels
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(RoomChannels self, object priorityProvider);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, RoomChannels self, object priorityProvider);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate RoomChannel orig_CreateChannel(RoomChannels self, ushort subscriptionId, string channelId, ChannelProperties properties);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate RoomChannel hook_CreateChannel(orig_CreateChannel orig, RoomChannels self, ushort subscriptionId, string channelId, ChannelProperties properties);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CreateChannel CreateChannel
		{
			add
			{
				HookEndpointManager.Add<hook_CreateChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CreateChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Dissonance
{
	public static class RoomChannels
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.RoomChannels.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.RoomChannels.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CreateChannel
		{
			add
			{
				HookEndpointManager.Modify<On.Dissonance.RoomChannels.hook_CreateChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Dissonance.RoomChannels.hook_CreateChannel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Dissonance
{
	public static class CodecSettings
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ref CodecSettings self, Codec codec, uint frameSize, int sampleRate);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ref CodecSettings self, Codec codec, uint frameSize, int sampleRate);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_ToString(ref CodecSettings self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_ToString(orig_ToString orig, ref CodecSettings self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public new static event hook_ToString ToString
		{
			add
			{
				HookEndpointManager.Add<hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)

BooBoo Building/BepInEx/plugins/MMHOOK/MMHOOK_Facepunch Transport for Netcode for GameObjects.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using Netcode.Transports.Facepunch;
using On;
using On.Netcode.Transports.Facepunch;
using On.__GEN;
using Steamworks.Data;
using Unity.Netcode;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On
{
	public static class UnitySourceGeneratedAssemblyMonoScriptTypes_v1
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType orig_Get();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType hook_Get(orig_Get orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, object self);

		public static event hook_Get Get
		{
			add
			{
				HookEndpointManager.Add<hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class UnitySourceGeneratedAssemblyMonoScriptTypes_v1
	{
		public static event Manipulator Get
		{
			add
			{
				HookEndpointManager.Modify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_Get>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnitySourceGeneratedAssemblyMonoScriptTypes_v1.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Netcode.Transports.Facepunch
{
	public static class FacepunchTransport
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDestroy(FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDestroy(orig_OnDestroy orig, FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DisconnectLocalClient(FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DisconnectLocalClient(orig_DisconnectLocalClient orig, FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DisconnectRemoteClient(FacepunchTransport self, ulong clientId);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DisconnectRemoteClient(orig_DisconnectRemoteClient orig, FacepunchTransport self, ulong clientId);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ulong orig_GetCurrentRtt(FacepunchTransport self, ulong clientId);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ulong hook_GetCurrentRtt(orig_GetCurrentRtt orig, FacepunchTransport self, ulong clientId);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Initialize(FacepunchTransport self, NetworkManager networkManager);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Initialize(orig_Initialize orig, FacepunchTransport self, NetworkManager networkManager);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate SendType orig_NetworkDeliveryToSendType(FacepunchTransport self, NetworkDelivery delivery);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate SendType hook_NetworkDeliveryToSendType(orig_NetworkDeliveryToSendType orig, FacepunchTransport self, NetworkDelivery delivery);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Shutdown(FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Shutdown(orig_Shutdown orig, FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Send(FacepunchTransport self, ulong clientId, ArraySegment<byte> data, NetworkDelivery delivery);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Send(orig_Send orig, FacepunchTransport self, ulong clientId, ArraySegment<byte> data, NetworkDelivery delivery);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate NetworkEvent orig_PollEvent(FacepunchTransport self, out ulong clientId, out ArraySegment<byte> payload, out float receiveTime);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate NetworkEvent hook_PollEvent(orig_PollEvent orig, FacepunchTransport self, out ulong clientId, out ArraySegment<byte> payload, out float receiveTime);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_StartClient(FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_StartClient(orig_StartClient orig, FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_StartServer(FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_StartServer(orig_StartServer orig, FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_EnsurePayloadCapacity(FacepunchTransport self, int size);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_EnsurePayloadCapacity(orig_EnsurePayloadCapacity orig, FacepunchTransport self, int size);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Steamworks_IConnectionManager_OnConnecting(FacepunchTransport self, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Steamworks_IConnectionManager_OnConnecting(orig_Steamworks_IConnectionManager_OnConnecting orig, FacepunchTransport self, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Steamworks_IConnectionManager_OnConnected(FacepunchTransport self, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Steamworks_IConnectionManager_OnConnected(orig_Steamworks_IConnectionManager_OnConnected orig, FacepunchTransport self, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Steamworks_IConnectionManager_OnDisconnected(FacepunchTransport self, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Steamworks_IConnectionManager_OnDisconnected(orig_Steamworks_IConnectionManager_OnDisconnected orig, FacepunchTransport self, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Steamworks_IConnectionManager_OnMessage(FacepunchTransport self, IntPtr data, int size, long messageNum, long recvTime, int channel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Steamworks_IConnectionManager_OnMessage(orig_Steamworks_IConnectionManager_OnMessage orig, FacepunchTransport self, IntPtr data, int size, long messageNum, long recvTime, int channel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Steamworks_ISocketManager_OnConnecting(FacepunchTransport self, Connection connection, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Steamworks_ISocketManager_OnConnecting(orig_Steamworks_ISocketManager_OnConnecting orig, FacepunchTransport self, Connection connection, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Steamworks_ISocketManager_OnConnected(FacepunchTransport self, Connection connection, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Steamworks_ISocketManager_OnConnected(orig_Steamworks_ISocketManager_OnConnected orig, FacepunchTransport self, Connection connection, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Steamworks_ISocketManager_OnDisconnected(FacepunchTransport self, Connection connection, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Steamworks_ISocketManager_OnDisconnected(orig_Steamworks_ISocketManager_OnDisconnected orig, FacepunchTransport self, Connection connection, ConnectionInfo info);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Steamworks_ISocketManager_OnMessage(FacepunchTransport self, Connection connection, NetIdentity identity, IntPtr data, int size, long messageNum, long recvTime, int channel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Steamworks_ISocketManager_OnMessage(orig_Steamworks_ISocketManager_OnMessage orig, FacepunchTransport self, Connection connection, NetIdentity identity, IntPtr data, int size, long messageNum, long recvTime, int channel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IEnumerator orig_InitSteamworks(FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IEnumerator hook_InitSteamworks(orig_InitSteamworks orig, FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(FacepunchTransport self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, FacepunchTransport self);

		public static class Client
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_ctor(object self);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_ctor(orig_ctor orig, object self);

			public static event hook_ctor ctor
			{
				add
				{
					HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDestroy OnDestroy
		{
			add
			{
				HookEndpointManager.Add<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DisconnectLocalClient DisconnectLocalClient
		{
			add
			{
				HookEndpointManager.Add<hook_DisconnectLocalClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DisconnectLocalClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DisconnectRemoteClient DisconnectRemoteClient
		{
			add
			{
				HookEndpointManager.Add<hook_DisconnectRemoteClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DisconnectRemoteClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetCurrentRtt GetCurrentRtt
		{
			add
			{
				HookEndpointManager.Add<hook_GetCurrentRtt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCurrentRtt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Initialize Initialize
		{
			add
			{
				HookEndpointManager.Add<hook_Initialize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Initialize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_NetworkDeliveryToSendType NetworkDeliveryToSendType
		{
			add
			{
				HookEndpointManager.Add<hook_NetworkDeliveryToSendType>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_NetworkDeliveryToSendType>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Shutdown Shutdown
		{
			add
			{
				HookEndpointManager.Add<hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Send Send
		{
			add
			{
				HookEndpointManager.Add<hook_Send>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Send>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_PollEvent PollEvent
		{
			add
			{
				HookEndpointManager.Add<hook_PollEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_PollEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartClient StartClient
		{
			add
			{
				HookEndpointManager.Add<hook_StartClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartServer StartServer
		{
			add
			{
				HookEndpointManager.Add<hook_StartServer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartServer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_EnsurePayloadCapacity EnsurePayloadCapacity
		{
			add
			{
				HookEndpointManager.Add<hook_EnsurePayloadCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_EnsurePayloadCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Steamworks_IConnectionManager_OnConnecting Steamworks_IConnectionManager_OnConnecting
		{
			add
			{
				HookEndpointManager.Add<hook_Steamworks_IConnectionManager_OnConnecting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Steamworks_IConnectionManager_OnConnecting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Steamworks_IConnectionManager_OnConnected Steamworks_IConnectionManager_OnConnected
		{
			add
			{
				HookEndpointManager.Add<hook_Steamworks_IConnectionManager_OnConnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Steamworks_IConnectionManager_OnConnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Steamworks_IConnectionManager_OnDisconnected Steamworks_IConnectionManager_OnDisconnected
		{
			add
			{
				HookEndpointManager.Add<hook_Steamworks_IConnectionManager_OnDisconnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Steamworks_IConnectionManager_OnDisconnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Steamworks_IConnectionManager_OnMessage Steamworks_IConnectionManager_OnMessage
		{
			add
			{
				HookEndpointManager.Add<hook_Steamworks_IConnectionManager_OnMessage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Steamworks_IConnectionManager_OnMessage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Steamworks_ISocketManager_OnConnecting Steamworks_ISocketManager_OnConnecting
		{
			add
			{
				HookEndpointManager.Add<hook_Steamworks_ISocketManager_OnConnecting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Steamworks_ISocketManager_OnConnecting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Steamworks_ISocketManager_OnConnected Steamworks_ISocketManager_OnConnected
		{
			add
			{
				HookEndpointManager.Add<hook_Steamworks_ISocketManager_OnConnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Steamworks_ISocketManager_OnConnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Steamworks_ISocketManager_OnDisconnected Steamworks_ISocketManager_OnDisconnected
		{
			add
			{
				HookEndpointManager.Add<hook_Steamworks_ISocketManager_OnDisconnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Steamworks_ISocketManager_OnDisconnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Steamworks_ISocketManager_OnMessage Steamworks_ISocketManager_OnMessage
		{
			add
			{
				HookEndpointManager.Add<hook_Steamworks_ISocketManager_OnMessage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Steamworks_ISocketManager_OnMessage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_InitSteamworks InitSteamworks
		{
			add
			{
				HookEndpointManager.Add<hook_InitSteamworks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_InitSteamworks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Netcode.Transports.Facepunch
{
	public static class FacepunchTransport
	{
		public static class Client
		{
			public static event Manipulator ctor
			{
				add
				{
					HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.Client.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.Client.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDestroy
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator DisconnectLocalClient
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_DisconnectLocalClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_DisconnectLocalClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator DisconnectRemoteClient
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_DisconnectRemoteClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_DisconnectRemoteClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetCurrentRtt
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_GetCurrentRtt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_GetCurrentRtt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Initialize
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Initialize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Initialize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator NetworkDeliveryToSendType
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_NetworkDeliveryToSendType>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_NetworkDeliveryToSendType>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Shutdown
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Send
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Send>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Send>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator PollEvent
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_PollEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_PollEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator StartClient
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_StartClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_StartClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator StartServer
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_StartServer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_StartServer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator EnsurePayloadCapacity
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_EnsurePayloadCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_EnsurePayloadCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Steamworks_IConnectionManager_OnConnecting
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_IConnectionManager_OnConnecting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_IConnectionManager_OnConnecting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Steamworks_IConnectionManager_OnConnected
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_IConnectionManager_OnConnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_IConnectionManager_OnConnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Steamworks_IConnectionManager_OnDisconnected
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_IConnectionManager_OnDisconnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_IConnectionManager_OnDisconnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Steamworks_IConnectionManager_OnMessage
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_IConnectionManager_OnMessage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_IConnectionManager_OnMessage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Steamworks_ISocketManager_OnConnecting
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_ISocketManager_OnConnecting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_ISocketManager_OnConnecting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Steamworks_ISocketManager_OnConnected
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_ISocketManager_OnConnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_ISocketManager_OnConnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Steamworks_ISocketManager_OnDisconnected
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_ISocketManager_OnDisconnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_ISocketManager_OnDisconnected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Steamworks_ISocketManager_OnMessage
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_ISocketManager_OnMessage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_Steamworks_ISocketManager_OnMessage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator InitSteamworks
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_InitSteamworks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_InitSteamworks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.FacepunchTransport.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Netcode.Transports.Facepunch
{
	public static class ReadOnlyAttribute
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ReadOnlyAttribute self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ReadOnlyAttribute self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Netcode.Transports.Facepunch
{
	public static class ReadOnlyAttribute
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Netcode.Transports.Facepunch.ReadOnlyAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Netcode.Transports.Facepunch.ReadOnlyAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.__GEN
{
	public static class NetworkVariableSerializationHelper
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_InitializeSerialization();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_InitializeSerialization(orig_InitializeSerialization orig);

		public static event hook_InitializeSerialization InitializeSerialization
		{
			add
			{
				HookEndpointManager.Add<hook_InitializeSerialization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_InitializeSerialization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.__GEN
{
	public static class NetworkVariableSerializationHelper
	{
		public static event Manipulator InitializeSerialization
		{
			add
			{
				HookEndpointManager.Modify<On.__GEN.NetworkVariableSerializationHelper.hook_InitializeSerialization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.__GEN.NetworkVariableSerializationHelper.hook_InitializeSerialization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace BepHookGen
{
	public class size14336
	{
	}
}

BooBoo Building/BepInEx/plugins/MMHOOK/MMHOOK_Facepunch.Steamworks.Win64.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On.Microsoft.CodeAnalysis;
using On.Steamworks;
using On.Steamworks.Data;
using On.Steamworks.ServerList;
using On.Steamworks.Ugc;
using On.System.Runtime.CompilerServices;
using Steamworks;
using Steamworks.Data;
using Steamworks.ServerList;
using Steamworks.Ugc;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On.Microsoft.CodeAnalysis
{
	public static class EmbeddedAttribute
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(Attribute self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, Attribute self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Microsoft.CodeAnalysis
{
	public static class EmbeddedAttribute
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Microsoft.CodeAnalysis.EmbeddedAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Microsoft.CodeAnalysis.EmbeddedAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.System.Runtime.CompilerServices
{
	public static class IsReadOnlyAttribute
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(Attribute self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, Attribute self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.System.Runtime.CompilerServices
{
	public static class IsReadOnlyAttribute
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.System.Runtime.CompilerServices.IsReadOnlyAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.System.Runtime.CompilerServices.IsReadOnlyAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Steamworks
{
	public static class AuthTicket
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Cancel(AuthTicket self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Cancel(orig_Cancel orig, AuthTicket self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Dispose(AuthTicket self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Dispose(orig_Dispose orig, AuthTicket self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AuthTicket self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AuthTicket self);

		public static event hook_Cancel Cancel
		{
			add
			{
				HookEndpointManager.Add<hook_Cancel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Cancel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Dispose Dispose
		{
			add
			{
				HookEndpointManager.Add<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Steamworks
{
	public static class AuthTicket
	{
		public static event Manipulator Cancel
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.AuthTicket.hook_Cancel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.AuthTicket.hook_Cancel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Dispose
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.AuthTicket.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.AuthTicket.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.AuthTicket.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.AuthTicket.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Steamworks
{
	public static class Dispatch
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SteamAPI_ManualDispatch_Init();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SteamAPI_ManualDispatch_Init(orig_SteamAPI_ManualDispatch_Init orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SteamAPI_ManualDispatch_RunFrame(ValueType pipe);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SteamAPI_ManualDispatch_RunFrame(orig_SteamAPI_ManualDispatch_RunFrame orig, ValueType pipe);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_SteamAPI_ManualDispatch_GetNextCallback(ValueType pipe, [In][Out] ValueType msg);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_SteamAPI_ManualDispatch_GetNextCallback(orig_SteamAPI_ManualDispatch_GetNextCallback orig, ValueType pipe, [In][Out] ValueType msg);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_SteamAPI_ManualDispatch_FreeLastCallback(ValueType pipe);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_SteamAPI_ManualDispatch_FreeLastCallback(orig_SteamAPI_ManualDispatch_FreeLastCallback orig, ValueType pipe);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Init();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Init(orig_Init orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Frame(ValueType pipe);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Frame(orig_Frame orig, ValueType pipe);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ProcessCallback(ValueType msg, bool isServer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ProcessCallback(orig_ProcessCallback orig, ValueType msg, bool isServer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_CallbackToString(CallbackType type, IntPtr data, int expectedsize);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_CallbackToString(orig_CallbackToString orig, CallbackType type, IntPtr data, int expectedsize);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ProcessResult(ValueType msg);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ProcessResult(orig_ProcessResult orig, ValueType msg);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LoopClientAsync();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LoopClientAsync(orig_LoopClientAsync orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LoopServerAsync();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LoopServerAsync(orig_LoopServerAsync orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ShutdownServer();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ShutdownServer(orig_ShutdownServer orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ShutdownClient();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ShutdownClient(orig_ShutdownClient orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_SteamAPI_ManualDispatch_Init SteamAPI_ManualDispatch_Init
		{
			add
			{
				HookEndpointManager.Add<hook_SteamAPI_ManualDispatch_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SteamAPI_ManualDispatch_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SteamAPI_ManualDispatch_RunFrame SteamAPI_ManualDispatch_RunFrame
		{
			add
			{
				HookEndpointManager.Add<hook_SteamAPI_ManualDispatch_RunFrame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SteamAPI_ManualDispatch_RunFrame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SteamAPI_ManualDispatch_GetNextCallback SteamAPI_ManualDispatch_GetNextCallback
		{
			add
			{
				HookEndpointManager.Add<hook_SteamAPI_ManualDispatch_GetNextCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SteamAPI_ManualDispatch_GetNextCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SteamAPI_ManualDispatch_FreeLastCallback SteamAPI_ManualDispatch_FreeLastCallback
		{
			add
			{
				HookEndpointManager.Add<hook_SteamAPI_ManualDispatch_FreeLastCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SteamAPI_ManualDispatch_FreeLastCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Init Init
		{
			add
			{
				HookEndpointManager.Add<hook_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Frame Frame
		{
			add
			{
				HookEndpointManager.Add<hook_Frame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Frame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ProcessCallback ProcessCallback
		{
			add
			{
				HookEndpointManager.Add<hook_ProcessCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ProcessCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CallbackToString CallbackToString
		{
			add
			{
				HookEndpointManager.Add<hook_CallbackToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CallbackToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ProcessResult ProcessResult
		{
			add
			{
				HookEndpointManager.Add<hook_ProcessResult>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ProcessResult>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LoopClientAsync LoopClientAsync
		{
			add
			{
				HookEndpointManager.Add<hook_LoopClientAsync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LoopClientAsync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LoopServerAsync LoopServerAsync
		{
			add
			{
				HookEndpointManager.Add<hook_LoopServerAsync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LoopServerAsync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ShutdownServer ShutdownServer
		{
			add
			{
				HookEndpointManager.Add<hook_ShutdownServer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ShutdownServer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ShutdownClient ShutdownClient
		{
			add
			{
				HookEndpointManager.Add<hook_ShutdownClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ShutdownClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Steamworks
{
	public static class Dispatch
	{
		public static event Manipulator SteamAPI_ManualDispatch_Init
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_SteamAPI_ManualDispatch_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_SteamAPI_ManualDispatch_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SteamAPI_ManualDispatch_RunFrame
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_SteamAPI_ManualDispatch_RunFrame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_SteamAPI_ManualDispatch_RunFrame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SteamAPI_ManualDispatch_GetNextCallback
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_SteamAPI_ManualDispatch_GetNextCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_SteamAPI_ManualDispatch_GetNextCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SteamAPI_ManualDispatch_FreeLastCallback
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_SteamAPI_ManualDispatch_FreeLastCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_SteamAPI_ManualDispatch_FreeLastCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Init
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Frame
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_Frame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_Frame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ProcessCallback
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_ProcessCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_ProcessCallback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CallbackToString
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_CallbackToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_CallbackToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ProcessResult
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_ProcessResult>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_ProcessResult>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LoopClientAsync
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_LoopClientAsync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_LoopClientAsync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LoopServerAsync
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_LoopServerAsync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_LoopServerAsync>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ShutdownServer
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_ShutdownServer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_ShutdownServer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ShutdownClient
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_ShutdownClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_ShutdownClient>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.Dispatch.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.Dispatch.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Steamworks
{
	public static class SteamAPI
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_Init();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_Init(orig_Init orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Shutdown();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Shutdown(orig_Shutdown orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType orig_GetHSteamPipe();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType hook_GetHSteamPipe(orig_GetHSteamPipe orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_RestartAppIfNecessary(uint unOwnAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_RestartAppIfNecessary(orig_RestartAppIfNecessary orig, uint unOwnAppID);

		public static class Native
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool orig_SteamAPI_Init();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool hook_SteamAPI_Init(orig_SteamAPI_Init orig);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_SteamAPI_Shutdown();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_SteamAPI_Shutdown(orig_SteamAPI_Shutdown orig);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate ValueType orig_SteamAPI_GetHSteamPipe();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate ValueType hook_SteamAPI_GetHSteamPipe(orig_SteamAPI_GetHSteamPipe orig);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool orig_SteamAPI_RestartAppIfNecessary(uint unOwnAppID);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool hook_SteamAPI_RestartAppIfNecessary(orig_SteamAPI_RestartAppIfNecessary orig, uint unOwnAppID);

			public static event hook_SteamAPI_Init SteamAPI_Init
			{
				add
				{
					HookEndpointManager.Add<hook_SteamAPI_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_SteamAPI_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_SteamAPI_Shutdown SteamAPI_Shutdown
			{
				add
				{
					HookEndpointManager.Add<hook_SteamAPI_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_SteamAPI_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_SteamAPI_GetHSteamPipe SteamAPI_GetHSteamPipe
			{
				add
				{
					HookEndpointManager.Add<hook_SteamAPI_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_SteamAPI_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_SteamAPI_RestartAppIfNecessary SteamAPI_RestartAppIfNecessary
			{
				add
				{
					HookEndpointManager.Add<hook_SteamAPI_RestartAppIfNecessary>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_SteamAPI_RestartAppIfNecessary>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_Init Init
		{
			add
			{
				HookEndpointManager.Add<hook_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Shutdown Shutdown
		{
			add
			{
				HookEndpointManager.Add<hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetHSteamPipe GetHSteamPipe
		{
			add
			{
				HookEndpointManager.Add<hook_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_RestartAppIfNecessary RestartAppIfNecessary
		{
			add
			{
				HookEndpointManager.Add<hook_RestartAppIfNecessary>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RestartAppIfNecessary>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Steamworks
{
	public static class SteamAPI
	{
		public static class Native
		{
			public static event Manipulator SteamAPI_Init
			{
				add
				{
					HookEndpointManager.Modify<On.Steamworks.SteamAPI.Native.hook_SteamAPI_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.Steamworks.SteamAPI.Native.hook_SteamAPI_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator SteamAPI_Shutdown
			{
				add
				{
					HookEndpointManager.Modify<On.Steamworks.SteamAPI.Native.hook_SteamAPI_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.Steamworks.SteamAPI.Native.hook_SteamAPI_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator SteamAPI_GetHSteamPipe
			{
				add
				{
					HookEndpointManager.Modify<On.Steamworks.SteamAPI.Native.hook_SteamAPI_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.Steamworks.SteamAPI.Native.hook_SteamAPI_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator SteamAPI_RestartAppIfNecessary
			{
				add
				{
					HookEndpointManager.Modify<On.Steamworks.SteamAPI.Native.hook_SteamAPI_RestartAppIfNecessary>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.Steamworks.SteamAPI.Native.hook_SteamAPI_RestartAppIfNecessary>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator Init
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.SteamAPI.hook_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.SteamAPI.hook_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Shutdown
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.SteamAPI.hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.SteamAPI.hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetHSteamPipe
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.SteamAPI.hook_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.SteamAPI.hook_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator RestartAppIfNecessary
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.SteamAPI.hook_RestartAppIfNecessary>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.SteamAPI.hook_RestartAppIfNecessary>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Steamworks
{
	public static class SteamGameServer
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RunCallbacks();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RunCallbacks(orig_RunCallbacks orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Shutdown();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Shutdown(orig_Shutdown orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType orig_GetHSteamPipe();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType hook_GetHSteamPipe(orig_GetHSteamPipe orig);

		public static class Native
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_SteamGameServer_RunCallbacks();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_SteamGameServer_RunCallbacks(orig_SteamGameServer_RunCallbacks orig);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_SteamGameServer_Shutdown();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_SteamGameServer_Shutdown(orig_SteamGameServer_Shutdown orig);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate ValueType orig_SteamGameServer_GetHSteamPipe();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate ValueType hook_SteamGameServer_GetHSteamPipe(orig_SteamGameServer_GetHSteamPipe orig);

			public static event hook_SteamGameServer_RunCallbacks SteamGameServer_RunCallbacks
			{
				add
				{
					HookEndpointManager.Add<hook_SteamGameServer_RunCallbacks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_SteamGameServer_RunCallbacks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_SteamGameServer_Shutdown SteamGameServer_Shutdown
			{
				add
				{
					HookEndpointManager.Add<hook_SteamGameServer_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_SteamGameServer_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_SteamGameServer_GetHSteamPipe SteamGameServer_GetHSteamPipe
			{
				add
				{
					HookEndpointManager.Add<hook_SteamGameServer_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_SteamGameServer_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_RunCallbacks RunCallbacks
		{
			add
			{
				HookEndpointManager.Add<hook_RunCallbacks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RunCallbacks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Shutdown Shutdown
		{
			add
			{
				HookEndpointManager.Add<hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetHSteamPipe GetHSteamPipe
		{
			add
			{
				HookEndpointManager.Add<hook_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Steamworks
{
	public static class SteamGameServer
	{
		public static class Native
		{
			public static event Manipulator SteamGameServer_RunCallbacks
			{
				add
				{
					HookEndpointManager.Modify<On.Steamworks.SteamGameServer.Native.hook_SteamGameServer_RunCallbacks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.Steamworks.SteamGameServer.Native.hook_SteamGameServer_RunCallbacks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator SteamGameServer_Shutdown
			{
				add
				{
					HookEndpointManager.Modify<On.Steamworks.SteamGameServer.Native.hook_SteamGameServer_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.Steamworks.SteamGameServer.Native.hook_SteamGameServer_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator SteamGameServer_GetHSteamPipe
			{
				add
				{
					HookEndpointManager.Modify<On.Steamworks.SteamGameServer.Native.hook_SteamGameServer_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.Steamworks.SteamGameServer.Native.hook_SteamGameServer_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator RunCallbacks
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.SteamGameServer.hook_RunCallbacks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.SteamGameServer.hook_RunCallbacks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Shutdown
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.SteamGameServer.hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.SteamGameServer.hook_Shutdown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetHSteamPipe
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.SteamGameServer.hook_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.SteamGameServer.hook_GetHSteamPipe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Steamworks
{
	public static class SteamInternal
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_GameServer_Init(uint unIP, ushort usPort, ushort usGamePort, ushort usQueryPort, int eServerMode, string pchVersionString);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_GameServer_Init(orig_GameServer_Init orig, uint unIP, ushort usPort, ushort usGamePort, ushort usQueryPort, int eServerMode, string pchVersionString);

		public static class Native
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool orig_SteamInternal_GameServer_Init(uint unIP, ushort usPort, ushort usGamePort, ushort usQueryPort, int eServerMode, string pchVersionString);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate bool hook_SteamInternal_GameServer_Init(orig_SteamInternal_GameServer_Init orig, uint unIP, ushort usPort, ushort usGamePort, ushort usQueryPort, int eServerMode, string pchVersionString);

			public static event hook_SteamInternal_GameServer_Init SteamInternal_GameServer_Init
			{
				add
				{
					HookEndpointManager.Add<hook_SteamInternal_GameServer_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_SteamInternal_GameServer_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_GameServer_Init GameServer_Init
		{
			add
			{
				HookEndpointManager.Add<hook_GameServer_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GameServer_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Steamworks
{
	public static class SteamInternal
	{
		public static class Native
		{
			public static event Manipulator SteamInternal_GameServer_Init
			{
				add
				{
					HookEndpointManager.Modify<On.Steamworks.SteamInternal.Native.hook_SteamInternal_GameServer_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.Steamworks.SteamInternal.Native.hook_SteamInternal_GameServer_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator GameServer_Init
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.SteamInternal.hook_GameServer_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.SteamInternal.hook_GameServer_Init>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Steamworks
{
	public static class CallbackTypeFactory
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Steamworks
{
	public static class CallbackTypeFactory
	{
		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.CallbackTypeFactory.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.CallbackTypeFactory.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Steamworks
{
	public static class ISteamAppList
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(object self, bool IsGameServer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, object self, bool IsGameServer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr orig_SteamAPI_SteamAppList_v001();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr hook_SteamAPI_SteamAppList_v001(orig_SteamAPI_SteamAppList_v001 orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr orig_GetUserInterfacePointer(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr hook_GetUserInterfacePointer(orig_GetUserInterfacePointer orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint orig__GetNumInstalledApps(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint hook__GetNumInstalledApps(orig__GetNumInstalledApps orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint orig_GetNumInstalledApps(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint hook_GetNumInstalledApps(orig_GetNumInstalledApps orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint orig__GetInstalledApps(IntPtr self, [In][Out] AppId[] pvecAppID, uint unMaxAppIDs);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint hook__GetInstalledApps(orig__GetInstalledApps orig, IntPtr self, [In][Out] AppId[] pvecAppID, uint unMaxAppIDs);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint orig_GetInstalledApps(object self, [In][Out] AppId[] pvecAppID, uint unMaxAppIDs);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint hook_GetInstalledApps(orig_GetInstalledApps orig, object self, [In][Out] AppId[] pvecAppID, uint unMaxAppIDs);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig__GetAppName(IntPtr self, AppId nAppID, IntPtr pchName, int cchNameMax);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook__GetAppName(orig__GetAppName orig, IntPtr self, AppId nAppID, IntPtr pchName, int cchNameMax);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetAppName(object self, AppId nAppID, out string pchName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetAppName(orig_GetAppName orig, object self, AppId nAppID, out string pchName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig__GetAppInstallDir(IntPtr self, AppId nAppID, IntPtr pchDirectory, int cchNameMax);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook__GetAppInstallDir(orig__GetAppInstallDir orig, IntPtr self, AppId nAppID, IntPtr pchDirectory, int cchNameMax);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetAppInstallDir(object self, AppId nAppID, out string pchDirectory);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetAppInstallDir(orig_GetAppInstallDir orig, object self, AppId nAppID, out string pchDirectory);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig__GetAppBuildId(IntPtr self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook__GetAppBuildId(orig__GetAppBuildId orig, IntPtr self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetAppBuildId(object self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetAppBuildId(orig_GetAppBuildId orig, object self, AppId nAppID);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SteamAPI_SteamAppList_v001 SteamAPI_SteamAppList_v001
		{
			add
			{
				HookEndpointManager.Add<hook_SteamAPI_SteamAppList_v001>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SteamAPI_SteamAppList_v001>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetUserInterfacePointer GetUserInterfacePointer
		{
			add
			{
				HookEndpointManager.Add<hook_GetUserInterfacePointer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetUserInterfacePointer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetNumInstalledApps _GetNumInstalledApps
		{
			add
			{
				HookEndpointManager.Add<hook__GetNumInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetNumInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetNumInstalledApps GetNumInstalledApps
		{
			add
			{
				HookEndpointManager.Add<hook_GetNumInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetNumInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetInstalledApps _GetInstalledApps
		{
			add
			{
				HookEndpointManager.Add<hook__GetInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetInstalledApps GetInstalledApps
		{
			add
			{
				HookEndpointManager.Add<hook_GetInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetAppName _GetAppName
		{
			add
			{
				HookEndpointManager.Add<hook__GetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetAppName GetAppName
		{
			add
			{
				HookEndpointManager.Add<hook_GetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetAppInstallDir _GetAppInstallDir
		{
			add
			{
				HookEndpointManager.Add<hook__GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetAppInstallDir GetAppInstallDir
		{
			add
			{
				HookEndpointManager.Add<hook_GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetAppBuildId _GetAppBuildId
		{
			add
			{
				HookEndpointManager.Add<hook__GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetAppBuildId GetAppBuildId
		{
			add
			{
				HookEndpointManager.Add<hook_GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.Steamworks
{
	public static class ISteamAppList
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SteamAPI_SteamAppList_v001
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook_SteamAPI_SteamAppList_v001>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook_SteamAPI_SteamAppList_v001>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetUserInterfacePointer
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook_GetUserInterfacePointer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook_GetUserInterfacePointer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator _GetNumInstalledApps
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook__GetNumInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook__GetNumInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetNumInstalledApps
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook_GetNumInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook_GetNumInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator _GetInstalledApps
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook__GetInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook__GetInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetInstalledApps
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook_GetInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook_GetInstalledApps>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator _GetAppName
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook__GetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook__GetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetAppName
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook_GetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook_GetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator _GetAppInstallDir
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook__GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook__GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetAppInstallDir
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook_GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook_GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator _GetAppBuildId
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook__GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook__GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetAppBuildId
		{
			add
			{
				HookEndpointManager.Modify<On.Steamworks.ISteamAppList.hook_GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Steamworks.ISteamAppList.hook_GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.Steamworks
{
	public static class ISteamApps
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(object self, bool IsGameServer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, object self, bool IsGameServer);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr orig_SteamAPI_SteamApps_v008();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr hook_SteamAPI_SteamApps_v008(orig_SteamAPI_SteamApps_v008 orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr orig_GetUserInterfacePointer(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr hook_GetUserInterfacePointer(orig_GetUserInterfacePointer orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr orig_SteamAPI_SteamGameServerApps_v008();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr hook_SteamAPI_SteamGameServerApps_v008(orig_SteamAPI_SteamGameServerApps_v008 orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr orig_GetServerInterfacePointer(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IntPtr hook_GetServerInterfacePointer(orig_GetServerInterfacePointer orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__BIsSubscribed(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__BIsSubscribed(orig__BIsSubscribed orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_BIsSubscribed(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_BIsSubscribed(orig_BIsSubscribed orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__BIsLowViolence(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__BIsLowViolence(orig__BIsLowViolence orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_BIsLowViolence(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_BIsLowViolence(orig_BIsLowViolence orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__BIsCybercafe(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__BIsCybercafe(orig__BIsCybercafe orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_BIsCybercafe(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_BIsCybercafe(orig_BIsCybercafe orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__BIsVACBanned(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__BIsVACBanned(orig__BIsVACBanned orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_BIsVACBanned(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_BIsVACBanned(orig_BIsVACBanned orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType orig__GetCurrentGameLanguage(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType hook__GetCurrentGameLanguage(orig__GetCurrentGameLanguage orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetCurrentGameLanguage(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetCurrentGameLanguage(orig_GetCurrentGameLanguage orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType orig__GetAvailableGameLanguages(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType hook__GetAvailableGameLanguages(orig__GetAvailableGameLanguages orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetAvailableGameLanguages(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetAvailableGameLanguages(orig_GetAvailableGameLanguages orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__BIsSubscribedApp(IntPtr self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__BIsSubscribedApp(orig__BIsSubscribedApp orig, IntPtr self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_BIsSubscribedApp(object self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_BIsSubscribedApp(orig_BIsSubscribedApp orig, object self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__BIsDlcInstalled(IntPtr self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__BIsDlcInstalled(orig__BIsDlcInstalled orig, IntPtr self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_BIsDlcInstalled(object self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_BIsDlcInstalled(orig_BIsDlcInstalled orig, object self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint orig__GetEarliestPurchaseUnixTime(IntPtr self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint hook__GetEarliestPurchaseUnixTime(orig__GetEarliestPurchaseUnixTime orig, IntPtr self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint orig_GetEarliestPurchaseUnixTime(object self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint hook_GetEarliestPurchaseUnixTime(orig_GetEarliestPurchaseUnixTime orig, object self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__BIsSubscribedFromFreeWeekend(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__BIsSubscribedFromFreeWeekend(orig__BIsSubscribedFromFreeWeekend orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_BIsSubscribedFromFreeWeekend(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_BIsSubscribedFromFreeWeekend(orig_BIsSubscribedFromFreeWeekend orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig__GetDLCCount(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook__GetDLCCount(orig__GetDLCCount orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetDLCCount(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetDLCCount(orig_GetDLCCount orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__BGetDLCDataByIndex(IntPtr self, int iDLC, ref AppId pAppID, ref bool pbAvailable, IntPtr pchName, int cchNameBufferSize);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__BGetDLCDataByIndex(orig__BGetDLCDataByIndex orig, IntPtr self, int iDLC, ref AppId pAppID, ref bool pbAvailable, IntPtr pchName, int cchNameBufferSize);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_BGetDLCDataByIndex(object self, int iDLC, ref AppId pAppID, ref bool pbAvailable, out string pchName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_BGetDLCDataByIndex(orig_BGetDLCDataByIndex orig, object self, int iDLC, ref AppId pAppID, ref bool pbAvailable, out string pchName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig__InstallDLC(IntPtr self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook__InstallDLC(orig__InstallDLC orig, IntPtr self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_InstallDLC(object self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_InstallDLC(orig_InstallDLC orig, object self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig__UninstallDLC(IntPtr self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook__UninstallDLC(orig__UninstallDLC orig, IntPtr self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UninstallDLC(object self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UninstallDLC(orig_UninstallDLC orig, object self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig__RequestAppProofOfPurchaseKey(IntPtr self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook__RequestAppProofOfPurchaseKey(orig__RequestAppProofOfPurchaseKey orig, IntPtr self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RequestAppProofOfPurchaseKey(object self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RequestAppProofOfPurchaseKey(orig_RequestAppProofOfPurchaseKey orig, object self, AppId nAppID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__GetCurrentBetaName(IntPtr self, IntPtr pchName, int cchNameBufferSize);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__GetCurrentBetaName(orig__GetCurrentBetaName orig, IntPtr self, IntPtr pchName, int cchNameBufferSize);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_GetCurrentBetaName(object self, out string pchName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_GetCurrentBetaName(orig_GetCurrentBetaName orig, object self, out string pchName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__MarkContentCorrupt(IntPtr self, bool bMissingFilesOnly);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__MarkContentCorrupt(orig__MarkContentCorrupt orig, IntPtr self, bool bMissingFilesOnly);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_MarkContentCorrupt(object self, bool bMissingFilesOnly);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_MarkContentCorrupt(orig_MarkContentCorrupt orig, object self, bool bMissingFilesOnly);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint orig__GetInstalledDepots(IntPtr self, AppId appID, [In][Out] ValueType pvecDepots, uint cMaxDepots);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint hook__GetInstalledDepots(orig__GetInstalledDepots orig, IntPtr self, AppId appID, [In][Out] ValueType pvecDepots, uint cMaxDepots);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint orig_GetInstalledDepots(object self, AppId appID, [In][Out] ValueType pvecDepots, uint cMaxDepots);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint hook_GetInstalledDepots(orig_GetInstalledDepots orig, object self, AppId appID, [In][Out] ValueType pvecDepots, uint cMaxDepots);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint orig__GetAppInstallDir(IntPtr self, AppId appID, IntPtr pchFolder, uint cchFolderBufferSize);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint hook__GetAppInstallDir(orig__GetAppInstallDir orig, IntPtr self, AppId appID, IntPtr pchFolder, uint cchFolderBufferSize);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint orig_GetAppInstallDir(object self, AppId appID, out string pchFolder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate uint hook_GetAppInstallDir(orig_GetAppInstallDir orig, object self, AppId appID, out string pchFolder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__BIsAppInstalled(IntPtr self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__BIsAppInstalled(orig__BIsAppInstalled orig, IntPtr self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_BIsAppInstalled(object self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_BIsAppInstalled(orig_BIsAppInstalled orig, object self, AppId appID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate SteamId orig__GetAppOwner(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate SteamId hook__GetAppOwner(orig__GetAppOwner orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate SteamId orig_GetAppOwner(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate SteamId hook_GetAppOwner(orig_GetAppOwner orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType orig__GetLaunchQueryParam(IntPtr self, string pchKey);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType hook__GetLaunchQueryParam(orig__GetLaunchQueryParam orig, IntPtr self, string pchKey);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetLaunchQueryParam(object self, string pchKey);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetLaunchQueryParam(orig_GetLaunchQueryParam orig, object self, string pchKey);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__GetDlcDownloadProgress(IntPtr self, AppId nAppID, ref ulong punBytesDownloaded, ref ulong punBytesTotal);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__GetDlcDownloadProgress(orig__GetDlcDownloadProgress orig, IntPtr self, AppId nAppID, ref ulong punBytesDownloaded, ref ulong punBytesTotal);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_GetDlcDownloadProgress(object self, AppId nAppID, ref ulong punBytesDownloaded, ref ulong punBytesTotal);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_GetDlcDownloadProgress(orig_GetDlcDownloadProgress orig, object self, AppId nAppID, ref ulong punBytesDownloaded, ref ulong punBytesTotal);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig__GetAppBuildId(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook__GetAppBuildId(orig__GetAppBuildId orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetAppBuildId(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetAppBuildId(orig_GetAppBuildId orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig__RequestAllProofOfPurchaseKeys(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook__RequestAllProofOfPurchaseKeys(orig__RequestAllProofOfPurchaseKeys orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RequestAllProofOfPurchaseKeys(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RequestAllProofOfPurchaseKeys(orig_RequestAllProofOfPurchaseKeys orig, object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType orig__GetFileDetails(IntPtr self, string pszFileName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType hook__GetFileDetails(orig__GetFileDetails orig, IntPtr self, string pszFileName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType orig_GetFileDetails(object self, string pszFileName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ValueType hook_GetFileDetails(orig_GetFileDetails orig, object self, string pszFileName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig__GetLaunchCommandLine(IntPtr self, IntPtr pszCommandLine, int cubCommandLine);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook__GetLaunchCommandLine(orig__GetLaunchCommandLine orig, IntPtr self, IntPtr pszCommandLine, int cubCommandLine);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetLaunchCommandLine(object self, out string pszCommandLine);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetLaunchCommandLine(orig_GetLaunchCommandLine orig, object self, out string pszCommandLine);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig__BIsSubscribedFromFamilySharing(IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook__BIsSubscribedFromFamilySharing(orig__BIsSubscribedFromFamilySharing orig, IntPtr self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_BIsSubscribedFromFamilySharing(object self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_BIsSubscribedFromFamilySharing(orig_BIsSubscribedFromFamilySharing orig, object self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SteamAPI_SteamApps_v008 SteamAPI_SteamApps_v008
		{
			add
			{
				HookEndpointManager.Add<hook_SteamAPI_SteamApps_v008>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SteamAPI_SteamApps_v008>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetUserInterfacePointer GetUserInterfacePointer
		{
			add
			{
				HookEndpointManager.Add<hook_GetUserInterfacePointer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetUserInterfacePointer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SteamAPI_SteamGameServerApps_v008 SteamAPI_SteamGameServerApps_v008
		{
			add
			{
				HookEndpointManager.Add<hook_SteamAPI_SteamGameServerApps_v008>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SteamAPI_SteamGameServerApps_v008>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetServerInterfacePointer GetServerInterfacePointer
		{
			add
			{
				HookEndpointManager.Add<hook_GetServerInterfacePointer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetServerInterfacePointer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__BIsSubscribed _BIsSubscribed
		{
			add
			{
				HookEndpointManager.Add<hook__BIsSubscribed>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__BIsSubscribed>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BIsSubscribed BIsSubscribed
		{
			add
			{
				HookEndpointManager.Add<hook_BIsSubscribed>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BIsSubscribed>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__BIsLowViolence _BIsLowViolence
		{
			add
			{
				HookEndpointManager.Add<hook__BIsLowViolence>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__BIsLowViolence>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BIsLowViolence BIsLowViolence
		{
			add
			{
				HookEndpointManager.Add<hook_BIsLowViolence>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BIsLowViolence>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__BIsCybercafe _BIsCybercafe
		{
			add
			{
				HookEndpointManager.Add<hook__BIsCybercafe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__BIsCybercafe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BIsCybercafe BIsCybercafe
		{
			add
			{
				HookEndpointManager.Add<hook_BIsCybercafe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BIsCybercafe>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__BIsVACBanned _BIsVACBanned
		{
			add
			{
				HookEndpointManager.Add<hook__BIsVACBanned>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__BIsVACBanned>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BIsVACBanned BIsVACBanned
		{
			add
			{
				HookEndpointManager.Add<hook_BIsVACBanned>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BIsVACBanned>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetCurrentGameLanguage _GetCurrentGameLanguage
		{
			add
			{
				HookEndpointManager.Add<hook__GetCurrentGameLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetCurrentGameLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetCurrentGameLanguage GetCurrentGameLanguage
		{
			add
			{
				HookEndpointManager.Add<hook_GetCurrentGameLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCurrentGameLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetAvailableGameLanguages _GetAvailableGameLanguages
		{
			add
			{
				HookEndpointManager.Add<hook__GetAvailableGameLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetAvailableGameLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetAvailableGameLanguages GetAvailableGameLanguages
		{
			add
			{
				HookEndpointManager.Add<hook_GetAvailableGameLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetAvailableGameLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__BIsSubscribedApp _BIsSubscribedApp
		{
			add
			{
				HookEndpointManager.Add<hook__BIsSubscribedApp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__BIsSubscribedApp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BIsSubscribedApp BIsSubscribedApp
		{
			add
			{
				HookEndpointManager.Add<hook_BIsSubscribedApp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BIsSubscribedApp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__BIsDlcInstalled _BIsDlcInstalled
		{
			add
			{
				HookEndpointManager.Add<hook__BIsDlcInstalled>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__BIsDlcInstalled>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BIsDlcInstalled BIsDlcInstalled
		{
			add
			{
				HookEndpointManager.Add<hook_BIsDlcInstalled>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BIsDlcInstalled>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetEarliestPurchaseUnixTime _GetEarliestPurchaseUnixTime
		{
			add
			{
				HookEndpointManager.Add<hook__GetEarliestPurchaseUnixTime>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetEarliestPurchaseUnixTime>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetEarliestPurchaseUnixTime GetEarliestPurchaseUnixTime
		{
			add
			{
				HookEndpointManager.Add<hook_GetEarliestPurchaseUnixTime>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetEarliestPurchaseUnixTime>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__BIsSubscribedFromFreeWeekend _BIsSubscribedFromFreeWeekend
		{
			add
			{
				HookEndpointManager.Add<hook__BIsSubscribedFromFreeWeekend>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__BIsSubscribedFromFreeWeekend>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BIsSubscribedFromFreeWeekend BIsSubscribedFromFreeWeekend
		{
			add
			{
				HookEndpointManager.Add<hook_BIsSubscribedFromFreeWeekend>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BIsSubscribedFromFreeWeekend>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetDLCCount _GetDLCCount
		{
			add
			{
				HookEndpointManager.Add<hook__GetDLCCount>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetDLCCount>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetDLCCount GetDLCCount
		{
			add
			{
				HookEndpointManager.Add<hook_GetDLCCount>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetDLCCount>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__BGetDLCDataByIndex _BGetDLCDataByIndex
		{
			add
			{
				HookEndpointManager.Add<hook__BGetDLCDataByIndex>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__BGetDLCDataByIndex>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BGetDLCDataByIndex BGetDLCDataByIndex
		{
			add
			{
				HookEndpointManager.Add<hook_BGetDLCDataByIndex>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BGetDLCDataByIndex>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__InstallDLC _InstallDLC
		{
			add
			{
				HookEndpointManager.Add<hook__InstallDLC>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__InstallDLC>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_InstallDLC InstallDLC
		{
			add
			{
				HookEndpointManager.Add<hook_InstallDLC>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_InstallDLC>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__UninstallDLC _UninstallDLC
		{
			add
			{
				HookEndpointManager.Add<hook__UninstallDLC>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__UninstallDLC>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UninstallDLC UninstallDLC
		{
			add
			{
				HookEndpointManager.Add<hook_UninstallDLC>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UninstallDLC>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__RequestAppProofOfPurchaseKey _RequestAppProofOfPurchaseKey
		{
			add
			{
				HookEndpointManager.Add<hook__RequestAppProofOfPurchaseKey>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__RequestAppProofOfPurchaseKey>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_RequestAppProofOfPurchaseKey RequestAppProofOfPurchaseKey
		{
			add
			{
				HookEndpointManager.Add<hook_RequestAppProofOfPurchaseKey>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RequestAppProofOfPurchaseKey>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetCurrentBetaName _GetCurrentBetaName
		{
			add
			{
				HookEndpointManager.Add<hook__GetCurrentBetaName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetCurrentBetaName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetCurrentBetaName GetCurrentBetaName
		{
			add
			{
				HookEndpointManager.Add<hook_GetCurrentBetaName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCurrentBetaName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__MarkContentCorrupt _MarkContentCorrupt
		{
			add
			{
				HookEndpointManager.Add<hook__MarkContentCorrupt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__MarkContentCorrupt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_MarkContentCorrupt MarkContentCorrupt
		{
			add
			{
				HookEndpointManager.Add<hook_MarkContentCorrupt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_MarkContentCorrupt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetInstalledDepots _GetInstalledDepots
		{
			add
			{
				HookEndpointManager.Add<hook__GetInstalledDepots>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetInstalledDepots>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetInstalledDepots GetInstalledDepots
		{
			add
			{
				HookEndpointManager.Add<hook_GetInstalledDepots>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetInstalledDepots>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetAppInstallDir _GetAppInstallDir
		{
			add
			{
				HookEndpointManager.Add<hook__GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetAppInstallDir GetAppInstallDir
		{
			add
			{
				HookEndpointManager.Add<hook_GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetAppInstallDir>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__BIsAppInstalled _BIsAppInstalled
		{
			add
			{
				HookEndpointManager.Add<hook__BIsAppInstalled>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__BIsAppInstalled>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BIsAppInstalled BIsAppInstalled
		{
			add
			{
				HookEndpointManager.Add<hook_BIsAppInstalled>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BIsAppInstalled>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetAppOwner _GetAppOwner
		{
			add
			{
				HookEndpointManager.Add<hook__GetAppOwner>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetAppOwner>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetAppOwner GetAppOwner
		{
			add
			{
				HookEndpointManager.Add<hook_GetAppOwner>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetAppOwner>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetLaunchQueryParam _GetLaunchQueryParam
		{
			add
			{
				HookEndpointManager.Add<hook__GetLaunchQueryParam>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetLaunchQueryParam>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetLaunchQueryParam GetLaunchQueryParam
		{
			add
			{
				HookEndpointManager.Add<hook_GetLaunchQueryParam>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetLaunchQueryParam>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetDlcDownloadProgress _GetDlcDownloadProgress
		{
			add
			{
				HookEndpointManager.Add<hook__GetDlcDownloadProgress>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetDlcDownloadProgress>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetDlcDownloadProgress GetDlcDownloadProgress
		{
			add
			{
				HookEndpointManager.Add<hook_GetDlcDownloadProgress>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetDlcDownloadProgress>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__GetAppBuildId _GetAppBuildId
		{
			add
			{
				HookEndpointManager.Add<hook__GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetAppBuildId GetAppBuildId
		{
			add
			{
				HookEndpointManager.Add<hook_GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetAppBuildId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook__RequestAllProofOfPurchaseKeys _RequestAllProofOfPurchaseKeys
		{
			add
			{
				HookEndpointManager.Add<hook__RequestAllProofOfPurchaseKeys>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook__RequestAllProofOfPurchaseKeys>(MethodBase.GetMethodFromHandle((Runt

BooBoo Building/BepInEx/plugins/monkes_mods-JumpDelayPatch/JumpDelayPatch.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("JumpDelayPatch")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("JumpDelayPatch")]
[assembly: AssemblyTitle("JumpDelayPatch")]
[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 JumpDelayPatch
{
	[BepInPlugin("monke.lc.jumpdelay", "Jump Delay Patch", "0.0.0.1")]
	public class monkeDelayPatch : BaseUnityPlugin
	{
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		internal class PlayerControllerB_PlayerJump
		{
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Expected O, but got Unknown
				List<CodeInstruction> list = instructions.ToList();
				for (int i = 0; i < list.Count; i++)
				{
					if (list[i].opcode == OpCodes.Ldc_R4)
					{
						list[i] = new CodeInstruction(OpCodes.Ldc_R4, (object)0f);
					}
				}
				return list;
			}
		}

		private void Awake()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin JumpDelayPatch is loaded!");
			Harmony val = new Harmony("monke.lc.jumpdelay");
			val.PatchAll();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "JumpDelayPatch";

		public const string PLUGIN_NAME = "JumpDelayPatch";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

BooBoo Building/BepInEx/plugins/Monkeytype-HideChat/HideChat.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("HideChat")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HideChat")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("fa900f4d-71b1-433a-ad23-a10fc53dc3d8")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HideChat
{
	[BepInPlugin("Miodec.HideChat", "Hide Chat", "1.0.0")]
	public class HidePlayerNames : BaseUnityPlugin
	{
		private const string modGUID = "Miodec.HideChat";

		private const string modName = "Hide Chat";

		private const string modVersion = "1.0.0";

		private static HidePlayerNames Instance;

		internal ManualLogSource mls;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("Miodec.HideChat");
			mls.LogDebug((object)"hidechat is awake");
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		}
	}
}
namespace HideChat.Patches
{
	[HarmonyPatch(typeof(HUDManager))]
	internal class HUDManagerPatch
	{
		[HarmonyPatch("OpenMenu_performed")]
		[HarmonyPatch("SubmitChat_performed")]
		[HarmonyPatch("AddChatMessage")]
		[HarmonyPostfix]
		public static void FadeToNothing(ref HUDManager __instance)
		{
			__instance.PingHUDElement(__instance.Chat, 5f, 1f, 0f);
		}
	}
}

BooBoo Building/BepInEx/plugins/no00ob-LCSoundTool/LC_SoundTool.dll

Decompiled 9 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LCSoundTool.Networking;
using LCSoundTool.Patches;
using LCSoundTool.Resources;
using LCSoundTool.Utilities;
using LCSoundToolMod.Properties;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LC_SoundTool")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Various audio related functions. Mainly logs all sounds that are playing and what type of playback they're into the BepInEx console.")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.0")]
[assembly: AssemblyProduct("LC_SoundTool")]
[assembly: AssemblyTitle("LC_SoundTool")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/no00ob/LCSoundTool")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LCSoundToolMod
{
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LC_SoundTool";

		public const string PLUGIN_NAME = "LC_SoundTool";

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

		private static CultureInfo resourceCulture;

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

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

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

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

		public bool playOnAwake = false;

		public bool loop = false;

		private bool updateHasBeenLogged = false;

		private bool hasPlayed = false;

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

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

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

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

		public RandomAudioClip(AudioClip clip, float chance)
		{
			this.clip = clip;
			this.chance = chance;
		}
	}
	[BepInPlugin("LCSoundTool", "LC Sound Tool", "1.4.0")]
	public class SoundTool : BaseUnityPlugin
	{
		public enum AudioType
		{
			wav,
			ogg,
			mp3
		}

		private const string PLUGIN_GUID = "LCSoundTool";

		private const string PLUGIN_NAME = "LC Sound Tool";

		private ConfigEntry<bool> configUseNetworking;

		private ConfigEntry<bool> configSyncRandomSeed;

		private ConfigEntry<float> configPlayOnAwakePatchRepeatDelay;

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

		public static SoundTool Instance;

		internal ManualLogSource logger;

		public KeyboardShortcut toggleAudioSourceDebugLog;

		public KeyboardShortcut toggleIndepthDebugLog;

		public KeyboardShortcut toggleInformationalDebugLog;

		public bool wasKeyDown;

		public bool wasKeyDown2;

		public bool wasKeyDown3;

		public static bool debugAudioSources;

		public static bool indepthDebugging;

		public static bool infoDebugging;

		public static bool networkingInitialized { get; private set; }

		public static bool networkingAvailable { get; private set; }

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

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

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

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

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

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

		private void Awake()
		{
			//IL_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)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			networkingAvailable = true;
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			configUseNetworking = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "EnableNetworking", false, "Whether or not to use the networking built into this plugin. If set to true everyone in the lobby needs LCSoundTool installed and networking enabled to join.");
			configSyncRandomSeed = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "SyncUnityRandomSeed", false, "Whether or not to sync the default Unity randomization seed with all clients. For this feature, networking has to be set to true. Will send the UnityEngine.Random.seed from the host to all clients automatically upon loading a networked scene.");
			configPlayOnAwakePatchRepeatDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Experimental", "NewPlayOnAwakePatchRepeatDelay", 90f, "How long to wait between checks for new playOnAwake AudioSources. Runs the same patching that is done when each scene is loaded with this delay between each run. DO NOT set too low or high. Anything below 10 or above 600 can cause issues. This time is in seconds. Set to 0 to disable rerunning the patch, but be warned that this might break runtime initialized playOnAwake AudioSources.");
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			logger = Logger.CreateLogSource("LCSoundTool");
			logger.LogInfo((object)"Plugin LCSoundTool is loaded!");
			toggleAudioSourceDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[0]);
			toggleIndepthDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 });
			toggleInformationalDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 });
			debugAudioSources = false;
			indepthDebugging = false;
			infoDebugging = false;
			replacedClips = new Dictionary<string, List<RandomAudioClip>>();
			clipTypes = new Dictionary<string, AudioType>();
		}

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

		private void Update()
		{
			if (configUseNetworking.Value)
			{
				if (!networkingInitialized)
				{
					if ((Object)(object)NetworkHandler.Instance != (Object)null)
					{
						networkingInitialized = true;
					}
				}
				else if ((Object)(object)NetworkHandler.Instance == (Object)null)
				{
					networkingInitialized = false;
				}
			}
			else
			{
				networkingInitialized = false;
			}
			if (((KeyboardShortcut)(ref toggleInformationalDebugLog)).IsDown() && !wasKeyDown3)
			{
				wasKeyDown3 = true;
				wasKeyDown2 = false;
				wasKeyDown = false;
			}
			if (((KeyboardShortcut)(ref toggleInformationalDebugLog)).IsUp() && wasKeyDown3)
			{
				wasKeyDown3 = false;
				wasKeyDown2 = false;
				wasKeyDown = false;
				infoDebugging = !infoDebugging;
				Instance.logger.LogDebug((object)$"Toggling informational debug logs {infoDebugging}!");
				return;
			}
			if (((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsDown() && !wasKeyDown2)
			{
				wasKeyDown2 = true;
				wasKeyDown = false;
			}
			if (((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsUp() && wasKeyDown2)
			{
				wasKeyDown2 = false;
				wasKeyDown = false;
				debugAudioSources = !debugAudioSources;
				indepthDebugging = debugAudioSources;
				infoDebugging = debugAudioSources;
				Instance.logger.LogDebug((object)$"Toggling in-depth AudioSource debug logs {debugAudioSources}!");
				return;
			}
			if (!wasKeyDown2 && !((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsDown() && ((KeyboardShortcut)(ref toggleAudioSourceDebugLog)).IsDown() && !wasKeyDown)
			{
				wasKeyDown = true;
				wasKeyDown2 = false;
			}
			if (((KeyboardShortcut)(ref toggleAudioSourceDebugLog)).IsUp() && wasKeyDown)
			{
				wasKeyDown = false;
				wasKeyDown2 = false;
				debugAudioSources = !debugAudioSources;
				if (indepthDebugging && !debugAudioSources)
				{
					indepthDebugging = false;
				}
				Instance.logger.LogDebug((object)$"Toggling AudioSource debug logs {debugAudioSources}!");
			}
		}

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

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

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

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

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

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

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

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

		public static void ReplaceAudioClip(string originalName, AudioClip newClip, float chance)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed.");
				return;
			}
			if ((Object)(object)newClip == (Object)null)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			string name = newClip.GetName();
			if (replacedClips.ContainsKey(originalName) && chance >= 100f)
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with 100% chance of playback! This is not allowed.");
				return;
			}
			chance = Mathf.Clamp01(chance);
			if (replacedClips.ContainsKey(originalName))
			{
				replacedClips[originalName].Add(new RandomAudioClip(newClip, chance));
			}
			else
			{
				replacedClips[originalName] = new List<RandomAudioClip>
				{
					new RandomAudioClip(newClip, chance)
				};
			}
			float num = 0f;
			for (int i = 0; i < replacedClips[originalName].Count(); i++)
			{
				num += replacedClips[originalName][i].chance;
			}
			if ((num < 1f || num > 1f) && replacedClips[originalName].Count() > 1)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} does not equal 100% (at least yet?)");
			}
			else if (num == 1f && replacedClips[originalName].Count() > 1)
			{
				Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} is equal to 100%");
			}
		}

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

		public static void RemoveRandomAudioClip(string name, float chance)
		{
			if (string.IsNullOrEmpty(name))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed.");
			}
			else if (!replacedClips.ContainsKey(name))
			{
				Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed.");
			}
			else
			{
				if (!(chance > 0f))
				{
					return;
				}
				for (int i = 0; i < replacedClips[name].Count(); i++)
				{
					if (replacedClips[name][i].chance == chance)
					{
						replacedClips[name].RemoveAt(i);
						break;
					}
				}
			}
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		private static void DebugPlayClipAtPointMethod(AudioSource audioSource, Vector3 position)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)audioSource == (Object)null)
			{
				return;
			}
			if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{audioSource} at {((Component)audioSource).transform.root} is playing {((Object)audioSource.clip).name} at point {position}");
			}
			else if (SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null)
			{
				SoundTool.Instance.logger.LogDebug((object)$"{audioSource} is playing {((Object)audioSource.clip).name} located at point {position} within ");
				Transform val = ((Component)audioSource).transform;
				while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)audioSource).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}");
					val = val.parent;
				}
				if ((Object)(object)val == (Object)(object)((Component)audioSource).transform.root)
				{
					SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)audioSource).transform.root}");
				}
			}
		}

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

		private static void RunDynamicClipReplacement(AudioSource instance)
		{
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.clip == (Object)null)
			{
				return;
			}
			string name = instance.clip.GetName();
			if (SoundTool.replacedClips.ContainsKey(name))
			{
				if (!originalClips.ContainsKey(name))
				{
					originalClips.Add(name, instance.clip);
				}
				List<RandomAudioClip> list = SoundTool.replacedClips[name];
				float num = 0f;
				foreach (RandomAudioClip item in list)
				{
					num += item.chance;
				}
				float num2 = Random.Range(0f, num);
				{
					foreach (RandomAudioClip item2 in list)
					{
						if (num2 <= item2.chance)
						{
							instance.clip = item2.clip;
							break;
						}
						num2 -= item2.chance;
					}
					return;
				}
			}
			if (originalClips.ContainsKey(name))
			{
				instance.clip = originalClips[name];
				originalClips.Remove(name);
			}
		}

		private static AudioClip ReplaceClipWithNew(AudioClip original)
		{
			if ((Object)(object)original == (Object)null)
			{
				return original;
			}
			string name = original.GetName();
			if (SoundTool.replacedClips.ContainsKey(name))
			{
				if (!originalClips.ContainsKey(name))
				{
					originalClips.Add(name, original);
				}
				List<RandomAudioClip> list = SoundTool.replacedClips[name];
				float num = 0f;
				foreach (RandomAudioClip item in list)
				{
					num += item.chance;
				}
				float num2 = Random.Range(0f, num);
				foreach (RandomAudioClip item2 in list)
				{
					if (num2 <= item2.chance)
					{
						return item2.clip;
					}
					num2 -= item2.chance;
				}
			}
			else if (originalClips.ContainsKey(name))
			{
				AudioClip result = originalClips[name];
				originalClips.Remove(name);
				return result;
			}
			return original;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	internal class GameNetworkManagerPatch
	{
		public static GameObject networkPrefab;

		public static GameObject networkHandlerHost;

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

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

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

		public static event Action ClientNetworkedAudioChanged;

		public static event Action HostNetworkedAudioChanged;

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

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

		[ClientRpc]
		public void RemoveAudioClipClientRpc(string clipName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1355469546u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1355469546u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && networkedAudioClips.ContainsKey(clipName))
			{
				networkedAudioClips.Remove(clipName);
				NetworkHandler.ClientNetworkedAudioChanged?.Invoke();
			}
		}

		[ClientRpc]
		public void SyncAudioClipsClientRpc(Strings clipNames)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3300200130u, val, (RpcDelivery)0);
				((FastBufferWriter)(ref val2)).WriteValueSafe<Strings>(ref clipNames, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3300200130u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			string[] myStrings = clipNames.MyStrings;
			for (int i = 0; i < myStrings.Length; i++)
			{
				if (!networkedAudioClips.ContainsKey(myStrings[i]))
				{
					SendExistingAudioClipServerRpc(myStrings[i]);
				}
			}
		}

		[ClientRpc]
		public void ReceiveSeedClientRpc(int seed)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1556253924u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, seed);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1556253924u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Random.InitState(seed);
					SoundTool.Instance.logger.LogDebug((object)$"Client received a new Unity Random seed of {seed}!");
				}
			}
		}

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

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

		[ServerRpc(RequireOwnership = false)]
		public void SyncAudioClipsServerRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(178607916u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 178607916u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				Strings clipNames = new Strings(networkedAudioClips.Keys.ToArray());
				if (clipNames.MyStrings.Length < 1)
				{
					SoundTool.Instance.logger.LogDebug((object)"No sounds found in networkedClips. Syncing process cancelled!");
				}
				else
				{
					SyncAudioClipsClientRpc(clipNames);
				}
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SendExistingAudioClipServerRpc(string clipName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				ServerRpcParams val = default(ServerRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(4006259189u, val, (RpcDelivery)0);
				bool flag = clipName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false);
				}
				((NetworkBehaviour)this).__endSendServerRpc(ref val2, 4006259189u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
			{
				return;
			}
			if (networkedAudioClips.ContainsKey(clipName))
			{
				byte[] array = null;
				if (SoundTool.clipTypes.ContainsKey(clipName))
				{
					if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.ogg)
					{
						array = OggUtility.AudioClipToByteArray(networkedAudioClips[clipName], out var _);
					}
					else if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.mp3)
					{
						array = Mp3Utility.AudioClipToByteArray(networkedAudioClips[clipName], out var _);
					}
				}
				if (array == null)
				{
					array = WavUtility.AudioClipToByteArray(networkedAudioClips[clipName], out var _);
				}
				ReceiveAudioClipClientRpc(clipName, array);
			}
			else
			{
				SoundTool.Instance.logger.LogWarning((object)"Trying to obtain and sync a sound from the host that does not exist in the host's game!");
			}
		}

		[ServerRpc(RequireOwnership = false)]
		public void SendSeedToClientsServerRpc(int seed)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(4286510828u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, seed);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 4286510828u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && ((NetworkBehaviour)this).IsHost)
				{
					ReceiveSeedClientRpc(seed);
					SoundTool.Instance.logger.LogDebug((object)$"Sending a new Unity random seed of {seed} to all clients...");
				}
			}
		}

		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(2736638642u, new RpcReceiveHandler(__rpc_handler_2736638642));
			NetworkManager.__rpc_func_table.Add(1355469546u, new RpcReceiveHandler(__rpc_handler_1355469546));
			NetworkManager.__rpc_func_table.Add(3300200130u, new RpcReceiveHandler(__rpc_handler_3300200130));
			NetworkManager.__rpc_func_table.Add(1556253924u, new RpcReceiveHandler(__rpc_handler_1556253924));
			NetworkManager.__rpc_func_table.Add(867452943u, new RpcReceiveHandler(__rpc_handler_867452943));
			NetworkManager.__rpc_func_table.Add(3103497155u, new RpcReceiveHandler(__rpc_handler_3103497155));
			NetworkManager.__rpc_func_table.Add(178607916u, new RpcReceiveHandler(__rpc_handler_178607916));
			NetworkManager.__rpc_func_table.Add(4006259189u, new RpcReceiveHandler(__rpc_handler_4006259189));
			NetworkManager.__rpc_func_table.Add(4286510828u, new RpcReceiveHandler(__rpc_handler_4286510828));
		}

		private static void __rpc_handler_2736638642(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_00a6: 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_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 clipName = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false);
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				byte[] audioData = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioData, default(ForPrimitives));
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).ReceiveAudioClipClientRpc(clipName, audioData);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

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

		private static void __rpc_handler_3300200130(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)
			{
				Strings clipNames = default(Strings);
				((FastBufferReader)(ref reader)).ReadValueSafe<Strings>(ref clipNames, default(ForNetworkSerializable));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).SyncAudioClipsClientRpc(clipNames);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1556253924(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 seed = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref seed);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).ReceiveSeedClientRpc(seed);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_867452943(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_00a6: 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_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 clipName = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false);
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				byte[] audioData = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioData, default(ForPrimitives));
				}
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).SendAudioClipServerRpc(clipName, audioData);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

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

		private static void __rpc_handler_178607916(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;
				((NetworkHandler)(object)target).SyncAudioClipsServerRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

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

		private static void __rpc_handler_4286510828(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 seed = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref seed);
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkHandler)(object)target).SendSeedToClientsServerRpc(seed);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "NetworkHandler";
		}
	}
	public struct Strings : INetworkSerializable
	{
		private string[] myStrings;

		public string[] MyStrings
		{
			get
			{
				return myStrings;
			}
			set
			{
				myStrings = value;
			}
		}

		public Strings(string[] myStrings)
		{
			this.myStrings = myStrings;
		}

		public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
		{
			//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_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0080: 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)
			if (serializer.IsWriter)
			{
				FastBufferWriter fastBufferWriter = serializer.GetFastBufferWriter();
				int num = myStrings.Length;
				((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				for (int i = 0; i < myStrings.Length; i++)
				{
					((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe(myStrings[i], false);
				}
			}
			if (serializer.IsReader)
			{
				FastBufferReader fastBufferReader = serializer.GetFastBufferReader();
				int num2 = default(int);
				((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num2, default(ForPrimitives));
				myStrings = new string[num2];
				for (int j = 0; j < num2; j++)
				{
					((FastBufferReader)(ref fastBufferReader)).ReadValueSafe(ref myStrings[j], false);
				}
			}
		}
	}
}
namespace LCSoundTool.Resources
{
	public static class Assets
	{
		internal static AssetBundle bundle;
	}
}

BooBoo Building/BepInEx/plugins/NotAtomicBomb-TerminalApi/TerminalApi.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("NotAtomicBomb")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Terminal Api for the terminal in Lethal Company")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.0+b87452af897d2b57619d1b55b8887fd436be901a")]
[assembly: AssemblyProduct("TerminalApi")]
[assembly: AssemblyTitle("TerminalApi")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/NotAtomicBomb/TerminalApi")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.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 TerminalApi
{
	internal class DelayedAction
	{
		internal Action<TerminalKeyword> Action { get; set; }

		internal TerminalKeyword Keyword { get; set; }

		internal void Run()
		{
			Action(Keyword);
		}
	}
	[BepInPlugin("atomic.terminalapi", "Terminal Api", "1.3.0")]
	public class Plugin : BaseUnityPlugin
	{
		public ManualLogSource Log = new ManualLogSource("Terminal Api");

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin TerminalApi is loaded!");
			Logger.Sources.Add((ILogSource)(object)Log);
			TerminalApi.plugin = this;
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		}
	}
	public static class TerminalApi
	{
		public static Plugin plugin;

		internal static List<DelayedAction> QueuedActions = new List<DelayedAction>();

		public static Terminal Terminal { get; internal set; }

		public static string CurrentText => Terminal.currentText;

		public static TMP_InputField ScreenText => Terminal.screenText;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		public const string PLUGIN_NAME = "TerminalApi";

		public const string PLUGIN_VERSION = "1.4.0";
	}
}
namespace TerminalApi.Events
{
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	[HarmonyPatch(typeof(Terminal))]
	public static class Events
	{
		public class TerminalEventArgs : EventArgs
		{
			public Terminal Terminal { get; set; }
		}

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

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

			public string SubmittedText { get; set; }
		}

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

		public class TerminalTextChangedEventArgs : TerminalEventArgs
		{
			public string NewText;

			public string CurrentInputText;
		}

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

		public static event TerminalEventHandler TerminalAwake;

		public static event TerminalEventHandler TerminalWaking;

		public static event TerminalEventHandler TerminalStarted;

		public static event TerminalEventHandler TerminalStarting;

		public static event TerminalEventHandler TerminalBeginUsing;

		public static event TerminalEventHandler TerminalBeganUsing;

		public static event TerminalEventHandler TerminalExited;

		public static event TerminalParseSentenceEventHandler TerminalParsedSentence;

		public static event TerminalTextChangedEventHandler TerminalTextChanged;

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		public static void Awake(ref Terminal __instance)
		{
			TerminalApi.Terminal = __instance;
			if (TerminalApi.QueuedActions.Count > 0)
			{
				TerminalApi.plugin.Log.LogMessage((object)"In game, now adding words.");
				foreach (DelayedAction queuedAction in TerminalApi.QueuedActions)
				{
					queuedAction.Run();
				}
				TerminalApi.QueuedActions.Clear();
			}
			Events.TerminalAwake?.Invoke(__instance, new TerminalEventArgs
			{
				Terminal = __instance
			});
		}

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

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

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

		[HarmonyPatch("ParsePlayerSentence")]
		[HarmonyPostfix]
		public static void ParsePlayerSentence(ref Terminal __instance, TerminalNode __result)
		{
			string submittedText = __instance.screenText.text.Substring(__instance.screenText.text.Length - __instance.textAdded);
			Events.TerminalParsedSentence?.Invoke(__instance, new TerminalParseSentenceEventArgs
			{
				Terminal = __instance,
				SubmittedText = submittedText,
				ReturnedNode = __result
			});
		}

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

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

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

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

BooBoo Building/BepInEx/plugins/notnotnotswipez-MoreCompany/MoreCompany.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("MoreCompany")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MoreCompany")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("511a1e5e-0611-49f1-b60f-cec69c668fd8")]
[assembly: AssemblyFileVersion("1.7.2")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.7.2.0")]
namespace MoreCompany
{
	[HarmonyPatch(typeof(AudioMixer), "SetFloat")]
	public static class AudioMixerSetFloatPatch
	{
		public static bool Prefix(string name, float value)
		{
			if (name.StartsWith("PlayerVolume") || name.StartsWith("PlayerPitch"))
			{
				string s = name.Replace("PlayerVolume", "").Replace("PlayerPitch", "");
				int num = int.Parse(s);
				PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[num];
				AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource;
				if ((Object)(object)val != (Object)null && Object.op_Implicit((Object)(object)currentVoiceChatAudioSource))
				{
					if (name.StartsWith("PlayerVolume"))
					{
						currentVoiceChatAudioSource.volume = value / 16f;
					}
					else if (name.StartsWith("PlayerPitch"))
					{
						currentVoiceChatAudioSource.pitch = value;
					}
				}
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddTextToChatOnServer")]
	public static class SendChatToServerPatch
	{
		public static bool Prefix(HUDManager __instance, string chatMessage, int playerId = -1)
		{
			if (((NetworkBehaviour)StartOfRound.Instance).IsHost && chatMessage.StartsWith("/mc") && DebugCommandRegistry.commandEnabled)
			{
				string text = chatMessage.Replace("/mc ", "");
				DebugCommandRegistry.HandleCommand(text.Split(new char[1] { ' ' }));
				return false;
			}
			if (chatMessage.StartsWith("[morecompanycosmetics]"))
			{
				ReflectionUtils.InvokeMethod(__instance, "AddPlayerChatMessageServerRpc", new object[2] { chatMessage, 99 });
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageServerRpc")]
	public static class ServerReceiveMessagePatch
	{
		public static string previousDataMessage = "";

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

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

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

		public static void HandleCommand(string[] args)
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			if (!commandEnabled)
			{
				return;
			}
			PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
			switch (args[0])
			{
			case "money":
			{
				int groupCredits = int.Parse(args[1]);
				Terminal val5 = Resources.FindObjectsOfTypeAll<Terminal>().First();
				val5.groupCredits = groupCredits;
				break;
			}
			case "spawnscrap":
			{
				string text = "";
				for (int i = 1; i < args.Length; i++)
				{
					text = text + args[i] + " ";
				}
				text = text.Trim();
				Vector3 val = ((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 2f;
				SpawnableItemWithRarity val2 = null;
				foreach (SpawnableItemWithRarity item in StartOfRound.Instance.currentLevel.spawnableScrap)
				{
					if (item.spawnableItem.itemName.ToLower() == text.ToLower())
					{
						val2 = item;
						break;
					}
				}
				GameObject val3 = Object.Instantiate<GameObject>(val2.spawnableItem.spawnPrefab, val, Quaternion.identity, (Transform)null);
				GrabbableObject component = val3.GetComponent<GrabbableObject>();
				((Component)component).transform.rotation = Quaternion.Euler(component.itemProperties.restingRotation);
				component.fallTime = 0f;
				NetworkObject component2 = val3.GetComponent<NetworkObject>();
				component2.Spawn(false);
				break;
			}
			case "spawnenemy":
			{
				string text2 = "";
				for (int j = 1; j < args.Length; j++)
				{
					text2 = text2 + args[j] + " ";
				}
				text2 = text2.Trim();
				SpawnableEnemyWithRarity val4 = null;
				foreach (SpawnableEnemyWithRarity enemy in StartOfRound.Instance.currentLevel.Enemies)
				{
					if (enemy.enemyType.enemyName.ToLower() == text2.ToLower())
					{
						val4 = enemy;
						break;
					}
				}
				RoundManager.Instance.SpawnEnemyGameObject(((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 2f, 0f, -1, val4.enemyType);
				break;
			}
			case "listall":
				MainClass.StaticLogger.LogInfo((object)"Spawnable scrap:");
				foreach (SpawnableItemWithRarity item2 in StartOfRound.Instance.currentLevel.spawnableScrap)
				{
					MainClass.StaticLogger.LogInfo((object)item2.spawnableItem.itemName);
				}
				MainClass.StaticLogger.LogInfo((object)"Spawnable enemies:");
				{
					foreach (SpawnableEnemyWithRarity enemy2 in StartOfRound.Instance.currentLevel.Enemies)
					{
						MainClass.StaticLogger.LogInfo((object)enemy2.enemyType.enemyName);
					}
					break;
				}
			}
		}
	}
	[HarmonyPatch(typeof(ForestGiantAI), "LookForPlayers")]
	public static class LookForPlayersForestGiantPatch
	{
		public static void Prefix(ForestGiantAI __instance)
		{
			if (__instance.playerStealthMeters.Length != MainClass.newPlayerCount)
			{
				__instance.playerStealthMeters = new float[MainClass.newPlayerCount];
				for (int i = 0; i < MainClass.newPlayerCount; i++)
				{
					__instance.playerStealthMeters[i] = 0f;
				}
			}
		}
	}
	[HarmonyPatch(typeof(SpringManAI), "Update")]
	public static class SpringManAIUpdatePatch
	{
		public static bool Prefix(SpringManAI __instance, ref float ___timeSinceHittingPlayer, ref float ___stopAndGoMinimumInterval, ref bool ___wasOwnerLastFrame, ref bool ___stoppingMovement, ref float ___currentChaseSpeed, ref bool ___hasStopped, ref float ___currentAnimSpeed, ref float ___updateDestinationInterval, ref Vector3 ___tempVelocity, ref float ___targetYRotation, ref float ___setDestinationToPlayerInterval, ref float ___previousYRotation)
		{
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			UpdateBase((EnemyAI)(object)__instance, ref ___updateDestinationInterval, ref ___tempVelocity, ref ___targetYRotation, ref ___setDestinationToPlayerInterval, ref ___previousYRotation);
			if (((EnemyAI)__instance).isEnemyDead)
			{
				return false;
			}
			int currentBehaviourStateIndex = ((EnemyAI)__instance).currentBehaviourStateIndex;
			if (currentBehaviourStateIndex != 0 && currentBehaviourStateIndex == 1)
			{
				if (___timeSinceHittingPlayer >= 0f)
				{
					___timeSinceHittingPlayer -= Time.deltaTime;
				}
				if (((NetworkBehaviour)__instance).IsOwner)
				{
					if (___stopAndGoMinimumInterval > 0f)
					{
						___stopAndGoMinimumInterval -= Time.deltaTime;
					}
					if (!___wasOwnerLastFrame)
					{
						___wasOwnerLastFrame = true;
						if (!___stoppingMovement && ___timeSinceHittingPlayer < 0.12f)
						{
							((EnemyAI)__instance).agent.speed = ___currentChaseSpeed;
						}
						else
						{
							((EnemyAI)__instance).agent.speed = 0f;
						}
					}
					bool flag = false;
					for (int i = 0; i < MainClass.newPlayerCount; i++)
					{
						if (((EnemyAI)__instance).PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false) && StartOfRound.Instance.allPlayerScripts[i].HasLineOfSightToPosition(((Component)__instance).transform.position + Vector3.up * 1.6f, 68f, 60, -1f) && Vector3.Distance(((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position, ((EnemyAI)__instance).eye.position) > 0.3f)
						{
							flag = true;
						}
					}
					if (((EnemyAI)__instance).stunNormalizedTimer > 0f)
					{
						flag = true;
					}
					if (flag != ___stoppingMovement && ___stopAndGoMinimumInterval <= 0f)
					{
						___stopAndGoMinimumInterval = 0.15f;
						if (flag)
						{
							__instance.SetAnimationStopServerRpc();
						}
						else
						{
							__instance.SetAnimationGoServerRpc();
						}
						___stoppingMovement = flag;
					}
				}
				if (___stoppingMovement)
				{
					if (__instance.animStopPoints.canAnimationStop)
					{
						if (!___hasStopped)
						{
							___hasStopped = true;
							__instance.mainCollider.isTrigger = false;
							if (GameNetworkManager.Instance.localPlayerController.HasLineOfSightToPosition(((Component)__instance).transform.position, 70f, 25, -1f))
							{
								float num = Vector3.Distance(((Component)__instance).transform.position, ((Component)GameNetworkManager.Instance.localPlayerController).transform.position);
								if (num < 4f)
								{
									GameNetworkManager.Instance.localPlayerController.JumpToFearLevel(0.9f, true);
								}
								else if (num < 9f)
								{
									GameNetworkManager.Instance.localPlayerController.JumpToFearLevel(0.4f, true);
								}
							}
							if (___currentAnimSpeed > 2f)
							{
								RoundManager.PlayRandomClip(((EnemyAI)__instance).creatureVoice, __instance.springNoises, false, 1f, 0);
								if (__instance.animStopPoints.animationPosition == 1)
								{
									((EnemyAI)__instance).creatureAnimator.SetTrigger("springBoing");
								}
								else
								{
									((EnemyAI)__instance).creatureAnimator.SetTrigger("springBoingPosition2");
								}
							}
						}
						((EnemyAI)__instance).creatureAnimator.SetFloat("walkSpeed", 0f);
						___currentAnimSpeed = 0f;
						if (((NetworkBehaviour)__instance).IsOwner)
						{
							((EnemyAI)__instance).agent.speed = 0f;
							return false;
						}
					}
				}
				else
				{
					if (___hasStopped)
					{
						___hasStopped = false;
						__instance.mainCollider.isTrigger = true;
					}
					___currentAnimSpeed = Mathf.Lerp(___currentAnimSpeed, 6f, 5f * Time.deltaTime);
					((EnemyAI)__instance).creatureAnimator.SetFloat("walkSpeed", ___currentAnimSpeed);
					if (((NetworkBehaviour)__instance).IsOwner)
					{
						((EnemyAI)__instance).agent.speed = Mathf.Lerp(((EnemyAI)__instance).agent.speed, ___currentChaseSpeed, 4.5f * Time.deltaTime);
					}
				}
			}
			return false;
		}

		private static void UpdateBase(EnemyAI __instance, ref float updateDestinationInterval, ref Vector3 tempVelocity, ref float targetYRotation, ref float setDestinationToPlayerInterval, ref float previousYRotation)
		{
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0364: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0379: Unknown result type (might be due to invalid IL or missing references)
			//IL_037e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0425: Unknown result type (might be due to invalid IL or missing references)
			//IL_0454: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.enemyType.isDaytimeEnemy && !__instance.daytimeEnemyLeaving)
			{
				ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "CheckTimeOfDayToLeave", null);
			}
			if (__instance.stunnedIndefinitely <= 0)
			{
				if ((double)__instance.stunNormalizedTimer >= 0.0)
				{
					__instance.stunNormalizedTimer -= Time.deltaTime / __instance.enemyType.stunTimeMultiplier;
				}
				else
				{
					__instance.stunnedByPlayer = null;
					if ((double)__instance.postStunInvincibilityTimer >= 0.0)
					{
						__instance.postStunInvincibilityTimer -= Time.deltaTime * 5f;
					}
				}
			}
			if (!__instance.ventAnimationFinished && (double)__instance.timeSinceSpawn < (double)__instance.exitVentAnimationTime + 0.004999999888241291 * (double)RoundManager.Instance.numberOfEnemiesInScene)
			{
				__instance.timeSinceSpawn += Time.deltaTime;
				if (!((NetworkBehaviour)__instance).IsOwner)
				{
					Vector3 serverPosition = __instance.serverPosition;
					if (__instance.serverPosition != Vector3.zero)
					{
						((Component)__instance).transform.position = __instance.serverPosition;
						((Component)__instance).transform.eulerAngles = new Vector3(((Component)__instance).transform.eulerAngles.x, targetYRotation, ((Component)__instance).transform.eulerAngles.z);
					}
				}
				else if ((double)updateDestinationInterval >= 0.0)
				{
					updateDestinationInterval -= Time.deltaTime;
				}
				else
				{
					__instance.SyncPositionToClients();
					updateDestinationInterval = 0.1f;
				}
				return;
			}
			if (!__instance.ventAnimationFinished)
			{
				__instance.ventAnimationFinished = true;
				if ((Object)(object)__instance.creatureAnimator != (Object)null)
				{
					__instance.creatureAnimator.SetBool("inSpawningAnimation", false);
				}
			}
			if (!((NetworkBehaviour)__instance).IsOwner)
			{
				if (__instance.currentSearch.inProgress)
				{
					__instance.StopSearch(__instance.currentSearch, true);
				}
				__instance.SetClientCalculatingAI(false);
				if (!__instance.inSpecialAnimation)
				{
					((Component)__instance).transform.position = Vector3.SmoothDamp(((Component)__instance).transform.position, __instance.serverPosition, ref tempVelocity, __instance.syncMovementSpeed);
					((Component)__instance).transform.eulerAngles = new Vector3(((Component)__instance).transform.eulerAngles.x, Mathf.LerpAngle(((Component)__instance).transform.eulerAngles.y, targetYRotation, 15f * Time.deltaTime), ((Component)__instance).transform.eulerAngles.z);
				}
				__instance.timeSinceSpawn += Time.deltaTime;
				return;
			}
			if (__instance.isEnemyDead)
			{
				__instance.SetClientCalculatingAI(false);
				return;
			}
			if (!__instance.inSpecialAnimation)
			{
				__instance.SetClientCalculatingAI(true);
			}
			if (__instance.movingTowardsTargetPlayer && (Object)(object)__instance.targetPlayer != (Object)null)
			{
				if ((double)setDestinationToPlayerInterval <= 0.0)
				{
					setDestinationToPlayerInterval = 0.25f;
					__instance.destination = RoundManager.Instance.GetNavMeshPosition(((Component)__instance.targetPlayer).transform.position, RoundManager.Instance.navHit, 2.7f, -1);
				}
				else
				{
					__instance.destination = new Vector3(((Component)__instance.targetPlayer).transform.position.x, __instance.destination.y, ((Component)__instance.targetPlayer).transform.position.z);
					setDestinationToPlayerInterval -= Time.deltaTime;
				}
			}
			if (__instance.inSpecialAnimation)
			{
				return;
			}
			if ((double)updateDestinationInterval >= 0.0)
			{
				updateDestinationInterval -= Time.deltaTime;
			}
			else
			{
				__instance.DoAIInterval();
				updateDestinationInterval = __instance.AIIntervalTime;
			}
			if (!((double)Mathf.Abs(previousYRotation - ((Component)__instance).transform.eulerAngles.y) <= 6.0))
			{
				previousYRotation = ((Component)__instance).transform.eulerAngles.y;
				targetYRotation = previousYRotation;
				if (((NetworkBehaviour)__instance).IsServer)
				{
					ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "UpdateEnemyRotationClientRpc", new object[1] { (short)previousYRotation });
				}
				else
				{
					ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "UpdateEnemyRotationServerRpc", new object[1] { (short)previousYRotation });
				}
			}
		}
	}
	[HarmonyPatch(typeof(SpringManAI), "DoAIInterval")]
	public static class SpringManAIIntervalPatch
	{
		public static bool Prefix(SpringManAI __instance)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			if (((EnemyAI)__instance).moveTowardsDestination)
			{
				((EnemyAI)__instance).agent.SetDestination(((EnemyAI)__instance).destination);
			}
			((EnemyAI)__instance).SyncPositionToClients();
			if (StartOfRound.Instance.allPlayersDead)
			{
				return false;
			}
			if (((EnemyAI)__instance).isEnemyDead)
			{
				return false;
			}
			switch (((EnemyAI)__instance).currentBehaviourStateIndex)
			{
			default:
				return false;
			case 1:
				if (__instance.searchForPlayers.inProgress)
				{
					((EnemyAI)__instance).StopSearch(__instance.searchForPlayers, true);
				}
				if (((EnemyAI)__instance).TargetClosestPlayer(1.5f, false, 70f))
				{
					PlayerControllerB fieldValue = ReflectionUtils.GetFieldValue<PlayerControllerB>(__instance, "previousTarget");
					if ((Object)(object)fieldValue != (Object)(object)((EnemyAI)__instance).targetPlayer)
					{
						ReflectionUtils.SetFieldValue(__instance, "previousTarget", ((EnemyAI)__instance).targetPlayer);
						((EnemyAI)__instance).ChangeOwnershipOfEnemy(((EnemyAI)__instance).targetPlayer.actualClientId);
					}
					((EnemyAI)__instance).movingTowardsTargetPlayer = true;
					return false;
				}
				((EnemyAI)__instance).SwitchToBehaviourState(0);
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(StartOfRound.Instance.allPlayerScripts[0].actualClientId);
				break;
			case 0:
			{
				if (!((NetworkBehaviour)__instance).IsServer)
				{
					((EnemyAI)__instance).ChangeOwnershipOfEnemy(StartOfRound.Instance.allPlayerScripts[0].actualClientId);
					return false;
				}
				for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
				{
					if (((EnemyAI)__instance).PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false) && !Physics.Linecast(((Component)__instance).transform.position + Vector3.up * 0.5f, ((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position, StartOfRound.Instance.collidersAndRoomMaskAndDefault) && Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < 30f)
					{
						((EnemyAI)__instance).SwitchToBehaviourState(1);
						return false;
					}
				}
				if (!__instance.searchForPlayers.inProgress)
				{
					((EnemyAI)__instance).movingTowardsTargetPlayer = false;
					((EnemyAI)__instance).StartSearch(((Component)__instance).transform.position, __instance.searchForPlayers);
					return false;
				}
				break;
			}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(EnemyAI), "GetClosestPlayer")]
	public static class GetClosestPlayerPatch
	{
		public static bool Prefix(EnemyAI __instance, ref PlayerControllerB __result, bool requireLineOfSight = false, bool cannotBeInShip = false, bool cannotBeNearShip = false)
		{
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB val = null;
			__instance.mostOptimalDistance = 2000f;
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				if (!__instance.PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], cannotBeInShip, false))
				{
					continue;
				}
				if (cannotBeNearShip)
				{
					if (StartOfRound.Instance.allPlayerScripts[i].isInElevator)
					{
						continue;
					}
					bool flag = false;
					for (int j = 0; j < RoundManager.Instance.spawnDenialPoints.Length; j++)
					{
						if (Vector3.Distance(RoundManager.Instance.spawnDenialPoints[j].transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < 10f)
						{
							flag = true;
							break;
						}
					}
					if (flag)
					{
						continue;
					}
				}
				if (!requireLineOfSight || !Physics.Linecast(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position, 256))
				{
					__instance.tempDist = Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position);
					if (__instance.tempDist < __instance.mostOptimalDistance)
					{
						__instance.mostOptimalDistance = __instance.tempDist;
						val = StartOfRound.Instance.allPlayerScripts[i];
					}
				}
			}
			__result = val;
			return false;
		}
	}
	[HarmonyPatch(typeof(EnemyAI), "GetAllPlayersInLineOfSight")]
	public static class GetAllPlayersInLineOfSightPatch
	{
		public static bool Prefix(EnemyAI __instance, ref PlayerControllerB[] __result, float width = 45f, int range = 60, Transform eyeObject = null, float proximityCheck = -1f, int layerMask = -1)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Invalid comparison between Unknown and I4
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			if (layerMask == -1)
			{
				layerMask = StartOfRound.Instance.collidersAndRoomMaskAndDefault;
			}
			if ((Object)(object)eyeObject == (Object)null)
			{
				eyeObject = __instance.eye;
			}
			if (__instance.enemyType.isOutsideEnemy && !__instance.enemyType.canSeeThroughFog && (int)TimeOfDay.Instance.currentLevelWeather == 3)
			{
				range = Mathf.Clamp(range, 0, 30);
			}
			List<PlayerControllerB> list = new List<PlayerControllerB>(MainClass.newPlayerCount);
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				if (!__instance.PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false))
				{
					continue;
				}
				Vector3 position = ((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position;
				if (Vector3.Distance(__instance.eye.position, position) < (float)range && !Physics.Linecast(eyeObject.position, position, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))
				{
					Vector3 val = position - eyeObject.position;
					if (Vector3.Angle(eyeObject.forward, val) < width || Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < proximityCheck)
					{
						list.Add(StartOfRound.Instance.allPlayerScripts[i]);
					}
				}
			}
			if (list.Count == MainClass.newPlayerCount)
			{
				__result = StartOfRound.Instance.allPlayerScripts;
				return false;
			}
			if (list.Count > 0)
			{
				__result = list.ToArray();
				return false;
			}
			__result = null;
			return false;
		}
	}
	[HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")]
	public static class DressGirlHauntPatch
	{
		public static bool Prefix(DressGirlAI __instance)
		{
			ReflectionUtils.SetFieldValue(__instance, "timesChoosingAPlayer", ReflectionUtils.GetFieldValue<int>(__instance, "timesChoosingAPlayer") + 1);
			if (ReflectionUtils.GetFieldValue<int>(__instance, "timesChoosingAPlayer") > 1)
			{
				__instance.timer = __instance.hauntInterval - 1f;
			}
			__instance.SFXVolumeLerpTo = 0f;
			((EnemyAI)__instance).creatureVoice.Stop();
			__instance.heartbeatMusic.volume = 0f;
			if (!ReflectionUtils.GetFieldValue<bool>(__instance, "initializedRandomSeed"))
			{
				ReflectionUtils.SetFieldValue(__instance, "ghostGirlRandom", new Random(StartOfRound.Instance.randomMapSeed + 158));
			}
			float num = 0f;
			float num2 = 0f;
			int num3 = 0;
			int num4 = 0;
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				if (StartOfRound.Instance.gameStats.allPlayerStats[i].turnAmount > num3)
				{
					num3 = StartOfRound.Instance.gameStats.allPlayerStats[i].turnAmount;
					num4 = i;
				}
				if (StartOfRound.Instance.allPlayerScripts[i].insanityLevel > num)
				{
					num = StartOfRound.Instance.allPlayerScripts[i].insanityLevel;
					num2 = i;
				}
			}
			int[] array = new int[MainClass.newPlayerCount];
			for (int j = 0; j < MainClass.newPlayerCount; j++)
			{
				if (!StartOfRound.Instance.allPlayerScripts[j].isPlayerControlled)
				{
					array[j] = 0;
					continue;
				}
				array[j] += 80;
				if (num2 == (float)j && num > 1f)
				{
					array[j] += 50;
				}
				if (num4 == j)
				{
					array[j] += 30;
				}
				if (!StartOfRound.Instance.allPlayerScripts[j].hasBeenCriticallyInjured)
				{
					array[j] += 10;
				}
				if ((Object)(object)StartOfRound.Instance.allPlayerScripts[j].currentlyHeldObjectServer != (Object)null && StartOfRound.Instance.allPlayerScripts[j].currentlyHeldObjectServer.scrapValue > 150)
				{
					array[j] += 30;
				}
			}
			__instance.hauntingPlayer = StartOfRound.Instance.allPlayerScripts[RoundManager.Instance.GetRandomWeightedIndex(array, ReflectionUtils.GetFieldValue<Random>(__instance, "ghostGirlRandom"))];
			if (__instance.hauntingPlayer.isPlayerDead)
			{
				for (int k = 0; k < StartOfRound.Instance.allPlayerScripts.Length; k++)
				{
					if (!StartOfRound.Instance.allPlayerScripts[k].isPlayerDead)
					{
						__instance.hauntingPlayer = StartOfRound.Instance.allPlayerScripts[k];
						break;
					}
				}
			}
			Debug.Log((object)$"Little girl: Haunting player with playerClientId: {__instance.hauntingPlayer.playerClientId}; actualClientId: {__instance.hauntingPlayer.actualClientId}");
			((EnemyAI)__instance).ChangeOwnershipOfEnemy(__instance.hauntingPlayer.actualClientId);
			__instance.hauntingLocalPlayer = (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)(object)__instance.hauntingPlayer;
			if (ReflectionUtils.GetFieldValue<Coroutine>(__instance, "switchHauntedPlayerCoroutine") != null)
			{
				((MonoBehaviour)__instance).StopCoroutine(ReflectionUtils.GetFieldValue<Coroutine>(__instance, "switchHauntedPlayerCoroutine"));
			}
			ReflectionUtils.SetFieldValue(__instance, "switchHauntedPlayerCoroutine", ((MonoBehaviour)__instance).StartCoroutine(ReflectionUtils.InvokeMethod<IEnumerator>(__instance, "setSwitchingHauntingPlayer", null)));
			return false;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "AddChatMessage")]
	public static class HudChatPatch
	{
		public static void Prefix(HUDManager __instance, ref string chatMessage, string nameOfUserWhoTyped = "")
		{
			if (!(__instance.lastChatMessage == chatMessage))
			{
				StringBuilder stringBuilder = new StringBuilder(chatMessage);
				for (int i = 0; i < MainClass.newPlayerCount; i++)
				{
					string oldValue = $"[playerNum{i}]";
					string playerUsername = StartOfRound.Instance.allPlayerScripts[i].playerUsername;
					stringBuilder.Replace(oldValue, playerUsername);
				}
				chatMessage = stringBuilder.ToString();
			}
		}
	}
	[HarmonyPatch(typeof(MenuManager), "Awake")]
	public static class MenuManagerLogoOverridePatch
	{
		public static void Postfix(MenuManager __instance)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GameObject gameObject = ((Component)((Component)__instance).transform.parent).gameObject;
				GameObject gameObject2 = ((Component)gameObject.transform.Find("MenuContainer").Find("MainButtons").Find("HeaderImage")).gameObject;
				Image component = gameObject2.GetComponent<Image>();
				MainClass.ReadSettingsFromFile();
				component.sprite = Sprite.Create(MainClass.mainLogo, new Rect(0f, 0f, (float)((Texture)MainClass.mainLogo).width, (float)((Texture)MainClass.mainLogo).height), new Vector2(0.5f, 0.5f));
				CosmeticRegistry.SpawnCosmeticGUI();
				Transform val = gameObject.transform.Find("MenuContainer").Find("LobbyHostSettings").Find("Panel")
					.Find("LobbyHostOptions")
					.Find("OptionsNormal");
				GameObject val2 = Object.Instantiate<GameObject>(MainClass.crewCountUI, val);
				RectTransform component2 = val2.GetComponent<RectTransform>();
				((Transform)component2).localPosition = new Vector3(96.9f, -70f, -6.7f);
				TMP_InputField inputField = ((Component)val2.transform.Find("InputField (TMP)")).GetComponent<TMP_InputField>();
				inputField.characterLimit = 3;
				inputField.text = MainClass.newPlayerCount.ToString();
				((UnityEvent<string>)(object)inputField.onValueChanged).AddListener((UnityAction<string>)delegate(string s)
				{
					if (int.TryParse(s, out var result))
					{
						MainClass.newPlayerCount = result;
						MainClass.newPlayerCount = Mathf.Clamp(MainClass.newPlayerCount, 1, MainClass.maxPlayerCount);
						inputField.text = MainClass.newPlayerCount.ToString();
						MainClass.SaveSettingsToFile();
					}
					else if (s.Length != 0)
					{
						inputField.text = MainClass.newPlayerCount.ToString();
						inputField.caretPosition = 1;
					}
				});
			}
			catch (Exception)
			{
			}
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "AddUserToPlayerList")]
	public static class AddUserPlayerListPatch
	{
		public static bool Prefix(QuickMenuManager __instance, ulong steamId, string playerName, int playerObjectId)
		{
			QuickmenuVisualInjectPatch.PopulateQuickMenu(__instance);
			MainClass.EnablePlayerObjectsBasedOnConnected();
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "RemoveUserFromPlayerList")]
	public static class RemoveUserPlayerListPatch
	{
		public static bool Prefix(QuickMenuManager __instance)
		{
			QuickmenuVisualInjectPatch.PopulateQuickMenu(__instance);
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "Update")]
	public static class QuickMenuUpdatePatch
	{
		public static bool Prefix(QuickMenuManager __instance)
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "NonHostPlayerSlotsEnabled")]
	public static class QuickMenuDisplayPatch
	{
		public static bool Prefix(QuickMenuManager __instance, ref bool __result)
		{
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager), "Start")]
	public static class QuickmenuVisualInjectPatch
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__2_2;

			internal void <PopulateQuickMenu>b__2_2()
			{
				if (!GameNetworkManager.Instance.disableSteam)
				{
				}
			}
		}

		public static GameObject quickMenuScrollInstance;

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

		public static void PopulateQuickMenu(QuickMenuManager __instance)
		{
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Expected O, but got Unknown
			//IL_02d8: 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_02e3: Expected O, but got Unknown
			int childCount = quickMenuScrollInstance.transform.Find("Holder").childCount;
			List<GameObject> list = new List<GameObject>();
			for (int i = 0; i < childCount; i++)
			{
				list.Add(((Component)quickMenuScrollInstance.transform.Find("Holder").GetChild(i)).gameObject);
			}
			foreach (GameObject item in list)
			{
				Object.Destroy((Object)(object)item);
			}
			if (!Object.op_Implicit((Object)(object)StartOfRound.Instance))
			{
				return;
			}
			for (int j = 0; j < StartOfRound.Instance.allPlayerScripts.Length; j++)
			{
				PlayerControllerB playerScript = StartOfRound.Instance.allPlayerScripts[j];
				if (!playerScript.isPlayerControlled && !playerScript.isPlayerDead)
				{
					continue;
				}
				GameObject val = Object.Instantiate<GameObject>(MainClass.playerEntry, quickMenuScrollInstance.transform.Find("Holder"));
				RectTransform component = val.GetComponent<RectTransform>();
				((Transform)component).localScale = Vector3.one;
				((Transform)component).localPosition = new Vector3(0f, 0f - ((Transform)component).localPosition.y, 0f);
				TextMeshProUGUI component2 = ((Component)val.transform.Find("PlayerNameButton").Find("PName")).GetComponent<TextMeshProUGUI>();
				((TMP_Text)component2).text = playerScript.playerUsername;
				Slider playerVolume = ((Component)val.transform.Find("PlayerVolumeSlider")).GetComponent<Slider>();
				int finalIndex = j;
				((UnityEvent<float>)(object)playerVolume.onValueChanged).AddListener((UnityAction<float>)delegate(float f)
				{
					if (playerScript.isPlayerControlled || playerScript.isPlayerDead)
					{
						float num = f / playerVolume.maxValue + 1f;
						if (num <= -1f)
						{
							SoundManager.Instance.playerVoiceVolumes[finalIndex] = -70f;
						}
						else
						{
							SoundManager.Instance.playerVoiceVolumes[finalIndex] = num;
						}
					}
				});
				if (StartOfRound.Instance.localPlayerController.playerClientId == playerScript.playerClientId)
				{
					((Component)playerVolume).gameObject.SetActive(false);
					((Component)val.transform.Find("Text (1)")).gameObject.SetActive(false);
				}
				Button component3 = ((Component)val.transform.Find("KickButton")).GetComponent<Button>();
				((UnityEvent)component3.onClick).AddListener((UnityAction)delegate
				{
					__instance.KickUserFromServer(finalIndex);
				});
				if (!GameNetworkManager.Instance.isHostingGame)
				{
					((Component)component3).gameObject.SetActive(false);
				}
				Button component4 = ((Component)val.transform.Find("ProfileIcon")).GetComponent<Button>();
				ButtonClickedEvent onClick = component4.onClick;
				object obj = <>c.<>9__2_2;
				if (obj == null)
				{
					UnityAction val2 = delegate
					{
						if (!GameNetworkManager.Instance.disableSteam)
						{
						}
					};
					<>c.<>9__2_2 = val2;
					obj = (object)val2;
				}
				((UnityEvent)onClick).AddListener((UnityAction)obj);
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager), "UpdateBoxesSpectateUI")]
	public static class SpectatorBoxUpdatePatch
	{
		public static void Postfix(HUDManager __instance)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<Animator, PlayerControllerB> fieldValue = ReflectionUtils.GetFieldValue<Dictionary<Animator, PlayerControllerB>>(__instance, "spectatingPlayerBoxes");
			int num = -64;
			int num2 = 0;
			int num3 = 0;
			int num4 = -70;
			int num5 = 230;
			int num6 = 4;
			foreach (KeyValuePair<Animator, PlayerControllerB> item in fieldValue)
			{
				if (((Component)item.Key).gameObject.activeInHierarchy)
				{
					GameObject gameObject = ((Component)item.Key).gameObject;
					RectTransform component = gameObject.GetComponent<RectTransform>();
					int num7 = (int)Math.Floor((double)num3 / (double)num6);
					int num8 = num3 % num6;
					int num9 = num8 * num4;
					int num10 = num7 * num5;
					component.anchoredPosition = Vector2.op_Implicit(new Vector3((float)(num + num10), (float)(num2 + num9), 0f));
					num3++;
				}
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager), "FillEndGameStats")]
	public static class HudFillEndGameFix
	{
		public static bool Prefix(HUDManager __instance, EndOfGameStats stats)
		{
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Invalid comparison between Unknown and I4
			int num = 0;
			int num2 = 0;
			for (int i = 0; i < __instance.statsUIElements.playerNamesText.Length; i++)
			{
				PlayerControllerB val = __instance.playersManager.allPlayerScripts[i];
				((TMP_Text)__instance.statsUIElements.playerNamesText[i]).text = "";
				((Behaviour)__instance.statsUIElements.playerStates[i]).enabled = false;
				((TMP_Text)__instance.statsUIElements.playerNotesText[i]).text = "Notes: \n";
				if (val.disconnectedMidGame || val.isPlayerDead || val.isPlayerControlled)
				{
					if (val.isPlayerDead)
					{
						num++;
					}
					else if (val.isPlayerControlled)
					{
						num2++;
					}
					((TMP_Text)__instance.statsUIElements.playerNamesText[i]).text = __instance.playersManager.allPlayerScripts[i].playerUsername;
					((Behaviour)__instance.statsUIElements.playerStates[i]).enabled = true;
					if (__instance.playersManager.allPlayerScripts[i].isPlayerDead)
					{
						if ((int)__instance.playersManager.allPlayerScripts[i].causeOfDeath == 10)
						{
							__instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.missingIcon;
						}
						else
						{
							__instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.deceasedIcon;
						}
					}
					else
					{
						__instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.aliveIcon;
					}
					for (int j = 0; j < 3 && j < stats.allPlayerStats[i].playerNotes.Count; j++)
					{
						TextMeshProUGUI val2 = __instance.statsUIElements.playerNotesText[i];
						((TMP_Text)val2).text = ((TMP_Text)val2).text + "* " + stats.allPlayerStats[i].playerNotes[j] + "\n";
					}
				}
				else
				{
					((TMP_Text)__instance.statsUIElements.playerNotesText[i]).text = "";
				}
			}
			((TMP_Text)__instance.statsUIElements.quotaNumerator).text = RoundManager.Instance.scrapCollectedInLevel.ToString();
			((TMP_Text)__instance.statsUIElements.quotaDenominator).text = RoundManager.Instance.totalScrapValueInLevel.ToString();
			if (StartOfRound.Instance.allPlayersDead)
			{
				((Behaviour)__instance.statsUIElements.allPlayersDeadOverlay).enabled = true;
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "F";
				return false;
			}
			((Behaviour)__instance.statsUIElements.allPlayersDeadOverlay).enabled = false;
			int num3 = 0;
			float num4 = (float)RoundManager.Instance.scrapCollectedInLevel / RoundManager.Instance.totalScrapValueInLevel;
			if (num2 == StartOfRound.Instance.connectedPlayersAmount + 1)
			{
				num3++;
			}
			else if (num > 1)
			{
				num3--;
			}
			if (num4 >= 0.99f)
			{
				num3 += 2;
			}
			else if (num4 >= 0.6f)
			{
				num3++;
			}
			else if (num4 <= 0.25f)
			{
				num3--;
			}
			switch (num3)
			{
			case -1:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "D";
				return false;
			case 0:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "C";
				return false;
			case 1:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "B";
				return false;
			case 2:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "A";
				return false;
			case 3:
				((TMP_Text)__instance.statsUIElements.gradeLetter).text = "S";
				return false;
			default:
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager), "Start")]
	public static class HudStartPatch
	{
		public static void Postfix(HUDManager __instance)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			EndOfGameStatUIElements statsUIElements = __instance.statsUIElements;
			GameObject gameObject = ((Component)((Component)statsUIElements.playerNamesText[0]).gameObject.transform.parent).gameObject;
			GameObject gameObject2 = ((Component)gameObject.transform.parent.parent).gameObject;
			GameObject gameObject3 = ((Component)gameObject2.transform.Find("BGBoxes")).gameObject;
			gameObject2.transform.parent.Find("DeathScreen").SetSiblingIndex(3);
			gameObject3.transform.localScale = new Vector3(2.5f, 1f, 1f);
			MakePlayerHolder(4, gameObject, statsUIElements, new Vector3(426.9556f, -0.7932f, 0f));
			MakePlayerHolder(5, gameObject, statsUIElements, new Vector3(426.9556f, -115.4483f, 0f));
			MakePlayerHolder(6, gameObject, statsUIElements, new Vector3(-253.6783f, -115.4483f, 0f));
			MakePlayerHolder(7, gameObject, statsUIElements, new Vector3(-253.6783f, -0.7932f, 0f));
			for (int i = 8; i < MainClass.newPlayerCount; i++)
			{
				MakePlayerHolder(i, gameObject, statsUIElements, new Vector3(10000f, 10000f, 0f));
			}
		}

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

		public const string PLUGIN_VERSION = "1.7.2";

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

		public static int maxPlayerCount = 50;

		public static bool showCosmetics = true;

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

		public static Texture2D mainLogo;

		public static GameObject quickMenuScrollParent;

		public static GameObject playerEntry;

		public static GameObject crewCountUI;

		public static GameObject cosmeticGUIInstance;

		public static GameObject cosmeticButton;

		public static ManualLogSource StaticLogger;

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

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

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

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

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

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

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

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

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

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

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

		public static void ResizePlayerCache(Dictionary<uint, Dictionary<int, NetworkObject>> ScenePlacedObjects)
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			if (instance.allPlayerObjects.Length == newPlayerCount)
			{
				return;
			}
			playerIdsAndCosmetics.Clear();
			uint num = 10000u;
			int num2 = newPlayerCount - instance.allPlayerObjects.Length;
			int num3 = instance.allPlayerObjects.Length;
			GameObject val = instance.allPlayerObjects[3];
			for (int i = 0; i < num2; i++)
			{
				uint num4 = num + (uint)i;
				GameObject val2 = Object.Instantiate<GameObject>(val);
				NetworkObject component = val2.GetComponent<NetworkObject>();
				ReflectionUtils.SetFieldValue(component, "GlobalObjectIdHash", num4);
				Scene scene = ((Component)component).gameObject.scene;
				int handle = ((Scene)(ref scene)).handle;
				uint num5 = num4;
				if (!ScenePlacedObjects.ContainsKey(num5))
				{
					ScenePlacedObjects.Add(num5, new Dictionary<int, NetworkObject>());
				}
				if (ScenePlacedObjects[num5].ContainsKey(handle))
				{
					string arg = (((Object)(object)ScenePlacedObjects[num5][handle] != (Object)null) ? ((Object)ScenePlacedObjects[num5][handle]).name : "Null Entry");
					throw new Exception(((Object)component).name + " tried to registered with ScenePlacedObjects which already contains " + string.Format("the same {0} value {1} for {2}!", "GlobalObjectIdHash", num5, arg));
				}
				ScenePlacedObjects[num5].Add(handle, component);
				((Object)val2).name = $"Player ({4 + i})";
				val2.transform.parent = null;
				PlayerControllerB componentInChildren = val2.GetComponentInChildren<PlayerControllerB>();
				notSupposedToExistPlayers.Add(componentInChildren);
				componentInChildren.playerClientId = (ulong)(4 + i);
				componentInChildren.isPlayerControlled = false;
				componentInChildren.isPlayerDead = false;
				componentInChildren.DropAllHeldItems(false, false);
				componentInChildren.TeleportPlayer(instance.notSpawnedPosition.position, false, 0f, false, true);
				UnlockableSuit.SwitchSuitForPlayer(componentInChildren, 0, false);
				Array.Resize(ref instance.allPlayerObjects, instance.allPlayerObjects.Length + 1);
				Array.Resize(ref instance.allPlayerScripts, instance.allPlayerScripts.Length + 1);
				Array.Resize(ref instance.gameStats.allPlayerStats, instance.gameStats.allPlayerStats.Length + 1);
				Array.Resize(ref instance.playerSpawnPositions, instance.playerSpawnPositions.Length + 1);
				instance.allPlayerObjects[num3 + i] = val2;
				instance.gameStats.allPlayerStats[num3 + i] = new PlayerStats();
				instance.allPlayerScripts[num3 + i] = componentInChildren;
				instance.playerSpawnPositions[num3 + i] = instance.playerSpawnPositions[3];
			}
		}

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

		public static void Prefix(PlayerControllerB __instance, ulong newPlayerSteamId)
		{
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if (!((Object)(object)networkManager == (Object)null) && networkManager.IsListening && networkManager.IsServer)
			{
				lastId = newPlayerSteamId;
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesClientRpc")]
	public static class SendNewPlayerValuesClientRpcPatch
	{
		public static void Prefix(PlayerControllerB __instance, ref ulong[] playerSteamIds)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening)
			{
				return;
			}
			if (StartOfRound.Instance.mapScreen.radarTargets.Count != MainClass.newPlayerCount)
			{
				List<PlayerControllerB> useless = new List<PlayerControllerB>();
				foreach (PlayerControllerB notSupposedToExistPlayer in MainClass.notSupposedToExistPlayers)
				{
					if (Object.op_Implicit((Object)(object)notSupposedToExistPlayer))
					{
						StartOfRound.Instance.mapScreen.radarTargets.Add(new TransformAndName(((Component)notSupposedToExistPlayer).transform, notSupposedToExistPlayer.playerUsername, false));
					}
					else
					{
						useless.Add(notSupposedToExistPlayer);
					}
				}
				MainClass.notSupposedToExistPlayers.RemoveAll((PlayerControllerB x) => useless.Contains(x));
			}
			if (!networkManager.IsServer)
			{
				return;
			}
			List<ulong> list = new List<ulong>();
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				if (i == (int)__instance.playerClientId)
				{
					list.Add(SendNewPlayerValuesServerRpcPatch.lastId);
				}
				else
				{
					list.Add(__instance.playersManager.allPlayerScripts[i].playerSteamId);
				}
			}
			playerSteamIds = list.ToArray();
		}
	}
	public static class HUDManagerBullshitPatch
	{
		public static bool ManualPrefix(HUDManager __instance)
		{
			return false;
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")]
	public static class SyncShipUnlockablePatch
	{
		public static void Prefix(StartOfRound __instance, ref int[] playerSuitIDs, bool shipLightsOn, Vector3[] placeableObjectPositions, Vector3[] placeableObjectRotations, int[] placeableObjects, int[] storedItems, int[] scrapValues, int[] itemSaveData)
		{
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if (!((Object)(object)networkManager == (Object)null) && networkManager.IsListening && networkManager.IsServer)
			{
				int[] array = new int[MainClass.newPlayerCount];
				for (int i = 0; i < MainClass.newPlayerCount; i++)
				{
					array[i] = __instance.allPlayerScripts[i].currentSuitID;
				}
				playerSuitIDs = array;
			}
		}
	}
	[HarmonyPatch(typeof(NetworkSceneManager), "PopulateScenePlacedObjects")]
	public static class ScenePlacedObjectsInitPatch
	{
		public static void Postfix(ref Dictionary<uint, Dictionary<int, NetworkObject>> ___ScenePlacedObjects)
		{
			MainClass.ResizePlayerCache(___ScenePlacedObjects);
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "LobbyDataIsJoinable")]
	public static class LobbyDataJoinablePatch
	{
		public static bool Prefix(ref bool __result)
		{
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(NetworkConnectionManager), "HandleConnectionApproval")]
	public static class ConnectionApprovalTest
	{
		public static void Prefix(ulong ownerClientId, ConnectionApprovalResponse response)
		{
			if (Object.op_Implicit((Object)(object)StartOfRound.Instance))
			{
				if (StartOfRound.Instance.connectedPlayersAmount >= MainClass.newPlayerCount)
				{
					response.Approved = false;
					response.Reason = "Server is full";
				}
				else
				{
					response.Approved = true;
				}
			}
		}
	}
	[HarmonyPatch(typeof(SteamMatchmaking), "CreateLobbyAsync")]
	public static class LobbyThingPatch
	{
		public static void Prefix(ref int maxMembers)
		{
			MainClass.ReadSettingsFromFile();
			maxMembers = MainClass.newPlayerCount;
		}
	}
	public class ManualHarmonyPatches
	{
		public static void ManualPatch(Harmony HarmonyInstance)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeof(HUDManager), "SyncAllPlayerLevelsServerRpc", new Type[0], (Type[])null), new HarmonyMethod(typeof(HUDManagerBullshitPatch).GetMethod("ManualPrefix")), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
	}
	public class MimicPatches
	{
		[HarmonyPatch(typeof(MaskedPlayerEnemy), "SetEnemyOutside")]
		public class MaskedPlayerEnemyOnEnablePatch
		{
			public static void Postfix(MaskedPlayerEnemy __instance)
			{
				//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)__instance.mimickingPlayer != (Object)null))
				{
					return;
				}
				List<string> list = MainClass.playerIdsAndCosmetics[(int)__instance.mimickingPlayer.playerClientId];
				Transform val = ((Component)__instance).transform.Find("ScavengerModel").Find("metarig");
				CosmeticApplication component = ((Component)val).GetComponent<CosmeticApplication>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.ClearCosmetics();
					Object.Destroy((Object)(object)component);
				}
				component = ((Component)val).gameObject.AddComponent<CosmeticApplication>();
				foreach (string item in list)
				{
					component.ApplyCosmetic(item, startEnabled: true);
				}
				foreach (CosmeticInstance spawnedCosmetic in component.spawnedCosmetics)
				{
					Transform transform = ((Component)spawnedCosmetic).transform;
					transform.localScale *= 0.38f;
				}
			}
		}
	}
	public class ReflectionUtils
	{
		public static void InvokeMethod(object obj, string methodName, object[] parameters)
		{
			Type type = obj.GetType();
			MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			method.Invoke(obj, parameters);
		}

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

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

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

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

		public static void SetFieldValue(object obj, string fieldName, object value)
		{
			Type type = obj.GetType();
			FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			field.SetValue(obj, value);
		}
	}
	[HarmonyPatch(typeof(ShipTeleporter), "Awake")]
	public static class ShipTeleporterAwakePatch
	{
		public static void Postfix(ShipTeleporter __instance)
		{
			int[] array = new int[MainClass.newPlayerCount];
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				array[i] = -1;
			}
			ReflectionUtils.SetFieldValue(__instance, "playersBeingTeleported", array);
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "SpectateNextPlayer")]
	public static class SpectatePatches
	{
		public static bool Prefix(PlayerControllerB __instance)
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			if ((Object)(object)__instance.spectatedPlayerScript != (Object)null)
			{
				num = (int)__instance.spectatedPlayerScript.playerClientId;
			}
			for (int i = 0; i < MainClass.newPlayerCount; i++)
			{
				num = (num + 1) % MainClass.newPlayerCount;
				if (!__instance.playersManager.allPlayerScripts[num].isPlayerDead && __instance.playersManager.allPlayerScripts[num].isPlayerControlled && (Object)(object)__instance.playersManager.allPlayerScripts[num] != (Object)(object)__instance)
				{
					__instance.spectatedPlayerScript = __instance.playersManager.allPlayerScripts[num];
					__instance.SetSpectatedPlayerEffects(false);
					return false;
				}
			}
			if ((Object)(object)__instance.deadBody != (Object)null && ((Component)__instance.deadBody).gameObject.activeSelf)
			{
				__instance.spectateCameraPivot.position = __instance.deadBody.bodyParts[0].position;
				ReflectionUtils.InvokeMethod(__instance, "RaycastSpectateCameraAroundPivot", null);
			}
			StartOfRound.Instance.SetPlayerSafeInShip();
			return false;
		}
	}
	[HarmonyPatch(typeof(SoundManager), "Start")]
	public static class SoundManagerStartPatch
	{
		public static void Postfix()
		{
			int num = MainClass.newPlayerCount - 4;
			int num2 = 4;
			for (int i = 0; i < num; i++)
			{
				Array.Resize(ref SoundManager.Instance.playerVoicePitches, SoundManager.Instance.playerVoicePitches.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoicePitchTargets, SoundManager.Instance.playerVoicePitchTargets.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoiceVolumes, SoundManager.Instance.playerVoiceVolumes.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoicePitchLerpSpeed, SoundManager.Instance.playerVoicePitchLerpSpeed.Length + 1);
				Array.Resize(ref SoundManager.Instance.playerVoiceMixers, SoundManager.Instance.playerVoiceMixers.Length + 1);
				AudioMixerGroup val = ((IEnumerable<AudioMixerGroup>)Resources.FindObjectsOfTypeAll<AudioMixerGroup>()).FirstOrDefault((Func<AudioMixerGroup, bool>)((AudioMixerGroup x) => ((Object)x).name.Contains("Voice")));
				SoundManager.Instance.playerVoicePitches[num2 + i] = 1f;
				SoundManager.Instance.playerVoicePitchTargets[num2 + i] = 1f;
				SoundManager.Instance.playerVoiceVolumes[num2 + i] = 0.5f;
				SoundManager.Instance.playerVoicePitchLerpSpeed[num2 + i] = 3f;
				SoundManager.Instance.playerVoiceMixers[num2 + i] = val;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "GetPlayerSpawnPosition")]
	public static class SpawnPositionClampPatch
	{
		public static void Prefix(ref int playerNum, bool simpleTeleport = false)
		{
			if (playerNum > 3)
			{
				playerNum = 3;
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "OnClientConnect")]
	public static class OnClientConnectedPatch
	{
		public static bool Prefix(StartOfRound __instance, ulong clientId)
		{
			if (!((NetworkBehaviour)__instance).IsServer)
			{
				return false;
			}
			Debug.Log((object)"player connected");
			Debug.Log((object)$"connected players #: {__instance.connectedPlayersAmount}");
			try
			{
				List<int> list = __instance.ClientPlayerList.Values.ToList();
				Debug.Log((object)$"Connecting new player on host; clientId: {clientId}");
				int num = 0;
				for (int i = 1; i < MainClass.newPlayerCount; i++)
				{
					if (!list.Contains(i))
					{
						num = i;
						break;
					}
				}
				__instance.allPlayerScripts[num].actualClientId = clientId;
				__instance.allPlayerObjects[num].GetComponent<NetworkObject>().ChangeOwnership(clientId);
				Debug.Log((object)$"New player assigned object id: {__instance.allPlayerObjects[num]}");
				List<ulong> list2 = new List<ulong>();
				for (int j = 0; j < __instance.allPlayerObjects.Length; j++)
				{
					NetworkObject component = __instance.allPlayerObjects[j].GetComponent<NetworkObject>();
					if (!component.IsOwnedByServer)
					{
						list2.Add(component.OwnerClientId);
					}
					else if (j == 0)
					{
						list2.Add(NetworkManager.Singleton.LocalClientId);
					}
					else
					{
						list2.Add(999uL);
					}
				}
				int groupCredits = Object.FindObjectOfType<Terminal>().groupCredits;
				int profitQuota = TimeOfDay.Instance.profitQuota;
				int quotaFulfilled = TimeOfDay.Instance.quotaFulfilled;
				int num2 = (int)TimeOfDay.Instance.timeUntilDeadline;
				ReflectionUtils.InvokeMethod(__instance, "OnPlayerConnectedClientRpc", new object[10]
				{
					clientId,
					__instance.connectedPlayersAmount,
					list2.ToArray(),
					num,
					groupCredits,
					__instance.currentLevelID,
					profitQuota,
					num2,
					quotaFulfilled,
					__instance.randomMapSeed
				});
				__instance.ClientPlayerList.Add(clientId, num);
				Debug.Log((object)$"client id connecting: {clientId} ; their corresponding player object id: {num}");
			}
			catch (Exception arg)
			{
				Debug.LogError((object)$"Error occured in OnClientConnected! Shutting server down. clientId: {clientId}. Error: {arg}");
				GameNetworkManager.Instance.disconnectionReasonMessage = "Error occured when a player attempted to join the server! Restart the application and please report the glitch!";
				GameNetworkManager.Instance.Disconnect();
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(SteamLobbyManager), "LoadServerList")]
	public static class LoadServerListPatch
	{
		public static bool Prefix(SteamLobbyManager __instance)
		{
			OverrideMethod(__instance);
			return false;
		}

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

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

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

		public Transform hip;

		public Transform lowerArmRight;

		public Transform shinLeft;

		public Transform shinRight;

		public Transform chest;

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

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

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

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

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

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

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

		private void ParentCosmetic(CosmeticInstance cosmeticInstance)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			Transform val = null;
			switch (cosmeticInstance.cosmeticType)
			{
			case CosmeticType.HAT:
				val = head;
				break;
			case CosmeticType.R_LOWER_ARM:
				val = lowerArmRight;
				break;
			case CosmeticType.HIP:
				val = hip;
				break;
			case CosmeticType.L_SHIN:
				val = shinLeft;
				break;
			case CosmeticType.R_SHIN:
				val = shinRight;
				break;
			case CosmeticType.CHEST:
				val = chest;
				break;
			}
			((Component)cosmeticInstance).transform.position = val.position;
			((Component)cosmeticInstance).transform.rotation = val.rotation;
			((Component)cosmeticInstance).transform.parent = val;
		}
	}
	public class CosmeticInstance : MonoBehaviour
	{
		public CosmeticType cosmeticType;

		public string cosmeticId;

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

		public virtual string cosmeticId { get; }

		public virtual string textureIconPath { get; }

		public CosmeticType cosmeticType { get; }

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

			public static UnityAction <>9__8_0;

			public static UnityAction <>9__8_1;

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

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

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

		public static GameObject cosmeticGUI;

		private static GameObject displayGuy;

		private static CosmeticApplication cosmeticApplication;

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

		public const float COSMETIC_PLAYER_SCALE_MULT = 0.38f;

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

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

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

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

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

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

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

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

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

		private Vector2 lastMousePosition;

		private bool dragging = false;

		private Vector3 rotationalVelocity = Vector3.zero;

		public float dragSpeed = 1f;

		public float airDrag = 0.99f;

		public GameObject target;

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

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

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

BooBoo Building/BepInEx/plugins/Ozone-BepInUtils/NicholaScott.BepInEx.Utils.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.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("NicholaScott.BepInEx.Utils")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NicholaScott.BepInEx.Utils")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("40BD9160-E0A3-402F-AE4F-059B39509F43")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace NicholaScott.BepInEx.Utils
{
	[BepInPlugin("NicholaScott.BepInEx.Utils", "BepInUtils", "1.2.1")]
	public class BepInUtils : BaseUnityPlugin
	{
		public void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"System loaded.");
		}
	}
}
namespace NicholaScott.BepInEx.Utils.Resources
{
	public static class Extensions
	{
		public static byte[] ReadAllBytes(this Stream inStream)
		{
			if (inStream is MemoryStream memoryStream)
			{
				return memoryStream.ToArray();
			}
			using MemoryStream memoryStream2 = new MemoryStream();
			inStream.CopyTo(memoryStream2);
			return memoryStream2.ToArray();
		}
	}
}
namespace NicholaScott.BepInEx.Utils.Patching
{
	[AttributeUsage(AttributeTargets.Class)]
	public class Production : Attribute
	{
	}
	public static class Extensions
	{
		public static Harmony PatchAttribute<TAttr>(this Assembly sourceAssembly, string guid, Action<object> logMethod = null) where TAttr : Attribute
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			Harmony val = new Harmony(string.Join(".", guid, typeof(TAttr).Name));
			foreach (Type item in from t in sourceAssembly.GetTypes()
				where t.IsClass && t.GetCustomAttributes(typeof(TAttr)).Any()
				select t)
			{
				int num = val.GetPatchedMethods().Count();
				val.PatchAll(item);
				int num2 = val.GetPatchedMethods().Count();
				int num3 = num2 - num;
				logMethod?.Invoke(string.Format("[{0}] Patched class {1}, containing {2} method{3}", typeof(TAttr).Name, item.Name, num3, (num3 > 1) ? "s." : "."));
			}
			return val;
		}
	}
}
namespace NicholaScott.BepInEx.Utils.Instancing
{
	public class AutoSingleton<TPrepare> where TPrepare : Object
	{
		private static TPrepare _instance;

		public static TPrepare Instance
		{
			get
			{
				if (!Object.op_Implicit((Object)(object)_instance))
				{
					_instance = Object.FindObjectOfType<TPrepare>();
				}
				return _instance;
			}
		}
	}
	public class CachedItem<TItem>
	{
		public delegate TItem InstanceLocator();

		public delegate bool ItemNotNull(TItem item);

		private InstanceLocator locatorMethod;

		private ItemNotNull notNullMethod;

		private bool valueAssigned = false;

		private TItem value;

		public TItem Value
		{
			get
			{
				if (valueAssigned && (notNullMethod == null || notNullMethod(value)))
				{
					return value;
				}
				value = locatorMethod();
				valueAssigned = notNullMethod == null || notNullMethod(value);
				return value;
			}
		}

		public CachedItem(InstanceLocator locator, ItemNotNull notNull = null)
		{
			locatorMethod = locator;
			notNullMethod = notNull;
		}

		public void ClearCache()
		{
			valueAssigned = false;
		}

		public static implicit operator TItem(CachedItem<TItem> item)
		{
			return item.Value;
		}
	}
	public class Singleton<TPrepare>
	{
		public static TPrepare Instance;

		public static ManualLogSource Logger
		{
			get
			{
				object? obj = typeof(BaseUnityPlugin).GetProperty("Logger", BindingFlags.Instance | BindingFlags.NonPublic)?.GetGetMethod(nonPublic: true)?.Invoke(Instance, Array.Empty<object>());
				return (ManualLogSource)((obj is ManualLogSource) ? obj : null);
			}
		}
	}
	public class Singleton<TPrepare, TConfig> : Singleton<TPrepare>
	{
		public static TConfig Configuration;
	}
}
namespace NicholaScott.BepInEx.Utils.Configuration
{
	[AttributeUsage(AttributeTargets.Field)]
	public class ConfigEntryDefinition : Attribute
	{
		public string Category;

		public string Name;

		public string Description;
	}
	public static class Extensions
	{
		public static TStruct BindStruct<TStruct>(this ConfigFile config, TStruct defaults) where TStruct : struct
		{
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Expected O, but got Unknown
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Expected O, but got Unknown
			object obj = new TStruct();
			FieldInfo[] fields = typeof(TStruct).GetFields();
			foreach (FieldInfo fieldInfo in fields)
			{
				ConfigEntryDefinition configEntryDefinition = fieldInfo.GetCustomAttribute<ConfigEntryDefinition>() ?? new ConfigEntryDefinition();
				configEntryDefinition.Category = configEntryDefinition.Category ?? "General";
				configEntryDefinition.Name = configEntryDefinition.Name ?? fieldInfo.Name;
				configEntryDefinition.Description = configEntryDefinition.Description ?? "";
				object obj2 = ((typeof(ConfigFile).GetMethods()?.Where((MethodInfo m) => m.IsGenericMethod && m.Name.Contains("Bind") && m.GetParameters()[0].ParameterType == typeof(ConfigDefinition)).First())?.MakeGenericMethod(fieldInfo.FieldType))?.Invoke(config, new object[3]
				{
					(object)new ConfigDefinition(configEntryDefinition.Category, configEntryDefinition.Name),
					fieldInfo.GetValue(defaults),
					(object)new ConfigDescription(configEntryDefinition.Description, (AcceptableValueBase)null, Array.Empty<object>())
				});
				object obj3 = (obj2?.GetType().GetProperty("Value"))?.GetGetMethod().Invoke(obj2, null);
				fieldInfo.SetValue(obj, obj3 ?? fieldInfo.GetValue(defaults));
			}
			return (TStruct)obj;
		}
	}
}

BooBoo Building/BepInEx/plugins/Ozone-Disregard_Early_Voting/NicholaScott.LethalCompany.ControlDeathVoting.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;
using NicholaScott.BepInEx.Utils.Configuration;
using NicholaScott.BepInEx.Utils.Instancing;
using NicholaScott.BepInEx.Utils.Patching;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("NicholaScott.LethalCompany.ControlDeathVoting")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NicholaScott.LethalCompany.ControlDeathVoting")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("A319A87A-6846-4876-8B42-C043875E31CF")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace NicholaScott.LethalCompany.ControlDeathVoting;

[BepInDependency("NicholaScott.BepInEx.Utils", "1.2.0")]
[BepInPlugin("NicholaScott.LethalCompany.ControlDeathVoting", "Control Death Voting", "1.0.2")]
public class ControlDeathVoting : BaseUnityPlugin
{
	public struct Configuration
	{
		public enum VoteType
		{
			Vanilla,
			MoreThanOne,
			NoVoting
		}

		[ConfigEntryDefinition(Description = "Vanilla changes nothing. MoreThanOne requires at least 2 votes to leave. NoVoting disables early ship voting entirely.")]
		public VoteType VoteHandling;

		[ConfigEntryDefinition(Description = "Multiplied by the default value of time to wait once a successful vote is cast before the ship leaves.")]
		public float ScaleShipLeaveDelay;
	}

	public void Awake()
	{
		Singleton<ControlDeathVoting>.Instance = this;
		Singleton<ControlDeathVoting, Configuration>.Configuration = Extensions.BindStruct<Configuration>(((BaseUnityPlugin)this).Config, new Configuration
		{
			VoteHandling = Configuration.VoteType.MoreThanOne,
			ScaleShipLeaveDelay = 1f
		});
		Extensions.PatchAttribute<Production>(Assembly.GetExecutingAssembly(), ((BaseUnityPlugin)this).Info.Metadata.GUID, (Action<object>)((BaseUnityPlugin)this).Logger.LogInfo);
	}
}
[Production]
public static class VotingPatches
{
	[HarmonyPatch(typeof(TimeOfDay), "SetShipLeaveEarlyServerRpc")]
	[HarmonyPrefix]
	public static bool IgnoreVotesIfServer(TimeOfDay __instance)
	{
		ControlDeathVoting.Configuration configuration = Singleton<ControlDeathVoting, ControlDeathVoting.Configuration>.Configuration;
		switch (configuration.VoteHandling)
		{
		case ControlDeathVoting.Configuration.VoteType.Vanilla:
			return true;
		case ControlDeathVoting.Configuration.VoteType.MoreThanOne:
			__instance.votesForShipToLeaveEarly++;
			if (__instance.votesForShipToLeaveEarly > 1 && __instance.votesForShipToLeaveEarly >= StartOfRound.Instance.connectedPlayersAmount + 1 - StartOfRound.Instance.livingPlayers)
			{
				__instance.SetShipLeaveEarlyClientRpc(__instance.normalizedTimeOfDay + 0.1f * configuration.ScaleShipLeaveDelay, __instance.votesForShipToLeaveEarly);
			}
			else
			{
				__instance.AddVoteForShipToLeaveEarlyClientRpc();
			}
			return false;
		case ControlDeathVoting.Configuration.VoteType.NoVoting:
			__instance.votesForShipToLeaveEarly++;
			__instance.AddVoteForShipToLeaveEarlyClientRpc();
			return false;
		default:
			return false;
		}
	}
}

BooBoo Building/BepInEx/plugins/Renegades-FlashlightToggle/FlashlightToggle.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

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

		public const string PLUGIN_NAME = "Control";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace Flashlight
{
	public class FlashButton : LcInputActions
	{
		[InputAction("<Keyboard>/f", Name = "Flashlight")]
		public InputAction FlashKey { get; set; }
	}
	[BepInPlugin("rr.Flashlight", "Flashlight", "1.5.0")]
	public class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource logSource;

		internal static FlashButton InputActionInstance = new FlashButton();

		private Harmony _harmony = new Harmony("Flashlight");

		private void Awake()
		{
			_harmony.PatchAll(typeof(Plugin));
			((BaseUnityPlugin)this).Logger.LogInfo((object)"------Flashlight done.------");
			logSource = ((BaseUnityPlugin)this).Logger;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
		[HarmonyPostfix]
		public static void ClearFlashlight(PlayerControllerB __instance)
		{
			__instance.pocketedFlashlight = null;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		public static void ReadInput(PlayerControllerB __instance)
		{
			if (((!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || (((NetworkBehaviour)__instance).IsServer && !__instance.isHostPlayerObject)) && !__instance.isTestingPlayer) || __instance.inTerminalMenu || __instance.isTypingChat || !Application.isFocused)
			{
				return;
			}
			if (__instance.currentlyHeldObjectServer is FlashlightItem && (Object)(object)__instance.currentlyHeldObjectServer != (Object)(object)__instance.pocketedFlashlight)
			{
				__instance.pocketedFlashlight = __instance.currentlyHeldObjectServer;
			}
			if ((Object)(object)__instance.pocketedFlashlight == (Object)null || !InputActionInstance.FlashKey.triggered || !(__instance.pocketedFlashlight is FlashlightItem) || !__instance.pocketedFlashlight.isHeld)
			{
				return;
			}
			try
			{
				__instance.pocketedFlashlight.UseItemOnClient(true);
				if (!(__instance.currentlyHeldObjectServer is FlashlightItem))
				{
					GrabbableObject pocketedFlashlight = __instance.pocketedFlashlight;
					((Behaviour)((FlashlightItem)((pocketedFlashlight is FlashlightItem) ? pocketedFlashlight : null)).flashlightBulbGlow).enabled = false;
					GrabbableObject pocketedFlashlight2 = __instance.pocketedFlashlight;
					((Behaviour)((FlashlightItem)((pocketedFlashlight2 is FlashlightItem) ? pocketedFlashlight2 : null)).flashlightBulb).enabled = false;
					GrabbableObject pocketedFlashlight3 = __instance.pocketedFlashlight;
					if (((pocketedFlashlight3 is FlashlightItem) ? pocketedFlashlight3 : null).isBeingUsed)
					{
						((Behaviour)__instance.helmetLight).enabled = true;
						GrabbableObject pocketedFlashlight4 = __instance.pocketedFlashlight;
						((FlashlightItem)((pocketedFlashlight4 is FlashlightItem) ? pocketedFlashlight4 : null)).usingPlayerHelmetLight = true;
						GrabbableObject pocketedFlashlight5 = __instance.pocketedFlashlight;
						((FlashlightItem)((pocketedFlashlight5 is FlashlightItem) ? pocketedFlashlight5 : null)).PocketFlashlightServerRpc(true);
					}
					else
					{
						((Behaviour)__instance.helmetLight).enabled = false;
						GrabbableObject pocketedFlashlight6 = __instance.pocketedFlashlight;
						((FlashlightItem)((pocketedFlashlight6 is FlashlightItem) ? pocketedFlashlight6 : null)).usingPlayerHelmetLight = false;
						GrabbableObject pocketedFlashlight7 = __instance.pocketedFlashlight;
						((FlashlightItem)((pocketedFlashlight7 is FlashlightItem) ? pocketedFlashlight7 : null)).PocketFlashlightServerRpc(false);
					}
				}
			}
			catch
			{
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/RickArg-Helmet_Cameras/HelmetCamera.dll

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

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

		public static ConfigEntry<int> config_isHighQuality;

		public static ConfigEntry<int> config_renderDistance;

		public static ConfigEntry<int> config_cameraFps;

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

		public const string PLUGIN_NAME = "Helmet_Cameras";

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

		private bool isMonitorChanged = false;

		private GameObject helmetCameraNew;

		private bool isSceneLoaded = false;

		private bool isCoroutineStarted = false;

		private int currentTransformIndex;

		private int resolution = 0;

		private int renderDistance = 50;

		private float cameraFps = 30f;

		private float elapsed;

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

		public void Start()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			isCoroutineStarted = false;
			while ((Object)(object)helmetCameraNew == (Object)null)
			{
				helmetCameraNew = new GameObject("HelmetCamera");
			}
			Scene activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).name != "MainMenu")
			{
				activeScene = SceneManager.GetActiveScene();
				if (((Scene)(ref activeScene)).name != "InitScene")
				{
					activeScene = SceneManager.GetActiveScene();
					if (((Scene)(ref activeScene)).name != "InitSceneLaunchOptions")
					{
						isSceneLoaded = true;
						Debug.Log((object)"[HELMET_CAMERAS] Starting coroutine...");
						((MonoBehaviour)this).StartCoroutine(LoadSceneEnter());
						return;
					}
				}
			}
			isSceneLoaded = false;
			isMonitorChanged = false;
		}

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

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

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

BooBoo Building/BepInEx/plugins/Rozebud-FOV_Adjust/FovAdjust.dll

Decompiled 9 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FovAdjust")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FovAdjust")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("dfb6681a-9f25-4737-a7fe-10b3c23f65b3")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace FovAdjust;

[BepInPlugin("Rozebud.FovAdjust", "FOV Adjust", "1.1.1")]
public class FovAdjustBase : BaseUnityPlugin
{
	private const string modGUID = "Rozebud.FovAdjust";

	private const string modName = "FOV Adjust";

	private const string modVer = "1.1.1";

	private readonly Harmony harmony = new Harmony("Rozebud.FovAdjust");

	private static FovAdjustBase Instance;

	public static ManualLogSource log;

	public static ConfigEntry<float> configFov;

	public static ConfigEntry<bool> configHideVisor;

	public static bool inDebugMode;

	private void Awake()
	{
		if ((Object)(object)Instance == (Object)null)
		{
			Instance = this;
		}
		log = Logger.CreateLogSource("Rozebud.FovAdjust");
		log.LogInfo((object)"Starting.");
		configFov = ((BaseUnityPlugin)this).Config.Bind<float>("General", "fov", 66f, "Change the field of view of the camera. Clamped from 66 to 130 for my sanity. Also keep in mind that this is vertical FOV.");
		configHideVisor = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "hideVisor", false, "Changes whether the first person visor is visible.");
		PlayerControllerBPatches.newTargetFovBase = Mathf.Clamp(configFov.Value, 66f, 130f);
		PlayerControllerBPatches.hideVisor = configHideVisor.Value;
		log.LogInfo((object)"Configs DONE!");
		PlayerControllerBPatches.calculateVisorStuff();
		harmony.PatchAll(typeof(PlayerControllerBPatches));
		harmony.PatchAll(typeof(HUDManagerPatches));
		log.LogInfo((object)"All FOV Adjust patches have loaded successfully.");
	}
}
public class PlayerControllerBPatches
{
	public static float newTargetFovBase = 66f;

	private static float prefixCamFov = 0f;

	public static bool hideVisor = false;

	private static Vector3 visorScale;

	public static Vector3 visorScaleBottom = new Vector3(0.68f, 0.8f, 0.95f);

	public static Vector3 visorScaleTop = new Vector3(0.68f, 0.35f, 0.99f);

	public static float linToSinLerp = 0.6f;

	public static float visorScaleTopRefFOV = 130f;

	[HarmonyPatch(typeof(PlayerControllerB), "Awake")]
	[HarmonyPostfix]
	private static void Awake_Postfix(PlayerControllerB __instance)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		if (!filterPlayerControllers(__instance))
		{
			__instance.localVisor.localScale = visorScale;
		}
	}

	[HarmonyPatch(typeof(PlayerControllerB), "Update")]
	[HarmonyPrefix]
	private static void Update_Prefix(PlayerControllerB __instance)
	{
		//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_01cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: 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_0199: Unknown result type (might be due to invalid IL or missing references)
		if (filterPlayerControllers(__instance))
		{
			return;
		}
		prefixCamFov = __instance.gameplayCamera.fieldOfView;
		if (FovAdjustBase.inDebugMode)
		{
			if (((ButtonControl)Keyboard.current.minusKey).wasPressedThisFrame)
			{
				visorScale.x -= 0.00049999997f;
				FovAdjustBase.log.LogMessage((object)visorScale);
			}
			else if (((ButtonControl)Keyboard.current.equalsKey).wasPressedThisFrame)
			{
				visorScale.x += 0.00049999997f;
				FovAdjustBase.log.LogMessage((object)visorScale);
			}
			if (((ButtonControl)Keyboard.current.leftBracketKey).wasPressedThisFrame)
			{
				visorScale.y -= 0.00049999997f;
				FovAdjustBase.log.LogMessage((object)visorScale);
			}
			else if (((ButtonControl)Keyboard.current.rightBracketKey).wasPressedThisFrame)
			{
				visorScale.y += 0.00049999997f;
				FovAdjustBase.log.LogMessage((object)visorScale);
			}
			if (((ButtonControl)Keyboard.current.semicolonKey).wasPressedThisFrame)
			{
				visorScale.z -= 0.00049999997f;
				FovAdjustBase.log.LogMessage((object)visorScale);
			}
			else if (((ButtonControl)Keyboard.current.quoteKey).wasPressedThisFrame)
			{
				visorScale.z += 0.00049999997f;
				FovAdjustBase.log.LogMessage((object)visorScale);
			}
		}
		if (__instance.localVisor.localScale != visorScale)
		{
			__instance.localVisor.localScale = visorScale;
		}
	}

	[HarmonyPatch(typeof(PlayerControllerB), "Update")]
	[HarmonyPostfix]
	private static void Update_Postfix(PlayerControllerB __instance)
	{
		if (!filterPlayerControllers(__instance))
		{
			float num = newTargetFovBase;
			if (__instance.inTerminalMenu)
			{
				num = 60f;
			}
			else if (__instance.IsInspectingItem)
			{
				num = 46f;
			}
			else if (__instance.isSprinting)
			{
				num *= 1.03f;
			}
			__instance.gameplayCamera.fieldOfView = Mathf.Lerp(prefixCamFov, num, 6f * Time.deltaTime);
		}
	}

	[HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")]
	[HarmonyPostfix]
	private static void LateUpdate_Postfix(PlayerControllerB __instance)
	{
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		if (!filterPlayerControllers(__instance) && (newTargetFovBase > 66f || FovAdjustBase.inDebugMode))
		{
			__instance.localVisor.position = __instance.localVisor.position + __instance.localVisor.rotation * new Vector3(0f, 0f, -0.06f);
		}
	}

	private static float easeOutSine(float x)
	{
		return Mathf.Sin(x * (float)Math.PI / 2f);
	}

	public static void calculateVisorStuff()
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: 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_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		if (hideVisor)
		{
			visorScale = new Vector3(0f, 0f, 0f);
		}
		else if (newTargetFovBase > 66f || FovAdjustBase.inDebugMode)
		{
			float num = (newTargetFovBase - 66f) / (visorScaleTopRefFOV - 66f);
			num = Mathf.Lerp(num, easeOutSine(num), linToSinLerp);
			visorScale = Vector3.LerpUnclamped(visorScaleBottom, visorScaleTop, num);
		}
		else
		{
			visorScale = new Vector3(0.36f, 0.49f, 0.49f);
		}
	}

	private static bool filterPlayerControllers(PlayerControllerB player)
	{
		return !((NetworkBehaviour)player).IsOwner || !player.isPlayerControlled || (((NetworkBehaviour)player).IsServer && !player.isHostPlayerObject && !player.isTestingPlayer);
	}
}
public class HUDManagerPatches
{
	[HarmonyPatch(typeof(HUDManager), "SubmitChat_performed")]
	[HarmonyPrefix]
	public static bool SubmitChat_performed_Prefix(HUDManager __instance)
	{
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0125: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0239: Unknown result type (might be due to invalid IL or missing references)
		//IL_023e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0262: Unknown result type (might be due to invalid IL or missing references)
		//IL_0267: Unknown result type (might be due to invalid IL or missing references)
		string text = __instance.chatTextField.text;
		if (text.StartsWith("/fov"))
		{
			string[] array = text.Split(new char[1] { ' ' });
			if (array.Length > 1 && float.TryParse(array[1], out var result))
			{
				result = Mathf.Clamp(result, 66f, 130f);
				PlayerControllerBPatches.newTargetFovBase = result;
				if (!FovAdjustBase.inDebugMode)
				{
					PlayerControllerBPatches.calculateVisorStuff();
				}
			}
		}
		else if (text.StartsWith("/toggleVisor"))
		{
			PlayerControllerBPatches.hideVisor = !PlayerControllerBPatches.hideVisor;
			PlayerControllerBPatches.calculateVisorStuff();
		}
		else if (text.StartsWith("/recalcVisor") && FovAdjustBase.inDebugMode)
		{
			PlayerControllerBPatches.calculateVisorStuff();
		}
		else if (text.StartsWith("/setScaleBottom") && FovAdjustBase.inDebugMode)
		{
			string[] array2 = text.Split(new char[1] { ' ' });
			PlayerControllerBPatches.visorScaleBottom = new Vector3(float.Parse(array2[1]), float.Parse(array2[2]), float.Parse(array2[3]));
		}
		else if (text.StartsWith("/setScaleTop") && FovAdjustBase.inDebugMode)
		{
			string[] array3 = text.Split(new char[1] { ' ' });
			PlayerControllerBPatches.visorScaleTop = new Vector3(float.Parse(array3[1]), float.Parse(array3[2]), float.Parse(array3[3]));
		}
		else if (text.StartsWith("/setSinAmount") && FovAdjustBase.inDebugMode)
		{
			string[] array4 = text.Split(new char[1] { ' ' });
			PlayerControllerBPatches.linToSinLerp = float.Parse(array4[1]);
		}
		else if (text.StartsWith("/setTopRef") && FovAdjustBase.inDebugMode)
		{
			string[] array5 = text.Split(new char[1] { ' ' });
			PlayerControllerBPatches.visorScaleTopRefFOV = float.Parse(array5[1]);
		}
		else
		{
			if (!text.StartsWith("/gimmeMyValues") || !FovAdjustBase.inDebugMode)
			{
				return true;
			}
			ManualLogSource log = FovAdjustBase.log;
			Vector3 val = PlayerControllerBPatches.visorScaleBottom;
			log.LogMessage((object)("visorScaleBottom: " + ((object)(Vector3)(ref val)).ToString()));
			ManualLogSource log2 = FovAdjustBase.log;
			val = PlayerControllerBPatches.visorScaleTop;
			log2.LogMessage((object)("visorScaleTop: " + ((object)(Vector3)(ref val)).ToString()));
			FovAdjustBase.log.LogMessage((object)("linToSinLerp: " + PlayerControllerBPatches.linToSinLerp));
			FovAdjustBase.log.LogMessage((object)("visorScaleTopRefFOV: " + PlayerControllerBPatches.visorScaleTopRefFOV));
		}
		__instance.localPlayer = GameNetworkManager.Instance.localPlayerController;
		__instance.localPlayer.isTypingChat = false;
		__instance.chatTextField.text = "";
		EventSystem.current.SetSelectedGameObject((GameObject)null);
		((Behaviour)__instance.typingIndicator).enabled = false;
		return false;
	}
}

BooBoo Building/BepInEx/plugins/Rune580-LethalCompany_InputUtils/LethalCompanyInputUtils.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.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using LethalCompanyInputUtils.Data;
using LethalCompanyInputUtils.Utils;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LethalCompanyInputUtils")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+9e95a88c49ab86635dbebf33cfb26802052a8769")]
[assembly: AssemblyProduct("LethalCompanyInputUtils")]
[assembly: AssemblyTitle("LethalCompanyInputUtils")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalCompanyInputUtils
{
	public static class LcInputActionApi
	{
		private static readonly Dictionary<string, LcInputActions> InputActionsMap = new Dictionary<string, LcInputActions>();

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

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

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

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

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

		internal static void CalculateVerticalMaxForGamepad(KepRemapPanel panel)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			int num = panel.remappableKeys.Count((RemappableKey key) => key.gamepadOnly);
			float horizontalOffset = panel.horizontalOffset;
			Rect rect = ((Component)((Transform)panel.keyRemapContainer).parent).GetComponent<RectTransform>().rect;
			float num2 = Mathf.Floor(((Rect)(ref rect)).width / horizontalOffset);
			panel.maxVertical = (float)num / num2;
			LayoutElement obj = EnsureLayoutElement(panel);
			obj.minHeight += (panel.maxVertical + 3f) * panel.verticalOffset;
		}

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

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

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

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

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

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

		public const string ModVersion = "0.4.4";

		private Harmony? _harmony;

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

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

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


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


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


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

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

		internal static ManualLogSource Logger { get; } = _logSource;


		internal static void SetLogSource(ManualLogSource logSource)
		{
			_logSource = logSource;
		}
	}
	internal static class RuntimeHelper
	{
		public static void SetLocalPosY(this RectTransform rectTransform, float y)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			Vector3 localPosition = ((Transform)rectTransform).localPosition;
			((Transform)rectTransform).localPosition = new Vector3(localPosition.x, y, localPosition.z);
		}

		public static void SetPivotY(this RectTransform rectTransform, float y)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			rectTransform.pivot = new Vector2(rectTransform.pivot.x, y);
		}

		public static void SetAnchorMinY(this RectTransform rectTransform, float y)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			rectTransform.anchorMin = new Vector2(rectTransform.anchorMin.x, y);
		}

		public static void SetAnchorMaxY(this RectTransform rectTransform, float y)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			rectTransform.anchorMax = new Vector2(rectTransform.anchorMax.x, y);
		}

		public static void SetAnchoredPosY(this RectTransform rectTransform, float y)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, y);
		}
	}
}
namespace LethalCompanyInputUtils.Patches
{
	public static class InputControlPathPatches
	{
		[HarmonyPatch]
		public static class ToHumanReadableStringPatch
		{
			public static IEnumerable<MethodBase> TargetMethods()
			{
				return from method in AccessTools.GetDeclaredMethods(typeof(InputControlPath))
					where method.Name == "ToHumanReadableString" && method.ReturnType == typeof(string)
					select method;
			}

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

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

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

		public string? origPath;

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

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

		public BindingOverrides(IEnumerable<InputBinding> bindings)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			overrides = new List<BindingOverride>();
			foreach (InputBinding binding in bindings)
			{
				InputBinding current = binding;
				if (((InputBinding)(ref current)).hasOverrides)
				{
					BindingOverride item = new BindingOverride
					{
						action = ((InputBinding)(ref current)).action,
						origPath = ((InputBinding)(ref current)).path,
						path = ((InputBinding)(ref current)).overridePath
					};
					overrides.Add(item);
				}
			}
		}

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

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

		public string? ActionId { get; set; }

		public string? GamepadPath { get; set; }

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


		public string? KbmInteractions { get; set; }

		public string? GamepadInteractions { get; set; }

		public string? Name { get; set; }

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

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

		private string? _actionId;

		private string? _kbmPath;

		private string? _gamepadPath;

		private string? _kbmInteractions;

		private string? _gamepadInteractions;

		private InputActionType _actionType;

		private string? _name;

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

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

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

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

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

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

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

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

		public InputAction Finish()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			if (_name == null)
			{
				_name = _actionId;
			}
			InputAction val = new InputAction(_actionId, _actionType, (string)null, (string)null, (string)null, (string)null);
			_mapBuilder.WithAction(val);
			if (_kbmPath != null)
			{
				_mapBuilder.WithBinding(new InputBinding(_kbmPath, _actionId, (string)null, (string)null, _kbmInteractions, _name));
			}
			if (_gamepadPath != null)
			{
				_mapBuilder.WithBinding(new InputBinding(_gamepadPath, _actionId, (string)null, (string)null, _gamepadInteractions, _name));
			}
			return val;
		}
	}
	public class InputActionMapBuilder
	{
		private readonly InputActionMap _actionMap = new InputActionMap(mapName);

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


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

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

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

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

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

		private readonly string _jsonPath;

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

		internal bool Loaded;

		private readonly Dictionary<PropertyInfo, InputActionAttribute> _inputProps;

		public InputActionAsset Asset { get; }

		internal bool WasEnabled { get; private set; }

		public bool Enabled => Asset.enabled;

		internal IReadOnlyCollection<InputActionReference> ActionRefs => _actionRefs;

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

		public BepInPlugin Plugin { get; }

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

		internal InputActionAsset GetAsset()
		{
			return Asset;
		}

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

		public virtual void CreateInputActions(in InputActionMapBuilder builder)
		{
		}

		public virtual void OnAssetLoaded()
		{
		}

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

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

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

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

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

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

BooBoo Building/BepInEx/plugins/Sligili-HDLethalCompany/HDLethalCompany.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HDLethalCompany.Patch;
using HDLethalCompany.Tools;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("HDLethalCompanyRemake")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HDLethalCompanyRemake")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("7f379bc1-1fd4-4c72-9247-a181862eec6b")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HDLethalCompany
{
	[BepInPlugin("HDLethalCompany", "HDLethalCompany-Sligili", "1.5.6")]
	public class HDLethalCompanyInitialization : BaseUnityPlugin
	{
		private static ConfigEntry<float> config_ResMult;

		private static ConfigEntry<bool> config_EnablePostProcessing;

		private static ConfigEntry<bool> config_EnableFog;

		private static ConfigEntry<bool> config_EnableAntialiasing;

		private static ConfigEntry<bool> config_EnableResolution;

		private static ConfigEntry<bool> config_EnableFoliage;

		private static ConfigEntry<int> config_FogQuality;

		private static ConfigEntry<int> config_TextureQuality;

		private static ConfigEntry<int> config_LOD;

		private static ConfigEntry<int> config_ShadowmapQuality;

		private Harmony _harmony;

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

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

		public const string Name = "HDLethalCompany-Sligili";

		public const string Ver = "1.5.6";
	}
}
namespace HDLethalCompany.Tools
{
	public class Reflection
	{
		public static object GetInstanceField(Type type, object instance, string fieldName)
		{
			BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
			FieldInfo field = type.GetField(fieldName, bindingAttr);
			return field.GetValue(instance);
		}

		public static object CallMethod(object instance, string methodName, params object[] args)
		{
			MethodInfo method = instance.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
			if (method != null)
			{
				return method.Invoke(instance, args);
			}
			return null;
		}
	}
}
namespace HDLethalCompany.Patch
{
	internal class GraphicsPatch
	{
		public static bool m_enablePostProcessing;

		public static bool m_enableFog;

		public static bool m_enableAntiAliasing;

		public static bool m_enableResolutionFix;

		public static bool m_enableFoliage = true;

		public static int m_setFogQuality;

		public static int m_setTextureResolution;

		public static int m_setLOD;

		public static int m_setShadowQuality;

		private static HDRenderPipelineAsset myAsset;

		public static AssetBundle assetBundle;

		public static float anchorOffsetX = 439.48f;

		public static float anchorOffsetY = 244.8f;

		public static float anchorOffsetZ;

		public static float multiplier;

		public static float m_widthResolution;

		public static float m_heightResolution;

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

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

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

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

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

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

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

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

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

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

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

BooBoo Building/BepInEx/plugins/Sligili-More_Emotes/MoreEmotes1.2.2.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using MoreEmotes.Patch;
using Tools;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FuckYouMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FuckYouMod")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5ecc2bf2-af12-4e83-a6f1-cf2eacbf3060")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Tools
{
	public class Reflection
	{
		public static object GetInstanceField(Type type, object instance, string fieldName)
		{
			BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
			FieldInfo field = type.GetField(fieldName, bindingAttr);
			return field.GetValue(instance);
		}

		public static object CallMethod(object instance, string methodName, params object[] args)
		{
			MethodInfo method = instance.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
			if (method != null)
			{
				return method.Invoke(instance, args);
			}
			return null;
		}
	}
}
namespace MoreEmotes
{
	[BepInPlugin("MoreEmotes", "MoreEmotes-Sligili", "1.2.2")]
	public class FuckYouModInitialization : BaseUnityPlugin
	{
		private Harmony _harmony;

		private ConfigEntry<string> config_KeyWheel;

		private ConfigEntry<bool> config_InventoryCheck;

		private ConfigEntry<string> config_KeyEmote3;

		private ConfigEntry<string> config_KeyEmote4;

		private ConfigEntry<string> config_KeyEmote5;

		private ConfigEntry<string> config_KeyEmote6;

		private ConfigEntry<string> config_KeyEmote7;

		private ConfigEntry<string> config_KeyEmote8;

		private void Awake()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"MoreEmotes loaded");
			EmotePatch.animationsBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animationsbundle"));
			EmotePatch.animatorBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animatorbundle"));
			EmotePatch.local = EmotePatch.animatorBundle.LoadAsset<RuntimeAnimatorController>("Assets/MoreEmotes/NEWmetarig.controller");
			EmotePatch.others = EmotePatch.animatorBundle.LoadAsset<RuntimeAnimatorController>("Assets/MoreEmotes/NEWmetarigOtherPlayers.controller");
			CustomAudioAnimationEvent.claps[0] = EmotePatch.animationsBundle.LoadAsset<AudioClip>("Assets/MoreEmotes/SingleClapEmote1.wav");
			CustomAudioAnimationEvent.claps[1] = EmotePatch.animationsBundle.LoadAsset<AudioClip>("Assets/MoreEmotes/SingleClapEmote2.wav");
			ConfigFile();
			IncompatibilityAids();
			_harmony = new Harmony("MoreEmotes");
			_harmony.PatchAll(typeof(EmotePatch));
		}

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

		private void ConfigFile()
		{
			EmotePatch.keybinds = new string[9];
			config_KeyWheel = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL", "Key", "v", (ConfigDescription)null);
			EmotePatch.wheelKeybind = config_KeyWheel.Value;
			config_InventoryCheck = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "InventoryCheck", true, "Prevents some emotes from performing while holding any item/scrap");
			EmotePatch.InvCheck = config_InventoryCheck.Value;
			config_KeyEmote3 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Middle Finger", "3", (ConfigDescription)null);
			EmotePatch.keybinds[2] = config_KeyEmote3.Value.Replace(" ", "");
			config_KeyEmote4 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "The Griddy", "6", (ConfigDescription)null);
			EmotePatch.keybinds[5] = config_KeyEmote4.Value.Replace(" ", "");
			config_KeyEmote5 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Shy", "5", (ConfigDescription)null);
			EmotePatch.keybinds[4] = config_KeyEmote5.Value.Replace(" ", "");
			config_KeyEmote6 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Clap", "4", (ConfigDescription)null);
			EmotePatch.keybinds[3] = config_KeyEmote6.Value.Replace(" ", "");
			config_KeyEmote7 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Twerk", "7", (ConfigDescription)null);
			EmotePatch.keybinds[6] = config_KeyEmote7.Value.Replace(" ", "");
			config_KeyEmote8 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Salute", "8", (ConfigDescription)null);
			EmotePatch.keybinds[7] = config_KeyEmote8.Value.Replace(" ", "");
		}
	}
	public static class PluginInfo
	{
		public const string Guid = "MoreEmotes";

		public const string Name = "MoreEmotes-Sligili";

		public const string Ver = "1.2.2";
	}
}
namespace MoreEmotes.Patch
{
	internal class EmotePatch
	{
		public static AssetBundle animationsBundle;

		public static AssetBundle animatorBundle;

		public static string[] keybinds;

		public static string wheelKeybind;

		private static CallbackContext context;

		public static RuntimeAnimatorController local;

		public static RuntimeAnimatorController others;

		private static int currentEmoteID;

		private static float svMovSpeed;

		public static bool IncompatibleStuff;

		public static bool InvCheck;

		public static bool emoteWheelIsOpened;

		public static GameObject wheel;

		public static GameObject rebindmenu;

		public static GameObject btn;

		private static SelectionWheel selectionWheel;

		[HarmonyPatch(typeof(MenuManager), "Start")]
		[HarmonyPostfix]
		private static void MenuStart(MenuManager __instance)
		{
			GameObject val = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesPanel.prefab");
			GameObject val2 = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesButton.prefab");
			GameObject gameObject = ((Component)((Component)__instance).transform.parent).gameObject;
			GameObject gameObject2 = ((Component)((Component)gameObject.transform.Find("MenuContainer")).transform.Find("SettingsPanel")).gameObject;
			if ((Object)(object)btn != (Object)null)
			{
				Object.Destroy((Object)(object)btn.gameObject);
			}
			btn = Object.Instantiate<GameObject>(val2, gameObject2.transform);
			btn.transform.SetSiblingIndex(7);
			if ((Object)(object)rebindmenu != (Object)null)
			{
				Object.Destroy((Object)(object)rebindmenu.gameObject);
			}
			rebindmenu = Object.Instantiate<GameObject>(val, gameObject2.transform);
			RebindBtn.defaultKeys = keybinds;
			BasicToggle.configValueInv = InvCheck;
			if ((Object)(object)gameObject2.GetComponent<SetupEverything>() == (Object)null)
			{
				gameObject2.AddComponent<SetupEverything>();
			}
			SetupEverything.configValue = InvCheck;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPostfix]
		private static void StartPostfix(PlayerControllerB __instance)
		{
			GameObject gameObject = ((Component)((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel")).transform.Find("metarig")).gameObject;
			CustomAudioAnimationEvent customAudioAnimationEvent = gameObject.AddComponent<CustomAudioAnimationEvent>();
			svMovSpeed = __instance.movementSpeed;
			customAudioAnimationEvent.player = __instance;
			if (Object.FindObjectsOfType(typeof(SelectionWheel)).Length == 0)
			{
				GameObject val = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesMenu.prefab");
				GameObject gameObject2 = ((Component)((Component)GameObject.Find("Systems").gameObject.transform.Find("UI")).gameObject.transform.Find("Canvas")).gameObject;
				GameObject val2 = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesPanel.prefab");
				GameObject val3 = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesButton.prefab");
				GameObject gameObject3 = ((Component)((Component)gameObject2.transform.Find("QuickMenu")).transform.Find("SettingsPanel")).gameObject;
				if ((Object)(object)btn != (Object)null)
				{
					Object.Destroy((Object)(object)btn.gameObject);
				}
				btn = Object.Instantiate<GameObject>(val3, gameObject3.transform);
				btn.transform.SetSiblingIndex(7);
				if ((Object)(object)rebindmenu != (Object)null)
				{
					Object.Destroy((Object)(object)rebindmenu.gameObject);
				}
				rebindmenu = Object.Instantiate<GameObject>(val2, gameObject3.transform);
				RebindBtn.defaultKeys = keybinds;
				BasicToggle.configValueInv = InvCheck;
				if ((Object)(object)wheel != (Object)null)
				{
					Object.Destroy((Object)(object)wheel.gameObject);
				}
				wheel = Object.Instantiate<GameObject>(val, gameObject2.transform);
				selectionWheel = wheel.AddComponent<SelectionWheel>();
				SelectionWheel.emotes_Keybinds = new string[keybinds.Length + 1];
				SelectionWheel.emotes_Keybinds = keybinds;
				if ((Object)(object)gameObject3.GetComponent<SetupEverything>() == (Object)null)
				{
					gameObject3.AddComponent<SetupEverything>();
				}
				SetupEverything.configValue = InvCheck;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(PlayerControllerB __instance)
		{
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.isPlayerControlled || !((NetworkBehaviour)__instance).IsOwner)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = others;
				return;
			}
			if ((Object)(object)__instance.playerBodyAnimator != (Object)(object)local)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = local;
			}
			if (__instance.performingEmote)
			{
				currentEmoteID = __instance.playerBodyAnimator.GetInteger("emoteNumber");
			}
			if (!IncompatibleStuff)
			{
				bool flag = (bool)Reflection.CallMethod(__instance, "CheckConditionsForEmote") && currentEmoteID == 6 && __instance.performingEmote;
				__instance.movementSpeed = (flag ? (svMovSpeed / 2f) : svMovSpeed);
			}
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", InvCheck ? 1 : 0);
			}
			else
			{
				InvCheck = PlayerPrefs.GetInt("InvCheck") == 1;
			}
			if (!PlayerPrefs.HasKey("Emote_Wheel"))
			{
				PlayerPrefs.SetString("Emote_Wheel", wheelKeybind);
			}
			if (InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[PlayerPrefs.GetString("Emote_Wheel")], 0f) && !emoteWheelIsOpened && !__instance.isPlayerDead && !__instance.inTerminalMenu && !__instance.quickMenuManager.isMenuOpen)
			{
				emoteWheelIsOpened = true;
				Cursor.visible = true;
				Cursor.lockState = (CursorLockMode)2;
				wheel.SetActive(emoteWheelIsOpened);
				__instance.disableLookInput = true;
			}
			else if ((!InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[PlayerPrefs.GetString("Emote_Wheel")], 0f) && emoteWheelIsOpened) || __instance.quickMenuManager.isMenuOpen)
			{
				if (!__instance.quickMenuManager.isMenuOpen || __instance.isPlayerDead)
				{
					int selectedEmoteID = selectionWheel.selectedEmoteID;
					if (selectedEmoteID <= 3 || selectedEmoteID == 6 || !InvCheck)
					{
						__instance.PerformEmote(context, selectedEmoteID);
					}
					else if (!__instance.isHoldingObject)
					{
						__instance.PerformEmote(context, selectedEmoteID);
					}
					Cursor.visible = false;
					Cursor.lockState = (CursorLockMode)1;
				}
				if (__instance.isPlayerDead && !__instance.quickMenuManager.isMenuOpen)
				{
					Cursor.visible = false;
					Cursor.lockState = (CursorLockMode)1;
				}
				__instance.disableLookInput = false;
				emoteWheelIsOpened = false;
				wheel.SetActive(emoteWheelIsOpened);
			}
			if (!emoteWheelIsOpened && !__instance.quickMenuManager.isMenuOpen)
			{
				EmoteInput(keybinds[2], needsEmptyHands: false, 3, __instance);
				EmoteInput(keybinds[3], needsEmptyHands: true, 4, __instance);
				EmoteInput(keybinds[4], needsEmptyHands: true, 5, __instance);
				EmoteInput(keybinds[5], needsEmptyHands: false, 6, __instance);
				EmoteInput(keybinds[6], needsEmptyHands: true, 7, __instance);
				EmoteInput(keybinds[7], needsEmptyHands: true, 8, __instance);
			}
		}

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

		[HarmonyPatch(typeof(PlayerControllerB), "CheckConditionsForEmote")]
		[HarmonyPrefix]
		private static bool prefixCheckConditions(ref bool __result, PlayerControllerB __instance)
		{
			bool flag = (bool)Reflection.GetInstanceField(typeof(PlayerControllerB), __instance, "isJumping");
			if (currentEmoteID == 6)
			{
				__result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && __instance.moveInputVector.x == 0f && !__instance.isSprinting && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu && !__instance.isTypingChat;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "PerformEmote")]
		[HarmonyPrefix]
		private static void PerformEmotePrefix(CallbackContext context, int emoteID, PlayerControllerB __instance)
		{
			if ((emoteID >= 3 || emoteWheelIsOpened || ((CallbackContext)(ref context)).performed) && ((((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject)) || __instance.isTestingPlayer) && (bool)Reflection.CallMethod(__instance, "CheckConditionsForEmote") && !(__instance.timeSinceStartingEmote < 0.5f))
			{
				__instance.timeSinceStartingEmote = 0f;
				__instance.performingEmote = true;
				__instance.playerBodyAnimator.SetInteger("emoteNumber", emoteID);
				__instance.StartPerformingEmoteServerRpc();
			}
		}
	}
	public class CustomAudioAnimationEvent : MonoBehaviour
	{
		private Animator animator;

		private AudioSource SoundsSource;

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

		public PlayerControllerB player;

		private void Start()
		{
			animator = ((Component)this).GetComponent<Animator>();
			SoundsSource = player.movementAudio;
		}

		public void PlayClapSound()
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			if (player.performingEmote && (!((NetworkBehaviour)player).IsOwner || !player.isPlayerControlled || animator.GetInteger("emoteNumber") == 4))
			{
				bool flag = player.isInHangarShipRoom && player.playersManager.hangarDoorsClosed;
				RoundManager.Instance.PlayAudibleNoise(((Component)player).transform.position, 22f, 0.6f, 0, flag, 6);
				SoundsSource.pitch = Random.Range(0.59f, 0.79f);
				SoundsSource.PlayOneShot(claps[Random.Range(0, claps.Length)]);
			}
		}

		public void PlayFootstepSound()
		{
			if (player.performingEmote && (!((NetworkBehaviour)player).IsOwner || !player.isPlayerControlled || animator.GetInteger("emoteNumber") == 6 || animator.GetInteger("emoteNumber") == 8) && ((Vector2)(ref player.moveInputVector)).sqrMagnitude == 0f)
			{
				player.PlayFootstepLocal();
				player.PlayFootstepServer();
			}
		}
	}
	public enum Emotes
	{
		Dance = 1,
		Point,
		Middle_Finger,
		Clap,
		Shy,
		The_Griddy,
		Twerk,
		Salute
	}
	public class SelectionWheel : MonoBehaviour
	{
		public RectTransform selectionBlock;

		public Text emoteInformation;

		public Text pageInformation;

		private int blocksNumber = 8;

		private int currentBlock = 1;

		public int pageNumber;

		public int selectedEmoteID;

		private float angle;

		private float pageCooldown = 0.1f;

		public GameObject[] Pages;

		private int cuadrante = 0;

		public string selectedEmoteName;

		public float wheelMovementOffset = 3.3f;

		public static string[] emotes_Keybinds;

		private Vector2 center;

		private void OnEnable()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			center = new Vector2((float)(Screen.width / 2), (float)(Screen.height / 2));
			PlayerInput component = GameObject.Find("PlayerSettingsObject").GetComponent<PlayerInput>();
			emotes_Keybinds[0] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote1", false), 0, (DisplayStringOptions)0);
			emotes_Keybinds[1] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote2", false), 0, (DisplayStringOptions)0);
			Cursor.visible = true;
			selectionBlock = ((Component)((Component)this).gameObject.transform.Find("SelectedEmote")).gameObject.GetComponent<RectTransform>();
			GameObject gameObject = ((Component)((Component)this).gameObject.transform.Find("FunctionalContent")).gameObject;
			emoteInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("EmoteInfo")).GetComponent<Text>();
			Pages = (GameObject[])(object)new GameObject[gameObject.transform.childCount];
			pageInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("PageNumber")).GetComponent<Text>();
			pageInformation.text = "Page " + Pages.Length + "/" + (pageNumber + 1);
			for (int i = 0; i < gameObject.transform.childCount; i++)
			{
				Pages[i] = ((Component)gameObject.transform.GetChild(i)).gameObject;
			}
			Mouse.current.WarpCursorPosition(center);
		}

		private void Update()
		{
			wheelSelection();
			pageSelection();
			selectedEmoteID = currentBlock + Mathf.RoundToInt((float)(blocksNumber / 4)) + blocksNumber * pageNumber;
			displayEmoteInfo();
		}

		private void wheelSelection()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: 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_0197: Unknown result type (might be due to invalid IL or missing references)
			if (!(Vector2.Distance(center, ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue()) < wheelMovementOffset))
			{
				bool flag = ((InputControl<float>)(object)((Pointer)Mouse.current).position.x).ReadValue() > center.x;
				bool flag2 = ((InputControl<float>)(object)((Pointer)Mouse.current).position.y).ReadValue() > center.y;
				cuadrante = ((!flag) ? (flag2 ? 2 : 3) : (flag2 ? 1 : 4));
				float num = (((InputControl<float>)(object)((Pointer)Mouse.current).position.y).ReadValue() - center.y) / (((InputControl<float>)(object)((Pointer)Mouse.current).position.x).ReadValue() - center.x);
				float num2 = 180 * (cuadrante - ((cuadrante <= 2) ? 1 : 2));
				angle = Mathf.Atan(num) * (180f / (float)Math.PI) + num2;
				if (angle == 90f)
				{
					angle = 270f;
				}
				else if (angle == 270f)
				{
					angle = 90f;
				}
				float num3 = 360 / blocksNumber;
				currentBlock = Mathf.RoundToInt((angle - num3 * 1.5f) / num3);
				((Transform)selectionBlock).localRotation = Quaternion.Euler(((Component)this).transform.rotation.z, ((Component)this).transform.rotation.y, num3 * (float)currentBlock);
			}
		}

		private void pageSelection()
		{
			pageInformation.text = "Page " + Pages.Length + "/" + (pageNumber + 1);
			if (pageCooldown > 0f)
			{
				pageCooldown -= Time.deltaTime;
			}
			else if (((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() != 0f)
			{
				GameObject[] pages = Pages;
				foreach (GameObject val in pages)
				{
					val.SetActive(false);
				}
				int num = ((((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() > 0f) ? 1 : (-1));
				if (pageNumber + 1 > Pages.Length - 1 && num > 0)
				{
					pageNumber = 0;
				}
				else if (pageNumber - 1 < 0 && num < 0)
				{
					pageNumber = Pages.Length - 1;
				}
				else
				{
					pageNumber += num;
				}
				Pages[pageNumber].SetActive(true);
				pageCooldown = 0.1f;
			}
		}

		private void displayEmoteInfo()
		{
			string text = ((selectedEmoteID > emotes_Keybinds.Length) ? "" : emotes_Keybinds[selectedEmoteID - 1]);
			object obj;
			if (selectedEmoteID <= Enum.GetValues(typeof(Emotes)).Length)
			{
				Emotes emotes = (Emotes)selectedEmoteID;
				obj = emotes.ToString().Replace("_", " ");
			}
			else
			{
				obj = "EMPTY";
			}
			string text2 = (string)obj;
			if (!PlayerPrefs.HasKey(text2.Replace(" ", "_")))
			{
				PlayerPrefs.SetString(text2.Replace(" ", "_"), (selectedEmoteID > emotes_Keybinds.Length) ? "" : emotes_Keybinds[selectedEmoteID - 1]);
			}
			else
			{
				text = PlayerPrefs.GetString(text2.Replace(" ", "_"));
			}
			emoteInformation.text = text2 + "\n[" + text.ToUpper() + "]";
		}
	}
	public class RebindBtn : MonoBehaviour
	{
		public string defaultKey;

		public static string[] defaultKeys;

		public string playerPrefs;

		public GameObject waitingForInput;

		public Text keyInfo;

		public Text description;

		private void Start()
		{
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			string text = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text;
			try
			{
				int num = (int)(Emotes)Enum.Parse(typeof(Emotes), text.Replace(" ", "_"));
				defaultKey = defaultKeys[num - 1];
			}
			catch
			{
				defaultKey = "V";
			}
			playerPrefs = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text.Replace(" ", "_");
			((Component)((Component)((Component)this).transform.parent).transform.Find("Delete")).gameObject.AddComponent<DeleteBtn>();
			keyInfo = ((Component)((Component)this).transform.Find("InputText")).GetComponent<Text>();
			waitingForInput = ((Component)((Component)this).transform.Find("wait")).gameObject;
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener(new UnityAction(GetKey));
			if (!PlayerPrefs.HasKey(playerPrefs))
			{
				PlayerPrefs.SetString(playerPrefs, defaultKey);
			}
			SetKeybind(PlayerPrefs.GetString(playerPrefs));
		}

		public void SetKeybind(string key)
		{
			PlayerPrefs.SetString(playerPrefs, key);
			keyInfo.text = key;
			((MonoBehaviour)this).StopAllCoroutines();
			waitingForInput.SetActive(false);
		}

		public void GetKey()
		{
			waitingForInput.SetActive(true);
			((MonoBehaviour)this).StartCoroutine(WaitForKey(delegate(string key)
			{
				SetKeybind(key);
			}));
		}

		private IEnumerator WaitForKey(Action<string> callback)
		{
			while (!((ButtonControl)Keyboard.current.anyKey).wasPressedThisFrame)
			{
				yield return (object)new WaitForEndOfFrame();
				Observable.CallOnce<InputControl>(InputSystem.onAnyButtonPress, (Action<InputControl>)delegate(InputControl ctrl)
				{
					callback((ctrl.device == Keyboard.current) ? ctrl.name : defaultKey);
				});
			}
		}
	}
	public class DeleteBtn : MonoBehaviour
	{
		private RebindBtn rebindBtn;

		private void Start()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			rebindBtn = ((Component)((Component)((Component)this).transform.parent).transform.Find("Button")).GetComponent<RebindBtn>();
			Button component = ((Component)this).GetComponent<Button>();
			((UnityEvent)component.onClick).AddListener(new UnityAction(deleteKey));
		}

		public void deleteKey()
		{
			rebindBtn.SetKeybind(string.Empty);
		}
	}
	public class BasicToggle : MonoBehaviour
	{
		private Toggle tog;

		public static bool configValueInv;

		public string playerPrefs;

		private void Start()
		{
			tog = ((Component)this).GetComponent<Toggle>();
			((UnityEvent<bool>)(object)tog.onValueChanged).AddListener((UnityAction<bool>)SetNewValue);
			if (!PlayerPrefs.HasKey(playerPrefs))
			{
				PlayerPrefs.SetInt(playerPrefs, configValueInv ? 1 : 0);
			}
		}

		public void SetNewValue(bool arg)
		{
			PlayerPrefs.SetInt(playerPrefs, tog.isOn ? 1 : 0);
		}
	}
	public class ButtonBasic : MonoBehaviour
	{
		public GameObject[] alternateActive = (GameObject[])(object)new GameObject[1];

		private void Start()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener(new UnityAction(onButtonTrigger));
			if (((Object)((Component)this).gameObject).name.Equals("BackButton"))
			{
				alternateActive[0] = ((Component)((Component)this).transform.parent).gameObject;
			}
			if (((Object)((Component)this).gameObject).name.Equals("MoreEmotesButton(Clone)"))
			{
				alternateActive[0] = ((Component)((Component)((Component)this).transform.parent).gameObject.transform.Find("MoreEmotesPanel(Clone)")).gameObject;
			}
		}

		public void onButtonTrigger()
		{
			GameObject[] array = alternateActive;
			foreach (GameObject val in array)
			{
				val.SetActive((!val.activeInHierarchy) ? true : false);
			}
		}
	}
	public class SetupEverything : MonoBehaviour
	{
		private GameObject panel;

		public static bool configValue;

		private void Start()
		{
			panel = ((Component)((Component)this).transform.Find("MoreEmotesPanel(Clone)")).gameObject;
			((Component)panel.transform.Find("Version")).GetComponent<Text>().text = "Sligili - 1.2.2";
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", configValue ? 1 : 0);
			}
			SetupMenuButton();
			BackButton();
			KeybindButtons();
			Others();
		}

		private void SetupMenuButton()
		{
			GameObject gameObject = ((Component)((Component)this).transform.Find("MoreEmotesButton(Clone)")).gameObject;
			gameObject.AddComponent<ButtonBasic>();
		}

		private void BackButton()
		{
			GameObject gameObject = ((Component)panel.transform.Find("BackButton")).gameObject;
			gameObject.AddComponent<ButtonBasic>();
		}

		private void KeybindButtons()
		{
			GameObject gameObject = ((Component)panel.transform.Find("KeybindButtons")).gameObject;
			GameObject[] array = (GameObject[])(object)new GameObject[gameObject.transform.childCount];
			for (int i = 0; i < gameObject.transform.childCount; i++)
			{
				array[i] = ((Component)gameObject.transform.GetChild(i)).gameObject;
			}
			GameObject[] array2 = array;
			foreach (GameObject val in array2)
			{
				((Component)val.transform.Find("Button")).gameObject.AddComponent<RebindBtn>();
			}
		}

		private void Others()
		{
			GameObject gameObject = ((Component)panel.transform.Find("Inv")).gameObject;
			gameObject.AddComponent<BasicToggle>();
			BasicToggle basicToggle = gameObject.AddComponent<BasicToggle>();
			basicToggle.playerPrefs = "InvCheck";
		}
	}
}

BooBoo Building/BepInEx/plugins/squidypal-Discord_Rich_Presence/LethalCompanyPresence.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.Runtime.Versioning;
using System.Text;
using Discord;
using LethalPresence;
using MelonLoader;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Lethal Presence")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany(null)]
[assembly: AssemblyProduct("Lethal Presence")]
[assembly: AssemblyCopyright("Created by squidypal")]
[assembly: AssemblyTrademark(null)]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: MelonInfo(typeof(global::LethalPresence.LethalPresence), "Lethal Presence", "1.0.0", "squidypal", null)]
[assembly: MelonGame(null, null)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace LethalPresence
{
	public static class BuildInfo
	{
		public const string Name = "Lethal Presence";

		public const string Author = "squidypal";

		public const string Company = null;

		public const string Version = "1.0.0";

		public const string DownloadLink = null;
	}
	public class LethalPresence : MelonMod
	{
		public class EmbeddedResourceHelper
		{
			public static byte[] GetResourceBytes(string filename)
			{
				Assembly executingAssembly = Assembly.GetExecutingAssembly();
				string[] manifestResourceNames = executingAssembly.GetManifestResourceNames();
				foreach (string text in manifestResourceNames)
				{
					if (!text.Contains(filename))
					{
						continue;
					}
					using Stream stream = executingAssembly.GetManifestResourceStream(text);
					if (stream == null)
					{
						return null;
					}
					byte[] array = new byte[stream.Length];
					stream.Read(array, 0, array.Length);
					return array;
				}
				return null;
			}
		}

		public static class DllTools
		{
			[DllImport("kernel32.dll")]
			public static extern IntPtr LoadLibrary(string dllPath);
		}

		private static global::Discord.Discord _discord;

		private static ActivityManager _activityManager;

		private static long _clientId = 1174141549764935721L;

		private int quota = 0;

		public List<string> Moons;

		private bool inGame;

		public static Activity defaultActivity = new Activity
		{
			State = "Picking a launch mode",
			Details = "Ready to be a great great asset!",
			Assets = 
			{
				LargeImage = "lethalcompanylargeimage",
				LargeText = "Lethal Company",
				SmallImage = "faceicon",
				SmallText = "Lethal Company"
			}
		};

		public override void OnApplicationStart()
		{
			try
			{
				LoadEmbeddedDll();
				_discord = new global::Discord.Discord(_clientId, 0uL);
				_activityManager = _discord.GetActivityManager();
				_activityManager.RegisterSteam(1966720u);
				MelonLogger.Msg("RichPresence created.");
				SetActivity(defaultActivity);
			}
			catch (Exception ex)
			{
				MelonLogger.Error("Error in OnApplicationStart: " + ex.Message);
			}
		}

		public override void OnUpdate()
		{
			_discord?.RunCallbacks();
			if (inGame)
			{
				SetActivity(defaultActivity);
				if (TimeOfDay.Instance.profitQuota > TimeOfDay.Instance.quotaFulfilled)
				{
					defaultActivity.Details = "Not meeting quota " + TimeOfDay.Instance.quotaFulfilled + "/" + TimeOfDay.Instance.profitQuota;
				}
				else
				{
					defaultActivity.Details = "Meeting quota " + TimeOfDay.Instance.quotaFulfilled + "/" + TimeOfDay.Instance.profitQuota;
				}
				defaultActivity.State = TimeOfDay.Instance.daysUntilDeadline + " days and " + TimeOfDay.Instance.hoursUntilDeadline + " hours until deadline";
				string text = ((object)TimeOfDay.Instance.currentLevel).ToString();
				string text2 = text;
			}
		}

		public static void LoadEmbeddedDll()
		{
			byte[] resourceBytes = EmbeddedResourceHelper.GetResourceBytes("discord_game_sdk.dll");
			if (resourceBytes == null)
			{
				throw new Exception("Failed to find embedded resource: discord_game_sdk.dll");
			}
			string text = Path.Combine(Path.GetTempPath(), "discord_game_sdk.dll");
			File.WriteAllBytes(text, resourceBytes);
			IntPtr intPtr = DllTools.LoadLibrary(text);
			if (intPtr == IntPtr.Zero)
			{
				int lastWin32Error = Marshal.GetLastWin32Error();
				throw new Exception($"Failed to load discord_game_sdk.dll. Error Code: {lastWin32Error}");
			}
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			if (!(sceneName == "SampleSceneRelay"))
			{
				if (sceneName == "MainMenu")
				{
					defaultActivity.Details = "In the Menu";
					SetActivity(defaultActivity);
					inGame = false;
				}
			}
			else
			{
				inGame = true;
			}
		}

		public static void SetActivity(Activity activity)
		{
			_activityManager.UpdateActivity(activity, delegate(Result result)
			{
				if (result != 0)
				{
					MelonLogger.Msg("Failed: " + result);
				}
			});
		}
	}
}
namespace Discord
{
	public class ActivityManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ActivityJoinHandler(IntPtr ptr, [MarshalAs(UnmanagedType.LPStr)] string secret);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ActivitySpectateHandler(IntPtr ptr, [MarshalAs(UnmanagedType.LPStr)] string secret);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ActivityJoinRequestHandler(IntPtr ptr, ref User user);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ActivityInviteHandler(IntPtr ptr, ActivityActionType type, ref User user, ref Activity activity);

			internal ActivityJoinHandler OnActivityJoin;

			internal ActivitySpectateHandler OnActivitySpectate;

			internal ActivityJoinRequestHandler OnActivityJoinRequest;

			internal ActivityInviteHandler OnActivityInvite;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result RegisterCommandMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string command);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result RegisterSteamMethod(IntPtr methodsPtr, uint steamId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void UpdateActivityCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void UpdateActivityMethod(IntPtr methodsPtr, ref Activity activity, IntPtr callbackData, UpdateActivityCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ClearActivityCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ClearActivityMethod(IntPtr methodsPtr, IntPtr callbackData, ClearActivityCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SendRequestReplyCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SendRequestReplyMethod(IntPtr methodsPtr, long userId, ActivityJoinRequestReply reply, IntPtr callbackData, SendRequestReplyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SendInviteCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SendInviteMethod(IntPtr methodsPtr, long userId, ActivityActionType type, [MarshalAs(UnmanagedType.LPStr)] string content, IntPtr callbackData, SendInviteCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void AcceptInviteCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void AcceptInviteMethod(IntPtr methodsPtr, long userId, IntPtr callbackData, AcceptInviteCallback callback);

			internal RegisterCommandMethod RegisterCommand;

			internal RegisterSteamMethod RegisterSteam;

			internal UpdateActivityMethod UpdateActivity;

			internal ClearActivityMethod ClearActivity;

			internal SendRequestReplyMethod SendRequestReply;

			internal SendInviteMethod SendInvite;

			internal AcceptInviteMethod AcceptInvite;
		}

		public delegate void UpdateActivityHandler(Result result);

		public delegate void ClearActivityHandler(Result result);

		public delegate void SendRequestReplyHandler(Result result);

		public delegate void SendInviteHandler(Result result);

		public delegate void AcceptInviteHandler(Result result);

		public delegate void ActivityJoinHandler(string secret);

		public delegate void ActivitySpectateHandler(string secret);

		public delegate void ActivityJoinRequestHandler(ref User user);

		public delegate void ActivityInviteHandler(ActivityActionType type, ref User user, ref Activity activity);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event ActivityJoinHandler OnActivityJoin;

		public event ActivitySpectateHandler OnActivitySpectate;

		public event ActivityJoinRequestHandler OnActivityJoinRequest;

		public event ActivityInviteHandler OnActivityInvite;

		public void RegisterCommand()
		{
			RegisterCommand(null);
		}

		internal ActivityManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnActivityJoin = OnActivityJoinImpl;
			events.OnActivitySpectate = OnActivitySpectateImpl;
			events.OnActivityJoinRequest = OnActivityJoinRequestImpl;
			events.OnActivityInvite = OnActivityInviteImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public void RegisterCommand(string command)
		{
			Result result = Methods.RegisterCommand(MethodsPtr, command);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void RegisterSteam(uint steamId)
		{
			Result result = Methods.RegisterSteam(MethodsPtr, steamId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		[MonoPInvokeCallback]
		private static void UpdateActivityCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			UpdateActivityHandler updateActivityHandler = (UpdateActivityHandler)gCHandle.Target;
			gCHandle.Free();
			updateActivityHandler(result);
		}

		public void UpdateActivity(Activity activity, UpdateActivityHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.UpdateActivity(MethodsPtr, ref activity, GCHandle.ToIntPtr(value), UpdateActivityCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void ClearActivityCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			ClearActivityHandler clearActivityHandler = (ClearActivityHandler)gCHandle.Target;
			gCHandle.Free();
			clearActivityHandler(result);
		}

		public void ClearActivity(ClearActivityHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.ClearActivity(MethodsPtr, GCHandle.ToIntPtr(value), ClearActivityCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void SendRequestReplyCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SendRequestReplyHandler sendRequestReplyHandler = (SendRequestReplyHandler)gCHandle.Target;
			gCHandle.Free();
			sendRequestReplyHandler(result);
		}

		public void SendRequestReply(long userId, ActivityJoinRequestReply reply, SendRequestReplyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.SendRequestReply(MethodsPtr, userId, reply, GCHandle.ToIntPtr(value), SendRequestReplyCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void SendInviteCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SendInviteHandler sendInviteHandler = (SendInviteHandler)gCHandle.Target;
			gCHandle.Free();
			sendInviteHandler(result);
		}

		public void SendInvite(long userId, ActivityActionType type, string content, SendInviteHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.SendInvite(MethodsPtr, userId, type, content, GCHandle.ToIntPtr(value), SendInviteCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void AcceptInviteCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			AcceptInviteHandler acceptInviteHandler = (AcceptInviteHandler)gCHandle.Target;
			gCHandle.Free();
			acceptInviteHandler(result);
		}

		public void AcceptInvite(long userId, AcceptInviteHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.AcceptInvite(MethodsPtr, userId, GCHandle.ToIntPtr(value), AcceptInviteCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void OnActivityJoinImpl(IntPtr ptr, string secret)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.ActivityManagerInstance.OnActivityJoin != null)
			{
				discord.ActivityManagerInstance.OnActivityJoin(secret);
			}
		}

		[MonoPInvokeCallback]
		private static void OnActivitySpectateImpl(IntPtr ptr, string secret)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.ActivityManagerInstance.OnActivitySpectate != null)
			{
				discord.ActivityManagerInstance.OnActivitySpectate(secret);
			}
		}

		[MonoPInvokeCallback]
		private static void OnActivityJoinRequestImpl(IntPtr ptr, ref User user)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.ActivityManagerInstance.OnActivityJoinRequest != null)
			{
				discord.ActivityManagerInstance.OnActivityJoinRequest(ref user);
			}
		}

		[MonoPInvokeCallback]
		private static void OnActivityInviteImpl(IntPtr ptr, ActivityActionType type, ref User user, ref Activity activity)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.ActivityManagerInstance.OnActivityInvite != null)
			{
				discord.ActivityManagerInstance.OnActivityInvite(type, ref user, ref activity);
			}
		}
	}
	internal static class Constants
	{
		public const string DllName = "discord_game_sdk";
	}
	public enum Result
	{
		Ok,
		ServiceUnavailable,
		InvalidVersion,
		LockFailed,
		InternalError,
		InvalidPayload,
		InvalidCommand,
		InvalidPermissions,
		NotFetched,
		NotFound,
		Conflict,
		InvalidSecret,
		InvalidJoinSecret,
		NoEligibleActivity,
		InvalidInvite,
		NotAuthenticated,
		InvalidAccessToken,
		ApplicationMismatch,
		InvalidDataUrl,
		InvalidBase64,
		NotFiltered,
		LobbyFull,
		InvalidLobbySecret,
		InvalidFilename,
		InvalidFileSize,
		InvalidEntitlement,
		NotInstalled,
		NotRunning,
		InsufficientBuffer,
		PurchaseCanceled,
		InvalidGuild,
		InvalidEvent,
		InvalidChannel,
		InvalidOrigin,
		RateLimited,
		OAuth2Error,
		SelectChannelTimeout,
		GetGuildTimeout,
		SelectVoiceForceRequired,
		CaptureShortcutAlreadyListening,
		UnauthorizedForAchievement,
		InvalidGiftCode,
		PurchaseError,
		TransactionAborted
	}
	public enum CreateFlags
	{
		Default,
		NoRequireDiscord
	}
	public enum LogLevel
	{
		Error = 1,
		Warn,
		Info,
		Debug
	}
	public enum UserFlag
	{
		Partner = 2,
		HypeSquadEvents = 4,
		HypeSquadHouse1 = 0x40,
		HypeSquadHouse2 = 0x80,
		HypeSquadHouse3 = 0x100
	}
	public enum PremiumType
	{
		None,
		Tier1,
		Tier2
	}
	public enum ImageType
	{
		User
	}
	public enum ActivityType
	{
		Playing,
		Streaming,
		Listening,
		Watching
	}
	public enum ActivityActionType
	{
		Join = 1,
		Spectate
	}
	public enum ActivityJoinRequestReply
	{
		No,
		Yes,
		Ignore
	}
	public enum Status
	{
		Offline,
		Online,
		Idle,
		DoNotDisturb
	}
	public enum RelationshipType
	{
		None,
		Friend,
		Blocked,
		PendingIncoming,
		PendingOutgoing,
		Implicit
	}
	public enum LobbyType
	{
		Private = 1,
		Public
	}
	public enum LobbySearchComparison
	{
		LessThanOrEqual = -2,
		LessThan,
		Equal,
		GreaterThan,
		GreaterThanOrEqual,
		NotEqual
	}
	public enum LobbySearchCast
	{
		String = 1,
		Number
	}
	public enum LobbySearchDistance
	{
		Local,
		Default,
		Extended,
		Global
	}
	public enum EntitlementType
	{
		Purchase = 1,
		PremiumSubscription,
		DeveloperGift,
		TestModePurchase,
		FreePurchase,
		UserGift,
		PremiumPurchase
	}
	public enum SkuType
	{
		Application = 1,
		DLC,
		Consumable,
		Bundle
	}
	public enum InputModeType
	{
		VoiceActivity,
		PushToTalk
	}
	public struct User
	{
		public long Id;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
		public string Username;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
		public string Discriminator;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Avatar;

		public bool Bot;
	}
	public struct OAuth2Token
	{
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string AccessToken;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
		public string Scopes;

		public long Expires;
	}
	public struct ImageHandle
	{
		public ImageType Type;

		public long Id;

		public uint Size;

		public static ImageHandle User(long id)
		{
			return User(id, 128u);
		}

		public static ImageHandle User(long id, uint size)
		{
			ImageHandle result = default(ImageHandle);
			result.Type = ImageType.User;
			result.Id = id;
			result.Size = size;
			return result;
		}
	}
	public struct ImageDimensions
	{
		public uint Width;

		public uint Height;
	}
	public struct ActivityTimestamps
	{
		public long Start;

		public long End;
	}
	public struct ActivityAssets
	{
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string LargeImage;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string LargeText;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string SmallImage;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string SmallText;
	}
	public struct PartySize
	{
		public int CurrentSize;

		public int MaxSize;
	}
	public struct ActivityParty
	{
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Id;

		public PartySize Size;
	}
	public struct ActivitySecrets
	{
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Match;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Join;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Spectate;
	}
	public struct Activity
	{
		public ActivityType Type;

		public long ApplicationId;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Name;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string State;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Details;

		public ActivityTimestamps Timestamps;

		public ActivityAssets Assets;

		public ActivityParty Party;

		public ActivitySecrets Secrets;

		public bool Instance;
	}
	public struct Presence
	{
		public Status Status;

		public Activity Activity;
	}
	public struct Relationship
	{
		public RelationshipType Type;

		public User User;

		public Presence Presence;
	}
	public struct Lobby
	{
		public long Id;

		public LobbyType Type;

		public long OwnerId;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string Secret;

		public uint Capacity;

		public bool Locked;
	}
	public struct FileStat
	{
		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
		public string Filename;

		public ulong Size;

		public ulong LastModified;
	}
	public struct Entitlement
	{
		public long Id;

		public EntitlementType Type;

		public long SkuId;
	}
	public struct SkuPrice
	{
		public uint Amount;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
		public string Currency;
	}
	public struct Sku
	{
		public long Id;

		public SkuType Type;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
		public string Name;

		public SkuPrice Price;
	}
	public struct InputMode
	{
		public InputModeType Type;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
		public string Shortcut;
	}
	public struct UserAchievement
	{
		public long UserId;

		public long AchievementId;

		public byte PercentComplete;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
		public string UnlockedAt;
	}
	public struct LobbyTransaction
	{
		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result SetTypeMethod(IntPtr methodsPtr, LobbyType type);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result SetOwnerMethod(IntPtr methodsPtr, long ownerId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result SetCapacityMethod(IntPtr methodsPtr, uint capacity);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result SetMetadataMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key, [MarshalAs(UnmanagedType.LPStr)] string value);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result DeleteMetadataMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result SetLockedMethod(IntPtr methodsPtr, bool locked);

			internal SetTypeMethod SetType;

			internal SetOwnerMethod SetOwner;

			internal SetCapacityMethod SetCapacity;

			internal SetMetadataMethod SetMetadata;

			internal DeleteMetadataMethod DeleteMetadata;

			internal SetLockedMethod SetLocked;
		}

		internal IntPtr MethodsPtr;

		internal object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public void SetType(LobbyType type)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetType(MethodsPtr, type);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void SetOwner(long ownerId)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetOwner(MethodsPtr, ownerId);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void SetCapacity(uint capacity)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetCapacity(MethodsPtr, capacity);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void SetMetadata(string key, string value)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetMetadata(MethodsPtr, key, value);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void DeleteMetadata(string key)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.DeleteMetadata(MethodsPtr, key);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void SetLocked(bool locked)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetLocked(MethodsPtr, locked);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}
	}
	public struct LobbyMemberTransaction
	{
		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result SetMetadataMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key, [MarshalAs(UnmanagedType.LPStr)] string value);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result DeleteMetadataMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key);

			internal SetMetadataMethod SetMetadata;

			internal DeleteMetadataMethod DeleteMetadata;
		}

		internal IntPtr MethodsPtr;

		internal object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public void SetMetadata(string key, string value)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.SetMetadata(MethodsPtr, key, value);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void DeleteMetadata(string key)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.DeleteMetadata(MethodsPtr, key);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}
	}
	public struct LobbySearchQuery
	{
		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result FilterMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key, LobbySearchComparison comparison, LobbySearchCast cast, [MarshalAs(UnmanagedType.LPStr)] string value);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result SortMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string key, LobbySearchCast cast, [MarshalAs(UnmanagedType.LPStr)] string value);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result LimitMethod(IntPtr methodsPtr, uint limit);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result DistanceMethod(IntPtr methodsPtr, LobbySearchDistance distance);

			internal FilterMethod Filter;

			internal SortMethod Sort;

			internal LimitMethod Limit;

			internal DistanceMethod Distance;
		}

		internal IntPtr MethodsPtr;

		internal object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public void Filter(string key, LobbySearchComparison comparison, LobbySearchCast cast, string value)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.Filter(MethodsPtr, key, comparison, cast, value);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void Sort(string key, LobbySearchCast cast, string value)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.Sort(MethodsPtr, key, cast, value);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void Limit(uint limit)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.Limit(MethodsPtr, limit);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}

		public void Distance(LobbySearchDistance distance)
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Result result = Methods.Distance(MethodsPtr, distance);
				if (result != 0)
				{
					throw new ResultException(result);
				}
			}
		}
	}
	public class ResultException : Exception
	{
		public readonly Result Result;

		public ResultException(Result result)
			: base(result.ToString())
		{
		}
	}
	public class Discord : IDisposable
	{
		internal struct FFIEvents
		{
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void DestroyHandler(IntPtr MethodsPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result RunCallbacksMethod(IntPtr methodsPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SetLogHookCallback(IntPtr ptr, LogLevel level, [MarshalAs(UnmanagedType.LPStr)] string message);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SetLogHookMethod(IntPtr methodsPtr, LogLevel minLevel, IntPtr callbackData, SetLogHookCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetApplicationManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetUserManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetImageManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetActivityManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetRelationshipManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetLobbyManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetNetworkManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetOverlayManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetStorageManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetStoreManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetVoiceManagerMethod(IntPtr discordPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate IntPtr GetAchievementManagerMethod(IntPtr discordPtr);

			internal DestroyHandler Destroy;

			internal RunCallbacksMethod RunCallbacks;

			internal SetLogHookMethod SetLogHook;

			internal GetApplicationManagerMethod GetApplicationManager;

			internal GetUserManagerMethod GetUserManager;

			internal GetImageManagerMethod GetImageManager;

			internal GetActivityManagerMethod GetActivityManager;

			internal GetRelationshipManagerMethod GetRelationshipManager;

			internal GetLobbyManagerMethod GetLobbyManager;

			internal GetNetworkManagerMethod GetNetworkManager;

			internal GetOverlayManagerMethod GetOverlayManager;

			internal GetStorageManagerMethod GetStorageManager;

			internal GetStoreManagerMethod GetStoreManager;

			internal GetVoiceManagerMethod GetVoiceManager;

			internal GetAchievementManagerMethod GetAchievementManager;
		}

		internal struct FFICreateParams
		{
			internal long ClientId;

			internal ulong Flags;

			internal IntPtr Events;

			internal IntPtr EventData;

			internal IntPtr ApplicationEvents;

			internal uint ApplicationVersion;

			internal IntPtr UserEvents;

			internal uint UserVersion;

			internal IntPtr ImageEvents;

			internal uint ImageVersion;

			internal IntPtr ActivityEvents;

			internal uint ActivityVersion;

			internal IntPtr RelationshipEvents;

			internal uint RelationshipVersion;

			internal IntPtr LobbyEvents;

			internal uint LobbyVersion;

			internal IntPtr NetworkEvents;

			internal uint NetworkVersion;

			internal IntPtr OverlayEvents;

			internal uint OverlayVersion;

			internal IntPtr StorageEvents;

			internal uint StorageVersion;

			internal IntPtr StoreEvents;

			internal uint StoreVersion;

			internal IntPtr VoiceEvents;

			internal uint VoiceVersion;

			internal IntPtr AchievementEvents;

			internal uint AchievementVersion;
		}

		public delegate void SetLogHookHandler(LogLevel level, string message);

		private GCHandle SelfHandle;

		private IntPtr EventsPtr;

		private FFIEvents Events;

		private IntPtr ApplicationEventsPtr;

		private ApplicationManager.FFIEvents ApplicationEvents;

		internal ApplicationManager ApplicationManagerInstance;

		private IntPtr UserEventsPtr;

		private UserManager.FFIEvents UserEvents;

		internal UserManager UserManagerInstance;

		private IntPtr ImageEventsPtr;

		private ImageManager.FFIEvents ImageEvents;

		internal ImageManager ImageManagerInstance;

		private IntPtr ActivityEventsPtr;

		private ActivityManager.FFIEvents ActivityEvents;

		internal ActivityManager ActivityManagerInstance;

		private IntPtr RelationshipEventsPtr;

		private RelationshipManager.FFIEvents RelationshipEvents;

		internal RelationshipManager RelationshipManagerInstance;

		private IntPtr LobbyEventsPtr;

		private LobbyManager.FFIEvents LobbyEvents;

		internal LobbyManager LobbyManagerInstance;

		private IntPtr NetworkEventsPtr;

		private NetworkManager.FFIEvents NetworkEvents;

		internal NetworkManager NetworkManagerInstance;

		private IntPtr OverlayEventsPtr;

		private OverlayManager.FFIEvents OverlayEvents;

		internal OverlayManager OverlayManagerInstance;

		private IntPtr StorageEventsPtr;

		private StorageManager.FFIEvents StorageEvents;

		internal StorageManager StorageManagerInstance;

		private IntPtr StoreEventsPtr;

		private StoreManager.FFIEvents StoreEvents;

		internal StoreManager StoreManagerInstance;

		private IntPtr VoiceEventsPtr;

		private VoiceManager.FFIEvents VoiceEvents;

		internal VoiceManager VoiceManagerInstance;

		private IntPtr AchievementEventsPtr;

		private AchievementManager.FFIEvents AchievementEvents;

		internal AchievementManager AchievementManagerInstance;

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private GCHandle? setLogHook;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		[DllImport("discord_game_sdk", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
		private static extern Result DiscordCreate(uint version, ref FFICreateParams createParams, out IntPtr manager);

		public Discord(long clientId, ulong flags)
		{
			FFICreateParams createParams = default(FFICreateParams);
			createParams.ClientId = clientId;
			createParams.Flags = flags;
			Events = default(FFIEvents);
			EventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(Events));
			createParams.Events = EventsPtr;
			SelfHandle = GCHandle.Alloc(this);
			createParams.EventData = GCHandle.ToIntPtr(SelfHandle);
			ApplicationEvents = default(ApplicationManager.FFIEvents);
			ApplicationEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ApplicationEvents));
			createParams.ApplicationEvents = ApplicationEventsPtr;
			createParams.ApplicationVersion = 1u;
			UserEvents = default(UserManager.FFIEvents);
			UserEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(UserEvents));
			createParams.UserEvents = UserEventsPtr;
			createParams.UserVersion = 1u;
			ImageEvents = default(ImageManager.FFIEvents);
			ImageEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ImageEvents));
			createParams.ImageEvents = ImageEventsPtr;
			createParams.ImageVersion = 1u;
			ActivityEvents = default(ActivityManager.FFIEvents);
			ActivityEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ActivityEvents));
			createParams.ActivityEvents = ActivityEventsPtr;
			createParams.ActivityVersion = 1u;
			RelationshipEvents = default(RelationshipManager.FFIEvents);
			RelationshipEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(RelationshipEvents));
			createParams.RelationshipEvents = RelationshipEventsPtr;
			createParams.RelationshipVersion = 1u;
			LobbyEvents = default(LobbyManager.FFIEvents);
			LobbyEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(LobbyEvents));
			createParams.LobbyEvents = LobbyEventsPtr;
			createParams.LobbyVersion = 1u;
			NetworkEvents = default(NetworkManager.FFIEvents);
			NetworkEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(NetworkEvents));
			createParams.NetworkEvents = NetworkEventsPtr;
			createParams.NetworkVersion = 1u;
			OverlayEvents = default(OverlayManager.FFIEvents);
			OverlayEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(OverlayEvents));
			createParams.OverlayEvents = OverlayEventsPtr;
			createParams.OverlayVersion = 1u;
			StorageEvents = default(StorageManager.FFIEvents);
			StorageEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(StorageEvents));
			createParams.StorageEvents = StorageEventsPtr;
			createParams.StorageVersion = 1u;
			StoreEvents = default(StoreManager.FFIEvents);
			StoreEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(StoreEvents));
			createParams.StoreEvents = StoreEventsPtr;
			createParams.StoreVersion = 1u;
			VoiceEvents = default(VoiceManager.FFIEvents);
			VoiceEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VoiceEvents));
			createParams.VoiceEvents = VoiceEventsPtr;
			createParams.VoiceVersion = 1u;
			AchievementEvents = default(AchievementManager.FFIEvents);
			AchievementEventsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(AchievementEvents));
			createParams.AchievementEvents = AchievementEventsPtr;
			createParams.AchievementVersion = 1u;
			InitEvents(EventsPtr, ref Events);
			Result result = DiscordCreate(2u, ref createParams, out MethodsPtr);
			if (result != 0)
			{
				Dispose();
				throw new ResultException(result);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public void Dispose()
		{
			if (MethodsPtr != IntPtr.Zero)
			{
				Methods.Destroy(MethodsPtr);
			}
			SelfHandle.Free();
			Marshal.FreeHGlobal(EventsPtr);
			Marshal.FreeHGlobal(ApplicationEventsPtr);
			Marshal.FreeHGlobal(UserEventsPtr);
			Marshal.FreeHGlobal(ImageEventsPtr);
			Marshal.FreeHGlobal(ActivityEventsPtr);
			Marshal.FreeHGlobal(RelationshipEventsPtr);
			Marshal.FreeHGlobal(LobbyEventsPtr);
			Marshal.FreeHGlobal(NetworkEventsPtr);
			Marshal.FreeHGlobal(OverlayEventsPtr);
			Marshal.FreeHGlobal(StorageEventsPtr);
			Marshal.FreeHGlobal(StoreEventsPtr);
			Marshal.FreeHGlobal(VoiceEventsPtr);
			Marshal.FreeHGlobal(AchievementEventsPtr);
			if (setLogHook.HasValue)
			{
				setLogHook.Value.Free();
			}
		}

		public void RunCallbacks()
		{
			Result result = Methods.RunCallbacks(MethodsPtr);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		[MonoPInvokeCallback]
		private static void SetLogHookCallbackImpl(IntPtr ptr, LogLevel level, string message)
		{
			SetLogHookHandler setLogHookHandler = (SetLogHookHandler)GCHandle.FromIntPtr(ptr).Target;
			setLogHookHandler(level, message);
		}

		public void SetLogHook(LogLevel minLevel, SetLogHookHandler callback)
		{
			if (setLogHook.HasValue)
			{
				setLogHook.Value.Free();
			}
			setLogHook = GCHandle.Alloc(callback);
			Methods.SetLogHook(MethodsPtr, minLevel, GCHandle.ToIntPtr(setLogHook.Value), SetLogHookCallbackImpl);
		}

		public ApplicationManager GetApplicationManager()
		{
			if (ApplicationManagerInstance == null)
			{
				ApplicationManagerInstance = new ApplicationManager(Methods.GetApplicationManager(MethodsPtr), ApplicationEventsPtr, ref ApplicationEvents);
			}
			return ApplicationManagerInstance;
		}

		public UserManager GetUserManager()
		{
			if (UserManagerInstance == null)
			{
				UserManagerInstance = new UserManager(Methods.GetUserManager(MethodsPtr), UserEventsPtr, ref UserEvents);
			}
			return UserManagerInstance;
		}

		public ImageManager GetImageManager()
		{
			if (ImageManagerInstance == null)
			{
				ImageManagerInstance = new ImageManager(Methods.GetImageManager(MethodsPtr), ImageEventsPtr, ref ImageEvents);
			}
			return ImageManagerInstance;
		}

		public ActivityManager GetActivityManager()
		{
			if (ActivityManagerInstance == null)
			{
				ActivityManagerInstance = new ActivityManager(Methods.GetActivityManager(MethodsPtr), ActivityEventsPtr, ref ActivityEvents);
			}
			return ActivityManagerInstance;
		}

		public RelationshipManager GetRelationshipManager()
		{
			if (RelationshipManagerInstance == null)
			{
				RelationshipManagerInstance = new RelationshipManager(Methods.GetRelationshipManager(MethodsPtr), RelationshipEventsPtr, ref RelationshipEvents);
			}
			return RelationshipManagerInstance;
		}

		public LobbyManager GetLobbyManager()
		{
			if (LobbyManagerInstance == null)
			{
				LobbyManagerInstance = new LobbyManager(Methods.GetLobbyManager(MethodsPtr), LobbyEventsPtr, ref LobbyEvents);
			}
			return LobbyManagerInstance;
		}

		public NetworkManager GetNetworkManager()
		{
			if (NetworkManagerInstance == null)
			{
				NetworkManagerInstance = new NetworkManager(Methods.GetNetworkManager(MethodsPtr), NetworkEventsPtr, ref NetworkEvents);
			}
			return NetworkManagerInstance;
		}

		public OverlayManager GetOverlayManager()
		{
			if (OverlayManagerInstance == null)
			{
				OverlayManagerInstance = new OverlayManager(Methods.GetOverlayManager(MethodsPtr), OverlayEventsPtr, ref OverlayEvents);
			}
			return OverlayManagerInstance;
		}

		public StorageManager GetStorageManager()
		{
			if (StorageManagerInstance == null)
			{
				StorageManagerInstance = new StorageManager(Methods.GetStorageManager(MethodsPtr), StorageEventsPtr, ref StorageEvents);
			}
			return StorageManagerInstance;
		}

		public StoreManager GetStoreManager()
		{
			if (StoreManagerInstance == null)
			{
				StoreManagerInstance = new StoreManager(Methods.GetStoreManager(MethodsPtr), StoreEventsPtr, ref StoreEvents);
			}
			return StoreManagerInstance;
		}

		public VoiceManager GetVoiceManager()
		{
			if (VoiceManagerInstance == null)
			{
				VoiceManagerInstance = new VoiceManager(Methods.GetVoiceManager(MethodsPtr), VoiceEventsPtr, ref VoiceEvents);
			}
			return VoiceManagerInstance;
		}

		public AchievementManager GetAchievementManager()
		{
			if (AchievementManagerInstance == null)
			{
				AchievementManagerInstance = new AchievementManager(Methods.GetAchievementManager(MethodsPtr), AchievementEventsPtr, ref AchievementEvents);
			}
			return AchievementManagerInstance;
		}
	}
	internal class MonoPInvokeCallbackAttribute : Attribute
	{
	}
	public class ApplicationManager
	{
		internal struct FFIEvents
		{
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ValidateOrExitCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ValidateOrExitMethod(IntPtr methodsPtr, IntPtr callbackData, ValidateOrExitCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void GetCurrentLocaleMethod(IntPtr methodsPtr, StringBuilder locale);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void GetCurrentBranchMethod(IntPtr methodsPtr, StringBuilder branch);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void GetOAuth2TokenCallback(IntPtr ptr, Result result, ref OAuth2Token oauth2Token);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void GetOAuth2TokenMethod(IntPtr methodsPtr, IntPtr callbackData, GetOAuth2TokenCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void GetTicketCallback(IntPtr ptr, Result result, [MarshalAs(UnmanagedType.LPStr)] ref string data);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void GetTicketMethod(IntPtr methodsPtr, IntPtr callbackData, GetTicketCallback callback);

			internal ValidateOrExitMethod ValidateOrExit;

			internal GetCurrentLocaleMethod GetCurrentLocale;

			internal GetCurrentBranchMethod GetCurrentBranch;

			internal GetOAuth2TokenMethod GetOAuth2Token;

			internal GetTicketMethod GetTicket;
		}

		public delegate void ValidateOrExitHandler(Result result);

		public delegate void GetOAuth2TokenHandler(Result result, ref OAuth2Token oauth2Token);

		public delegate void GetTicketHandler(Result result, ref string data);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		internal ApplicationManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		[MonoPInvokeCallback]
		private static void ValidateOrExitCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			ValidateOrExitHandler validateOrExitHandler = (ValidateOrExitHandler)gCHandle.Target;
			gCHandle.Free();
			validateOrExitHandler(result);
		}

		public void ValidateOrExit(ValidateOrExitHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.ValidateOrExit(MethodsPtr, GCHandle.ToIntPtr(value), ValidateOrExitCallbackImpl);
		}

		public string GetCurrentLocale()
		{
			StringBuilder stringBuilder = new StringBuilder(128);
			Methods.GetCurrentLocale(MethodsPtr, stringBuilder);
			return stringBuilder.ToString();
		}

		public string GetCurrentBranch()
		{
			StringBuilder stringBuilder = new StringBuilder(4096);
			Methods.GetCurrentBranch(MethodsPtr, stringBuilder);
			return stringBuilder.ToString();
		}

		[MonoPInvokeCallback]
		private static void GetOAuth2TokenCallbackImpl(IntPtr ptr, Result result, ref OAuth2Token oauth2Token)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			GetOAuth2TokenHandler getOAuth2TokenHandler = (GetOAuth2TokenHandler)gCHandle.Target;
			gCHandle.Free();
			getOAuth2TokenHandler(result, ref oauth2Token);
		}

		public void GetOAuth2Token(GetOAuth2TokenHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.GetOAuth2Token(MethodsPtr, GCHandle.ToIntPtr(value), GetOAuth2TokenCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void GetTicketCallbackImpl(IntPtr ptr, Result result, ref string data)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			GetTicketHandler getTicketHandler = (GetTicketHandler)gCHandle.Target;
			gCHandle.Free();
			getTicketHandler(result, ref data);
		}

		public void GetTicket(GetTicketHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.GetTicket(MethodsPtr, GCHandle.ToIntPtr(value), GetTicketCallbackImpl);
		}
	}
	public class UserManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void CurrentUserUpdateHandler(IntPtr ptr);

			internal CurrentUserUpdateHandler OnCurrentUserUpdate;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetCurrentUserMethod(IntPtr methodsPtr, ref User currentUser);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void GetUserCallback(IntPtr ptr, Result result, ref User user);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void GetUserMethod(IntPtr methodsPtr, long userId, IntPtr callbackData, GetUserCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetCurrentUserPremiumTypeMethod(IntPtr methodsPtr, ref PremiumType premiumType);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result CurrentUserHasFlagMethod(IntPtr methodsPtr, UserFlag flag, ref bool hasFlag);

			internal GetCurrentUserMethod GetCurrentUser;

			internal GetUserMethod GetUser;

			internal GetCurrentUserPremiumTypeMethod GetCurrentUserPremiumType;

			internal CurrentUserHasFlagMethod CurrentUserHasFlag;
		}

		public delegate void GetUserHandler(Result result, ref User user);

		public delegate void CurrentUserUpdateHandler();

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event CurrentUserUpdateHandler OnCurrentUserUpdate;

		internal UserManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnCurrentUserUpdate = OnCurrentUserUpdateImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public User GetCurrentUser()
		{
			User currentUser = default(User);
			Result result = Methods.GetCurrentUser(MethodsPtr, ref currentUser);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return currentUser;
		}

		[MonoPInvokeCallback]
		private static void GetUserCallbackImpl(IntPtr ptr, Result result, ref User user)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			GetUserHandler getUserHandler = (GetUserHandler)gCHandle.Target;
			gCHandle.Free();
			getUserHandler(result, ref user);
		}

		public void GetUser(long userId, GetUserHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.GetUser(MethodsPtr, userId, GCHandle.ToIntPtr(value), GetUserCallbackImpl);
		}

		public PremiumType GetCurrentUserPremiumType()
		{
			PremiumType premiumType = PremiumType.None;
			Result result = Methods.GetCurrentUserPremiumType(MethodsPtr, ref premiumType);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return premiumType;
		}

		public bool CurrentUserHasFlag(UserFlag flag)
		{
			bool hasFlag = false;
			Result result = Methods.CurrentUserHasFlag(MethodsPtr, flag, ref hasFlag);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return hasFlag;
		}

		[MonoPInvokeCallback]
		private static void OnCurrentUserUpdateImpl(IntPtr ptr)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.UserManagerInstance.OnCurrentUserUpdate != null)
			{
				discord.UserManagerInstance.OnCurrentUserUpdate();
			}
		}
	}
	public class ImageManager
	{
		internal struct FFIEvents
		{
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void FetchCallback(IntPtr ptr, Result result, ImageHandle handleResult);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void FetchMethod(IntPtr methodsPtr, ImageHandle handle, bool refresh, IntPtr callbackData, FetchCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetDimensionsMethod(IntPtr methodsPtr, ImageHandle handle, ref ImageDimensions dimensions);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetDataMethod(IntPtr methodsPtr, ImageHandle handle, byte[] data, int dataLen);

			internal FetchMethod Fetch;

			internal GetDimensionsMethod GetDimensions;

			internal GetDataMethod GetData;
		}

		public delegate void FetchHandler(Result result, ImageHandle handleResult);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		internal ImageManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		[MonoPInvokeCallback]
		private static void FetchCallbackImpl(IntPtr ptr, Result result, ImageHandle handleResult)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			FetchHandler fetchHandler = (FetchHandler)gCHandle.Target;
			gCHandle.Free();
			fetchHandler(result, handleResult);
		}

		public void Fetch(ImageHandle handle, bool refresh, FetchHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.Fetch(MethodsPtr, handle, refresh, GCHandle.ToIntPtr(value), FetchCallbackImpl);
		}

		public ImageDimensions GetDimensions(ImageHandle handle)
		{
			ImageDimensions dimensions = default(ImageDimensions);
			Result result = Methods.GetDimensions(MethodsPtr, handle, ref dimensions);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return dimensions;
		}

		public void GetData(ImageHandle handle, byte[] data)
		{
			Result result = Methods.GetData(MethodsPtr, handle, data, data.Length);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void Fetch(ImageHandle handle, FetchHandler callback)
		{
			Fetch(handle, refresh: false, callback);
		}

		public byte[] GetData(ImageHandle handle)
		{
			ImageDimensions dimensions = GetDimensions(handle);
			byte[] array = new byte[dimensions.Width * dimensions.Height * 4];
			GetData(handle, array);
			return array;
		}
	}
	public class RelationshipManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void RefreshHandler(IntPtr ptr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void RelationshipUpdateHandler(IntPtr ptr, ref Relationship relationship);

			internal RefreshHandler OnRefresh;

			internal RelationshipUpdateHandler OnRelationshipUpdate;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate bool FilterCallback(IntPtr ptr, ref Relationship relationship);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void FilterMethod(IntPtr methodsPtr, IntPtr callbackData, FilterCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result CountMethod(IntPtr methodsPtr, ref int count);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetMethod(IntPtr methodsPtr, long userId, ref Relationship relationship);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetAtMethod(IntPtr methodsPtr, uint index, ref Relationship relationship);

			internal FilterMethod Filter;

			internal CountMethod Count;

			internal GetMethod Get;

			internal GetAtMethod GetAt;
		}

		public delegate bool FilterHandler(ref Relationship relationship);

		public delegate void RefreshHandler();

		public delegate void RelationshipUpdateHandler(ref Relationship relationship);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event RefreshHandler OnRefresh;

		public event RelationshipUpdateHandler OnRelationshipUpdate;

		internal RelationshipManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnRefresh = OnRefreshImpl;
			events.OnRelationshipUpdate = OnRelationshipUpdateImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		[MonoPInvokeCallback]
		private static bool FilterCallbackImpl(IntPtr ptr, ref Relationship relationship)
		{
			FilterHandler filterHandler = (FilterHandler)GCHandle.FromIntPtr(ptr).Target;
			return filterHandler(ref relationship);
		}

		public void Filter(FilterHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.Filter(MethodsPtr, GCHandle.ToIntPtr(value), FilterCallbackImpl);
			value.Free();
		}

		public int Count()
		{
			int count = 0;
			Result result = Methods.Count(MethodsPtr, ref count);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return count;
		}

		public Relationship Get(long userId)
		{
			Relationship relationship = default(Relationship);
			Result result = Methods.Get(MethodsPtr, userId, ref relationship);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return relationship;
		}

		public Relationship GetAt(uint index)
		{
			Relationship relationship = default(Relationship);
			Result result = Methods.GetAt(MethodsPtr, index, ref relationship);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return relationship;
		}

		[MonoPInvokeCallback]
		private static void OnRefreshImpl(IntPtr ptr)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.RelationshipManagerInstance.OnRefresh != null)
			{
				discord.RelationshipManagerInstance.OnRefresh();
			}
		}

		[MonoPInvokeCallback]
		private static void OnRelationshipUpdateImpl(IntPtr ptr, ref Relationship relationship)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.RelationshipManagerInstance.OnRelationshipUpdate != null)
			{
				discord.RelationshipManagerInstance.OnRelationshipUpdate(ref relationship);
			}
		}
	}
	public class LobbyManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void LobbyUpdateHandler(IntPtr ptr, long lobbyId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void LobbyDeleteHandler(IntPtr ptr, long lobbyId, uint reason);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void MemberConnectHandler(IntPtr ptr, long lobbyId, long userId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void MemberUpdateHandler(IntPtr ptr, long lobbyId, long userId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void MemberDisconnectHandler(IntPtr ptr, long lobbyId, long userId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void LobbyMessageHandler(IntPtr ptr, long lobbyId, long userId, IntPtr dataPtr, int dataLen);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SpeakingHandler(IntPtr ptr, long lobbyId, long userId, bool speaking);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void NetworkMessageHandler(IntPtr ptr, long lobbyId, long userId, byte channelId, IntPtr dataPtr, int dataLen);

			internal LobbyUpdateHandler OnLobbyUpdate;

			internal LobbyDeleteHandler OnLobbyDelete;

			internal MemberConnectHandler OnMemberConnect;

			internal MemberUpdateHandler OnMemberUpdate;

			internal MemberDisconnectHandler OnMemberDisconnect;

			internal LobbyMessageHandler OnLobbyMessage;

			internal SpeakingHandler OnSpeaking;

			internal NetworkMessageHandler OnNetworkMessage;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetLobbyCreateTransactionMethod(IntPtr methodsPtr, ref IntPtr transaction);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetLobbyUpdateTransactionMethod(IntPtr methodsPtr, long lobbyId, ref IntPtr transaction);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetMemberUpdateTransactionMethod(IntPtr methodsPtr, long lobbyId, long userId, ref IntPtr transaction);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void CreateLobbyCallback(IntPtr ptr, Result result, ref Lobby lobby);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void CreateLobbyMethod(IntPtr methodsPtr, IntPtr transaction, IntPtr callbackData, CreateLobbyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void UpdateLobbyCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void UpdateLobbyMethod(IntPtr methodsPtr, long lobbyId, IntPtr transaction, IntPtr callbackData, UpdateLobbyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void DeleteLobbyCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void DeleteLobbyMethod(IntPtr methodsPtr, long lobbyId, IntPtr callbackData, DeleteLobbyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ConnectLobbyCallback(IntPtr ptr, Result result, ref Lobby lobby);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ConnectLobbyMethod(IntPtr methodsPtr, long lobbyId, [MarshalAs(UnmanagedType.LPStr)] string secret, IntPtr callbackData, ConnectLobbyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ConnectLobbyWithActivitySecretCallback(IntPtr ptr, Result result, ref Lobby lobby);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ConnectLobbyWithActivitySecretMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string activitySecret, IntPtr callbackData, ConnectLobbyWithActivitySecretCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void DisconnectLobbyCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void DisconnectLobbyMethod(IntPtr methodsPtr, long lobbyId, IntPtr callbackData, DisconnectLobbyCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetLobbyMethod(IntPtr methodsPtr, long lobbyId, ref Lobby lobby);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetLobbyActivitySecretMethod(IntPtr methodsPtr, long lobbyId, StringBuilder secret);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetLobbyMetadataValueMethod(IntPtr methodsPtr, long lobbyId, [MarshalAs(UnmanagedType.LPStr)] string key, StringBuilder value);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetLobbyMetadataKeyMethod(IntPtr methodsPtr, long lobbyId, int index, StringBuilder key);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result LobbyMetadataCountMethod(IntPtr methodsPtr, long lobbyId, ref int count);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result MemberCountMethod(IntPtr methodsPtr, long lobbyId, ref int count);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetMemberUserIdMethod(IntPtr methodsPtr, long lobbyId, int index, ref long userId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetMemberUserMethod(IntPtr methodsPtr, long lobbyId, long userId, ref User user);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetMemberMetadataValueMethod(IntPtr methodsPtr, long lobbyId, long userId, [MarshalAs(UnmanagedType.LPStr)] string key, StringBuilder value);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetMemberMetadataKeyMethod(IntPtr methodsPtr, long lobbyId, long userId, int index, StringBuilder key);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result MemberMetadataCountMethod(IntPtr methodsPtr, long lobbyId, long userId, ref int count);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void UpdateMemberCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void UpdateMemberMethod(IntPtr methodsPtr, long lobbyId, long userId, IntPtr transaction, IntPtr callbackData, UpdateMemberCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SendLobbyMessageCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SendLobbyMessageMethod(IntPtr methodsPtr, long lobbyId, byte[] data, int dataLen, IntPtr callbackData, SendLobbyMessageCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetSearchQueryMethod(IntPtr methodsPtr, ref IntPtr query);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SearchCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SearchMethod(IntPtr methodsPtr, IntPtr query, IntPtr callbackData, SearchCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void LobbyCountMethod(IntPtr methodsPtr, ref int count);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetLobbyIdMethod(IntPtr methodsPtr, int index, ref long lobbyId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ConnectVoiceCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ConnectVoiceMethod(IntPtr methodsPtr, long lobbyId, IntPtr callbackData, ConnectVoiceCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void DisconnectVoiceCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void DisconnectVoiceMethod(IntPtr methodsPtr, long lobbyId, IntPtr callbackData, DisconnectVoiceCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result ConnectNetworkMethod(IntPtr methodsPtr, long lobbyId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result DisconnectNetworkMethod(IntPtr methodsPtr, long lobbyId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result FlushNetworkMethod(IntPtr methodsPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result OpenNetworkChannelMethod(IntPtr methodsPtr, long lobbyId, byte channelId, bool reliable);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result SendNetworkMessageMethod(IntPtr methodsPtr, long lobbyId, long userId, byte channelId, byte[] data, int dataLen);

			internal GetLobbyCreateTransactionMethod GetLobbyCreateTransaction;

			internal GetLobbyUpdateTransactionMethod GetLobbyUpdateTransaction;

			internal GetMemberUpdateTransactionMethod GetMemberUpdateTransaction;

			internal CreateLobbyMethod CreateLobby;

			internal UpdateLobbyMethod UpdateLobby;

			internal DeleteLobbyMethod DeleteLobby;

			internal ConnectLobbyMethod ConnectLobby;

			internal ConnectLobbyWithActivitySecretMethod ConnectLobbyWithActivitySecret;

			internal DisconnectLobbyMethod DisconnectLobby;

			internal GetLobbyMethod GetLobby;

			internal GetLobbyActivitySecretMethod GetLobbyActivitySecret;

			internal GetLobbyMetadataValueMethod GetLobbyMetadataValue;

			internal GetLobbyMetadataKeyMethod GetLobbyMetadataKey;

			internal LobbyMetadataCountMethod LobbyMetadataCount;

			internal MemberCountMethod MemberCount;

			internal GetMemberUserIdMethod GetMemberUserId;

			internal GetMemberUserMethod GetMemberUser;

			internal GetMemberMetadataValueMethod GetMemberMetadataValue;

			internal GetMemberMetadataKeyMethod GetMemberMetadataKey;

			internal MemberMetadataCountMethod MemberMetadataCount;

			internal UpdateMemberMethod UpdateMember;

			internal SendLobbyMessageMethod SendLobbyMessage;

			internal GetSearchQueryMethod GetSearchQuery;

			internal SearchMethod Search;

			internal LobbyCountMethod LobbyCount;

			internal GetLobbyIdMethod GetLobbyId;

			internal ConnectVoiceMethod ConnectVoice;

			internal DisconnectVoiceMethod DisconnectVoice;

			internal ConnectNetworkMethod ConnectNetwork;

			internal DisconnectNetworkMethod DisconnectNetwork;

			internal FlushNetworkMethod FlushNetwork;

			internal OpenNetworkChannelMethod OpenNetworkChannel;

			internal SendNetworkMessageMethod SendNetworkMessage;
		}

		public delegate void CreateLobbyHandler(Result result, ref Lobby lobby);

		public delegate void UpdateLobbyHandler(Result result);

		public delegate void DeleteLobbyHandler(Result result);

		public delegate void ConnectLobbyHandler(Result result, ref Lobby lobby);

		public delegate void ConnectLobbyWithActivitySecretHandler(Result result, ref Lobby lobby);

		public delegate void DisconnectLobbyHandler(Result result);

		public delegate void UpdateMemberHandler(Result result);

		public delegate void SendLobbyMessageHandler(Result result);

		public delegate void SearchHandler(Result result);

		public delegate void ConnectVoiceHandler(Result result);

		public delegate void DisconnectVoiceHandler(Result result);

		public delegate void LobbyUpdateHandler(long lobbyId);

		public delegate void LobbyDeleteHandler(long lobbyId, uint reason);

		public delegate void MemberConnectHandler(long lobbyId, long userId);

		public delegate void MemberUpdateHandler(long lobbyId, long userId);

		public delegate void MemberDisconnectHandler(long lobbyId, long userId);

		public delegate void LobbyMessageHandler(long lobbyId, long userId, byte[] data);

		public delegate void SpeakingHandler(long lobbyId, long userId, bool speaking);

		public delegate void NetworkMessageHandler(long lobbyId, long userId, byte channelId, byte[] data);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event LobbyUpdateHandler OnLobbyUpdate;

		public event LobbyDeleteHandler OnLobbyDelete;

		public event MemberConnectHandler OnMemberConnect;

		public event MemberUpdateHandler OnMemberUpdate;

		public event MemberDisconnectHandler OnMemberDisconnect;

		public event LobbyMessageHandler OnLobbyMessage;

		public event SpeakingHandler OnSpeaking;

		public event NetworkMessageHandler OnNetworkMessage;

		internal LobbyManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnLobbyUpdate = OnLobbyUpdateImpl;
			events.OnLobbyDelete = OnLobbyDeleteImpl;
			events.OnMemberConnect = OnMemberConnectImpl;
			events.OnMemberUpdate = OnMemberUpdateImpl;
			events.OnMemberDisconnect = OnMemberDisconnectImpl;
			events.OnLobbyMessage = OnLobbyMessageImpl;
			events.OnSpeaking = OnSpeakingImpl;
			events.OnNetworkMessage = OnNetworkMessageImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public LobbyTransaction GetLobbyCreateTransaction()
		{
			LobbyTransaction result = default(LobbyTransaction);
			Result result2 = Methods.GetLobbyCreateTransaction(MethodsPtr, ref result.MethodsPtr);
			if (result2 != 0)
			{
				throw new ResultException(result2);
			}
			return result;
		}

		public LobbyTransaction GetLobbyUpdateTransaction(long lobbyId)
		{
			LobbyTransaction result = default(LobbyTransaction);
			Result result2 = Methods.GetLobbyUpdateTransaction(MethodsPtr, lobbyId, ref result.MethodsPtr);
			if (result2 != 0)
			{
				throw new ResultException(result2);
			}
			return result;
		}

		public LobbyMemberTransaction GetMemberUpdateTransaction(long lobbyId, long userId)
		{
			LobbyMemberTransaction result = default(LobbyMemberTransaction);
			Result result2 = Methods.GetMemberUpdateTransaction(MethodsPtr, lobbyId, userId, ref result.MethodsPtr);
			if (result2 != 0)
			{
				throw new ResultException(result2);
			}
			return result;
		}

		[MonoPInvokeCallback]
		private static void CreateLobbyCallbackImpl(IntPtr ptr, Result result, ref Lobby lobby)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			CreateLobbyHandler createLobbyHandler = (CreateLobbyHandler)gCHandle.Target;
			gCHandle.Free();
			createLobbyHandler(result, ref lobby);
		}

		public void CreateLobby(LobbyTransaction transaction, CreateLobbyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.CreateLobby(MethodsPtr, transaction.MethodsPtr, GCHandle.ToIntPtr(value), CreateLobbyCallbackImpl);
			transaction.MethodsPtr = IntPtr.Zero;
		}

		[MonoPInvokeCallback]
		private static void UpdateLobbyCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			UpdateLobbyHandler updateLobbyHandler = (UpdateLobbyHandler)gCHandle.Target;
			gCHandle.Free();
			updateLobbyHandler(result);
		}

		public void UpdateLobby(long lobbyId, LobbyTransaction transaction, UpdateLobbyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.UpdateLobby(MethodsPtr, lobbyId, transaction.MethodsPtr, GCHandle.ToIntPtr(value), UpdateLobbyCallbackImpl);
			transaction.MethodsPtr = IntPtr.Zero;
		}

		[MonoPInvokeCallback]
		private static void DeleteLobbyCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			DeleteLobbyHandler deleteLobbyHandler = (DeleteLobbyHandler)gCHandle.Target;
			gCHandle.Free();
			deleteLobbyHandler(result);
		}

		public void DeleteLobby(long lobbyId, DeleteLobbyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.DeleteLobby(MethodsPtr, lobbyId, GCHandle.ToIntPtr(value), DeleteLobbyCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void ConnectLobbyCallbackImpl(IntPtr ptr, Result result, ref Lobby lobby)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			ConnectLobbyHandler connectLobbyHandler = (ConnectLobbyHandler)gCHandle.Target;
			gCHandle.Free();
			connectLobbyHandler(result, ref lobby);
		}

		public void ConnectLobby(long lobbyId, string secret, ConnectLobbyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.ConnectLobby(MethodsPtr, lobbyId, secret, GCHandle.ToIntPtr(value), ConnectLobbyCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void ConnectLobbyWithActivitySecretCallbackImpl(IntPtr ptr, Result result, ref Lobby lobby)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			ConnectLobbyWithActivitySecretHandler connectLobbyWithActivitySecretHandler = (ConnectLobbyWithActivitySecretHandler)gCHandle.Target;
			gCHandle.Free();
			connectLobbyWithActivitySecretHandler(result, ref lobby);
		}

		public void ConnectLobbyWithActivitySecret(string activitySecret, ConnectLobbyWithActivitySecretHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.ConnectLobbyWithActivitySecret(MethodsPtr, activitySecret, GCHandle.ToIntPtr(value), ConnectLobbyWithActivitySecretCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void DisconnectLobbyCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			DisconnectLobbyHandler disconnectLobbyHandler = (DisconnectLobbyHandler)gCHandle.Target;
			gCHandle.Free();
			disconnectLobbyHandler(result);
		}

		public void DisconnectLobby(long lobbyId, DisconnectLobbyHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.DisconnectLobby(MethodsPtr, lobbyId, GCHandle.ToIntPtr(value), DisconnectLobbyCallbackImpl);
		}

		public Lobby GetLobby(long lobbyId)
		{
			Lobby lobby = default(Lobby);
			Result result = Methods.GetLobby(MethodsPtr, lobbyId, ref lobby);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return lobby;
		}

		public string GetLobbyActivitySecret(long lobbyId)
		{
			StringBuilder stringBuilder = new StringBuilder(128);
			Result result = Methods.GetLobbyActivitySecret(MethodsPtr, lobbyId, stringBuilder);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return stringBuilder.ToString();
		}

		public string GetLobbyMetadataValue(long lobbyId, string key)
		{
			StringBuilder stringBuilder = new StringBuilder(4096);
			Result result = Methods.GetLobbyMetadataValue(MethodsPtr, lobbyId, key, stringBuilder);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return stringBuilder.ToString();
		}

		public string GetLobbyMetadataKey(long lobbyId, int index)
		{
			StringBuilder stringBuilder = new StringBuilder(256);
			Result result = Methods.GetLobbyMetadataKey(MethodsPtr, lobbyId, index, stringBuilder);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return stringBuilder.ToString();
		}

		public int LobbyMetadataCount(long lobbyId)
		{
			int count = 0;
			Result result = Methods.LobbyMetadataCount(MethodsPtr, lobbyId, ref count);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return count;
		}

		public int MemberCount(long lobbyId)
		{
			int count = 0;
			Result result = Methods.MemberCount(MethodsPtr, lobbyId, ref count);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return count;
		}

		public long GetMemberUserId(long lobbyId, int index)
		{
			long userId = 0L;
			Result result = Methods.GetMemberUserId(MethodsPtr, lobbyId, index, ref userId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return userId;
		}

		public User GetMemberUser(long lobbyId, long userId)
		{
			User user = default(User);
			Result result = Methods.GetMemberUser(MethodsPtr, lobbyId, userId, ref user);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return user;
		}

		public string GetMemberMetadataValue(long lobbyId, long userId, string key)
		{
			StringBuilder stringBuilder = new StringBuilder(4096);
			Result result = Methods.GetMemberMetadataValue(MethodsPtr, lobbyId, userId, key, stringBuilder);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return stringBuilder.ToString();
		}

		public string GetMemberMetadataKey(long lobbyId, long userId, int index)
		{
			StringBuilder stringBuilder = new StringBuilder(256);
			Result result = Methods.GetMemberMetadataKey(MethodsPtr, lobbyId, userId, index, stringBuilder);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return stringBuilder.ToString();
		}

		public int MemberMetadataCount(long lobbyId, long userId)
		{
			int count = 0;
			Result result = Methods.MemberMetadataCount(MethodsPtr, lobbyId, userId, ref count);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return count;
		}

		[MonoPInvokeCallback]
		private static void UpdateMemberCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			UpdateMemberHandler updateMemberHandler = (UpdateMemberHandler)gCHandle.Target;
			gCHandle.Free();
			updateMemberHandler(result);
		}

		public void UpdateMember(long lobbyId, long userId, LobbyMemberTransaction transaction, UpdateMemberHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.UpdateMember(MethodsPtr, lobbyId, userId, transaction.MethodsPtr, GCHandle.ToIntPtr(value), UpdateMemberCallbackImpl);
			transaction.MethodsPtr = IntPtr.Zero;
		}

		[MonoPInvokeCallback]
		private static void SendLobbyMessageCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SendLobbyMessageHandler sendLobbyMessageHandler = (SendLobbyMessageHandler)gCHandle.Target;
			gCHandle.Free();
			sendLobbyMessageHandler(result);
		}

		public void SendLobbyMessage(long lobbyId, byte[] data, SendLobbyMessageHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.SendLobbyMessage(MethodsPtr, lobbyId, data, data.Length, GCHandle.ToIntPtr(value), SendLobbyMessageCallbackImpl);
		}

		public LobbySearchQuery GetSearchQuery()
		{
			LobbySearchQuery result = default(LobbySearchQuery);
			Result result2 = Methods.GetSearchQuery(MethodsPtr, ref result.MethodsPtr);
			if (result2 != 0)
			{
				throw new ResultException(result2);
			}
			return result;
		}

		[MonoPInvokeCallback]
		private static void SearchCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SearchHandler searchHandler = (SearchHandler)gCHandle.Target;
			gCHandle.Free();
			searchHandler(result);
		}

		public void Search(LobbySearchQuery query, SearchHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.Search(MethodsPtr, query.MethodsPtr, GCHandle.ToIntPtr(value), SearchCallbackImpl);
			query.MethodsPtr = IntPtr.Zero;
		}

		public int LobbyCount()
		{
			int count = 0;
			Methods.LobbyCount(MethodsPtr, ref count);
			return count;
		}

		public long GetLobbyId(int index)
		{
			long lobbyId = 0L;
			Result result = Methods.GetLobbyId(MethodsPtr, index, ref lobbyId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
			return lobbyId;
		}

		[MonoPInvokeCallback]
		private static void ConnectVoiceCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			ConnectVoiceHandler connectVoiceHandler = (ConnectVoiceHandler)gCHandle.Target;
			gCHandle.Free();
			connectVoiceHandler(result);
		}

		public void ConnectVoice(long lobbyId, ConnectVoiceHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.ConnectVoice(MethodsPtr, lobbyId, GCHandle.ToIntPtr(value), ConnectVoiceCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void DisconnectVoiceCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			DisconnectVoiceHandler disconnectVoiceHandler = (DisconnectVoiceHandler)gCHandle.Target;
			gCHandle.Free();
			disconnectVoiceHandler(result);
		}

		public void DisconnectVoice(long lobbyId, DisconnectVoiceHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.DisconnectVoice(MethodsPtr, lobbyId, GCHandle.ToIntPtr(value), DisconnectVoiceCallbackImpl);
		}

		public void ConnectNetwork(long lobbyId)
		{
			Result result = Methods.ConnectNetwork(MethodsPtr, lobbyId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void DisconnectNetwork(long lobbyId)
		{
			Result result = Methods.DisconnectNetwork(MethodsPtr, lobbyId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void FlushNetwork()
		{
			Result result = Methods.FlushNetwork(MethodsPtr);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void OpenNetworkChannel(long lobbyId, byte channelId, bool reliable)
		{
			Result result = Methods.OpenNetworkChannel(MethodsPtr, lobbyId, channelId, reliable);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void SendNetworkMessage(long lobbyId, long userId, byte channelId, byte[] data)
		{
			Result result = Methods.SendNetworkMessage(MethodsPtr, lobbyId, userId, channelId, data, data.Length);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		[MonoPInvokeCallback]
		private static void OnLobbyUpdateImpl(IntPtr ptr, long lobbyId)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnLobbyUpdate != null)
			{
				discord.LobbyManagerInstance.OnLobbyUpdate(lobbyId);
			}
		}

		[MonoPInvokeCallback]
		private static void OnLobbyDeleteImpl(IntPtr ptr, long lobbyId, uint reason)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnLobbyDelete != null)
			{
				discord.LobbyManagerInstance.OnLobbyDelete(lobbyId, reason);
			}
		}

		[MonoPInvokeCallback]
		private static void OnMemberConnectImpl(IntPtr ptr, long lobbyId, long userId)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnMemberConnect != null)
			{
				discord.LobbyManagerInstance.OnMemberConnect(lobbyId, userId);
			}
		}

		[MonoPInvokeCallback]
		private static void OnMemberUpdateImpl(IntPtr ptr, long lobbyId, long userId)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnMemberUpdate != null)
			{
				discord.LobbyManagerInstance.OnMemberUpdate(lobbyId, userId);
			}
		}

		[MonoPInvokeCallback]
		private static void OnMemberDisconnectImpl(IntPtr ptr, long lobbyId, long userId)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnMemberDisconnect != null)
			{
				discord.LobbyManagerInstance.OnMemberDisconnect(lobbyId, userId);
			}
		}

		[MonoPInvokeCallback]
		private static void OnLobbyMessageImpl(IntPtr ptr, long lobbyId, long userId, IntPtr dataPtr, int dataLen)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnLobbyMessage != null)
			{
				byte[] array = new byte[dataLen];
				Marshal.Copy(dataPtr, array, 0, dataLen);
				discord.LobbyManagerInstance.OnLobbyMessage(lobbyId, userId, array);
			}
		}

		[MonoPInvokeCallback]
		private static void OnSpeakingImpl(IntPtr ptr, long lobbyId, long userId, bool speaking)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnSpeaking != null)
			{
				discord.LobbyManagerInstance.OnSpeaking(lobbyId, userId, speaking);
			}
		}

		[MonoPInvokeCallback]
		private static void OnNetworkMessageImpl(IntPtr ptr, long lobbyId, long userId, byte channelId, IntPtr dataPtr, int dataLen)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.LobbyManagerInstance.OnNetworkMessage != null)
			{
				byte[] array = new byte[dataLen];
				Marshal.Copy(dataPtr, array, 0, dataLen);
				discord.LobbyManagerInstance.OnNetworkMessage(lobbyId, userId, channelId, array);
			}
		}

		public IEnumerable<User> GetMemberUsers(long lobbyID)
		{
			int num = MemberCount(lobbyID);
			List<User> list = new List<User>();
			for (int i = 0; i < num; i++)
			{
				list.Add(GetMemberUser(lobbyID, GetMemberUserId(lobbyID, i)));
			}
			return list;
		}

		public void SendLobbyMessage(long lobbyID, string data, SendLobbyMessageHandler handler)
		{
			SendLobbyMessage(lobbyID, Encoding.UTF8.GetBytes(data), handler);
		}
	}
	public class NetworkManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void MessageHandler(IntPtr ptr, ulong peerId, byte channelId, IntPtr dataPtr, int dataLen);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void RouteUpdateHandler(IntPtr ptr, [MarshalAs(UnmanagedType.LPStr)] string routeData);

			internal MessageHandler OnMessage;

			internal RouteUpdateHandler OnRouteUpdate;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void GetPeerIdMethod(IntPtr methodsPtr, ref ulong peerId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result FlushMethod(IntPtr methodsPtr);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result OpenPeerMethod(IntPtr methodsPtr, ulong peerId, [MarshalAs(UnmanagedType.LPStr)] string routeData);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result UpdatePeerMethod(IntPtr methodsPtr, ulong peerId, [MarshalAs(UnmanagedType.LPStr)] string routeData);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result ClosePeerMethod(IntPtr methodsPtr, ulong peerId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result OpenChannelMethod(IntPtr methodsPtr, ulong peerId, byte channelId, bool reliable);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result CloseChannelMethod(IntPtr methodsPtr, ulong peerId, byte channelId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result SendMessageMethod(IntPtr methodsPtr, ulong peerId, byte channelId, byte[] data, int dataLen);

			internal GetPeerIdMethod GetPeerId;

			internal FlushMethod Flush;

			internal OpenPeerMethod OpenPeer;

			internal UpdatePeerMethod UpdatePeer;

			internal ClosePeerMethod ClosePeer;

			internal OpenChannelMethod OpenChannel;

			internal CloseChannelMethod CloseChannel;

			internal SendMessageMethod SendMessage;
		}

		public delegate void MessageHandler(ulong peerId, byte channelId, byte[] data);

		public delegate void RouteUpdateHandler(string routeData);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event MessageHandler OnMessage;

		public event RouteUpdateHandler OnRouteUpdate;

		internal NetworkManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnMessage = OnMessageImpl;
			events.OnRouteUpdate = OnRouteUpdateImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public ulong GetPeerId()
		{
			ulong peerId = 0uL;
			Methods.GetPeerId(MethodsPtr, ref peerId);
			return peerId;
		}

		public void Flush()
		{
			Result result = Methods.Flush(MethodsPtr);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void OpenPeer(ulong peerId, string routeData)
		{
			Result result = Methods.OpenPeer(MethodsPtr, peerId, routeData);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void UpdatePeer(ulong peerId, string routeData)
		{
			Result result = Methods.UpdatePeer(MethodsPtr, peerId, routeData);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void ClosePeer(ulong peerId)
		{
			Result result = Methods.ClosePeer(MethodsPtr, peerId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void OpenChannel(ulong peerId, byte channelId, bool reliable)
		{
			Result result = Methods.OpenChannel(MethodsPtr, peerId, channelId, reliable);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void CloseChannel(ulong peerId, byte channelId)
		{
			Result result = Methods.CloseChannel(MethodsPtr, peerId, channelId);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		public void SendMessage(ulong peerId, byte channelId, byte[] data)
		{
			Result result = Methods.SendMessage(MethodsPtr, peerId, channelId, data, data.Length);
			if (result != 0)
			{
				throw new ResultException(result);
			}
		}

		[MonoPInvokeCallback]
		private static void OnMessageImpl(IntPtr ptr, ulong peerId, byte channelId, IntPtr dataPtr, int dataLen)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.NetworkManagerInstance.OnMessage != null)
			{
				byte[] array = new byte[dataLen];
				Marshal.Copy(dataPtr, array, 0, dataLen);
				discord.NetworkManagerInstance.OnMessage(peerId, channelId, array);
			}
		}

		[MonoPInvokeCallback]
		private static void OnRouteUpdateImpl(IntPtr ptr, string routeData)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.NetworkManagerInstance.OnRouteUpdate != null)
			{
				discord.NetworkManagerInstance.OnRouteUpdate(routeData);
			}
		}
	}
	public class OverlayManager
	{
		internal struct FFIEvents
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ToggleHandler(IntPtr ptr, bool locked);

			internal ToggleHandler OnToggle;
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void IsEnabledMethod(IntPtr methodsPtr, ref bool enabled);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void IsLockedMethod(IntPtr methodsPtr, ref bool locked);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SetLockedCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void SetLockedMethod(IntPtr methodsPtr, bool locked, IntPtr callbackData, SetLockedCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void OpenActivityInviteCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void OpenActivityInviteMethod(IntPtr methodsPtr, ActivityActionType type, IntPtr callbackData, OpenActivityInviteCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void OpenGuildInviteCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void OpenGuildInviteMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string code, IntPtr callbackData, OpenGuildInviteCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void OpenVoiceSettingsCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void OpenVoiceSettingsMethod(IntPtr methodsPtr, IntPtr callbackData, OpenVoiceSettingsCallback callback);

			internal IsEnabledMethod IsEnabled;

			internal IsLockedMethod IsLocked;

			internal SetLockedMethod SetLocked;

			internal OpenActivityInviteMethod OpenActivityInvite;

			internal OpenGuildInviteMethod OpenGuildInvite;

			internal OpenVoiceSettingsMethod OpenVoiceSettings;
		}

		public delegate void SetLockedHandler(Result result);

		public delegate void OpenActivityInviteHandler(Result result);

		public delegate void OpenGuildInviteHandler(Result result);

		public delegate void OpenVoiceSettingsHandler(Result result);

		public delegate void ToggleHandler(bool locked);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		public event ToggleHandler OnToggle;

		internal OverlayManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
		}

		private void InitEvents(IntPtr eventsPtr, ref FFIEvents events)
		{
			events.OnToggle = OnToggleImpl;
			Marshal.StructureToPtr(events, eventsPtr, fDeleteOld: false);
		}

		public bool IsEnabled()
		{
			bool enabled = false;
			Methods.IsEnabled(MethodsPtr, ref enabled);
			return enabled;
		}

		public bool IsLocked()
		{
			bool locked = false;
			Methods.IsLocked(MethodsPtr, ref locked);
			return locked;
		}

		[MonoPInvokeCallback]
		private static void SetLockedCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			SetLockedHandler setLockedHandler = (SetLockedHandler)gCHandle.Target;
			gCHandle.Free();
			setLockedHandler(result);
		}

		public void SetLocked(bool locked, SetLockedHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.SetLocked(MethodsPtr, locked, GCHandle.ToIntPtr(value), SetLockedCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void OpenActivityInviteCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			OpenActivityInviteHandler openActivityInviteHandler = (OpenActivityInviteHandler)gCHandle.Target;
			gCHandle.Free();
			openActivityInviteHandler(result);
		}

		public void OpenActivityInvite(ActivityActionType type, OpenActivityInviteHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.OpenActivityInvite(MethodsPtr, type, GCHandle.ToIntPtr(value), OpenActivityInviteCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void OpenGuildInviteCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			OpenGuildInviteHandler openGuildInviteHandler = (OpenGuildInviteHandler)gCHandle.Target;
			gCHandle.Free();
			openGuildInviteHandler(result);
		}

		public void OpenGuildInvite(string code, OpenGuildInviteHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.OpenGuildInvite(MethodsPtr, code, GCHandle.ToIntPtr(value), OpenGuildInviteCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void OpenVoiceSettingsCallbackImpl(IntPtr ptr, Result result)
		{
			GCHandle gCHandle = GCHandle.FromIntPtr(ptr);
			OpenVoiceSettingsHandler openVoiceSettingsHandler = (OpenVoiceSettingsHandler)gCHandle.Target;
			gCHandle.Free();
			openVoiceSettingsHandler(result);
		}

		public void OpenVoiceSettings(OpenVoiceSettingsHandler callback)
		{
			GCHandle value = GCHandle.Alloc(callback);
			Methods.OpenVoiceSettings(MethodsPtr, GCHandle.ToIntPtr(value), OpenVoiceSettingsCallbackImpl);
		}

		[MonoPInvokeCallback]
		private static void OnToggleImpl(IntPtr ptr, bool locked)
		{
			Discord discord = (Discord)GCHandle.FromIntPtr(ptr).Target;
			if (discord.OverlayManagerInstance.OnToggle != null)
			{
				discord.OverlayManagerInstance.OnToggle(locked);
			}
		}
	}
	public class StorageManager
	{
		internal struct FFIEvents
		{
		}

		internal struct FFIMethods
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result ReadMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string name, byte[] data, int dataLen, ref uint read);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ReadAsyncCallback(IntPtr ptr, Result result, IntPtr dataPtr, int dataLen);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ReadAsyncMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string name, IntPtr callbackData, ReadAsyncCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ReadAsyncPartialCallback(IntPtr ptr, Result result, IntPtr dataPtr, int dataLen);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void ReadAsyncPartialMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string name, ulong offset, ulong length, IntPtr callbackData, ReadAsyncPartialCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result WriteMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string name, byte[] data, int dataLen);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void WriteAsyncCallback(IntPtr ptr, Result result);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void WriteAsyncMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string name, byte[] data, int dataLen, IntPtr callbackData, WriteAsyncCallback callback);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result DeleteMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string name);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result ExistsMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string name, ref bool exists);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate void CountMethod(IntPtr methodsPtr, ref int count);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result StatMethod(IntPtr methodsPtr, [MarshalAs(UnmanagedType.LPStr)] string name, ref FileStat stat);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result StatAtMethod(IntPtr methodsPtr, int index, ref FileStat stat);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			internal delegate Result GetPathMethod(IntPtr methodsPtr, StringBuilder path);

			internal ReadMethod Read;

			internal ReadAsyncMethod ReadAsync;

			internal ReadAsyncPartialMethod ReadAsyncPartial;

			internal WriteMethod Write;

			internal WriteAsyncMethod WriteAsync;

			internal DeleteMethod Delete;

			internal ExistsMethod Exists;

			internal CountMethod Count;

			internal StatMethod Stat;

			internal StatAtMethod StatAt;

			internal GetPathMethod GetPath;
		}

		public delegate void ReadAsyncHandler(Result result, byte[] data);

		public delegate void ReadAsyncPartialHandler(Result result, byte[] data);

		public delegate void WriteAsyncHandler(Result result);

		private IntPtr MethodsPtr;

		private object MethodsStructure;

		private FFIMethods Methods
		{
			get
			{
				if (MethodsStructure == null)
				{
					MethodsStructure = Marshal.PtrToStructure(MethodsPtr, typeof(FFIMethods));
				}
				return (FFIMethods)MethodsStructure;
			}
		}

		internal StorageManager(IntPtr ptr, IntPtr eventsPtr, ref FFIEvents events)
		{
			if (eventsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalError);
			}
			InitEvents(eventsPtr, ref events);
			MethodsPtr = ptr;
			if (MethodsPtr == IntPtr.Zero)
			{
				throw new ResultException(Result.InternalErr

BooBoo Building/BepInEx/plugins/stefan750-LCUltrawide/LCUltrawide.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("stefan750")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A mod that allows changing of the resolution and aspect ratio of the game and UI elements")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1+516a65c96fe17ba1154e9435a986f5bce37b2daf")]
[assembly: AssemblyProduct("LCUltrawide")]
[assembly: AssemblyTitle("LCUltrawide")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LCUltrawide
{
	[BepInPlugin("LCUltrawide", "LCUltrawide", "1.1.1")]
	public class Plugin : BaseUnityPlugin
	{
		private static ConfigEntry<int> configResW;

		private static ConfigEntry<int> configResH;

		private static ConfigEntry<float> configUIScale;

		private static ConfigEntry<float> configUIAspect;

		private static float aspectUpdateTime = 1f;

		private static bool aspectAutoDetect = false;

		private static float prevAspect = 0f;

		private static float prevTime = 0f;

		private static float fDefaultHelmetWidth = 0.3628f;

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LCUltrawide is loaded!");
			configResW = ((BaseUnityPlugin)this).Config.Bind<int>("Resolution Override", "Width", 0, "Horizontal rendering resolution override.\nIf set to 0, the resolution will be automatically adjusted to fit your monitors aspect ratio.\nGame default value: 860");
			configResH = ((BaseUnityPlugin)this).Config.Bind<int>("Resolution Override", "Height", 0, "Vertical rendering resolution override.\nIf set to 0, the original resolution will be used.\nGame default value: 520");
			configUIScale = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "Scale", 1f, "Changes the size of UI elements on the screen.");
			configUIAspect = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "AspectRatio", 0f, "Changes the aspect ratio of the ingame HUD, a higher number makes the HUD wider.\n(0 = auto, 1.33 = 4:3, 1.77 = 16:9, 2.33 = 21:9, 3.55 = 32:9)");
			aspectAutoDetect = configResW.Value <= 0;
			Harmony.CreateAndPatchAll(typeof(Plugin), (string)null);
		}

		public static void ChangeAspectRatio(float newAspect)
		{
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
			HUDManager instance = HUDManager.Instance;
			Texture texture = instance.playerScreenTexture.texture;
			RenderTexture val = (RenderTexture)(object)((texture is RenderTexture) ? texture : null);
			val.Release();
			((Texture)val).height = ((configResH.Value > 0) ? configResH.Value : ((Texture)val).height);
			((Texture)val).width = ((configResW.Value > 0) ? configResW.Value : Convert.ToInt32((float)((Texture)val).height * newAspect));
			GameObject val2 = GameObject.Find("TerminalScript");
			Terminal val3 = default(Terminal);
			if ((Object)(object)val2 != (Object)null && val2.TryGetComponent<Terminal>(ref val3))
			{
				RenderTexture playerScreenTexHighRes = val3.playerScreenTexHighRes;
				playerScreenTexHighRes.Release();
				((Texture)playerScreenTexHighRes).height = ((configResH.Value > 0) ? configResH.Value : ((Texture)playerScreenTexHighRes).height);
				((Texture)playerScreenTexHighRes).width = ((configResW.Value > 0) ? configResW.Value : Convert.ToInt32((float)((Texture)playerScreenTexHighRes).height * newAspect));
			}
			if ((Object)(object)GameNetworkManager.Instance != (Object)null && (Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null)
			{
				GameNetworkManager.Instance.localPlayerController.gameplayCamera.ResetAspect();
			}
			GameObject val4 = GameObject.Find("Systems/UI/Canvas/Panel");
			AspectRatioFitter val5 = default(AspectRatioFitter);
			if ((Object)(object)val4 != (Object)null && val4.TryGetComponent<AspectRatioFitter>(ref val5))
			{
				val5.aspectRatio = newAspect;
			}
			GameObject val6 = GameObject.Find("Systems/UI/Canvas");
			CanvasScaler val7 = default(CanvasScaler);
			if ((Object)(object)val6 != (Object)null && val6.TryGetComponent<CanvasScaler>(ref val7))
			{
				float num = 500f / configUIScale.Value;
				float num2 = num * newAspect;
				val7.referenceResolution = new Vector2(num2, num);
			}
			GameObject hUDContainer = instance.HUDContainer;
			AspectRatioFitter val8 = default(AspectRatioFitter);
			if ((Object)(object)hUDContainer != (Object)null && hUDContainer.TryGetComponent<AspectRatioFitter>(ref val8))
			{
				val8.aspectRatio = ((configUIAspect.Value > 0f) ? configUIAspect.Value : newAspect);
			}
			GameObject val9 = GameObject.Find("Systems/UI/UICamera");
			Camera val10 = default(Camera);
			if ((Object)(object)val9 != (Object)null && val9.TryGetComponent<Camera>(ref val10))
			{
				val10.fieldOfView = Math.Min(106f / ((configUIAspect.Value > 0f) ? configUIAspect.Value : newAspect), 60f);
			}
			GameObject gameObject = ((Component)instance.Inventory.canvasGroup).gameObject;
			RectTransform val11 = default(RectTransform);
			if ((Object)(object)gameObject != (Object)null && gameObject.TryGetComponent<RectTransform>(ref val11))
			{
				val11.anchoredPosition = Vector2.zero;
				val11.anchorMax = new Vector2(0.5f, 0f);
				val11.anchorMin = new Vector2(0.5f, 0.5f);
				val11.pivot = new Vector2(0.5f, 0f);
			}
			GameObject val12 = GameObject.Find("PlayerHUDHelmetModel");
			Transform val13 = default(Transform);
			if ((Object)(object)val12 != (Object)null && val12.TryGetComponent<Transform>(ref val13))
			{
				Vector3 localScale = val13.localScale;
				localScale.x = fDefaultHelmetWidth * Math.Max(newAspect / 2.3f, 1f);
				val13.localScale = localScale;
			}
		}

		[HarmonyPatch(typeof(HUDManager), "Start")]
		[HarmonyPostfix]
		private static void HUDManagerStart(HUDManager __instance)
		{
			if (!aspectAutoDetect)
			{
				ChangeAspectRatio(1.77f);
			}
			prevAspect = 0f;
			prevTime = 0f;
		}

		[HarmonyPatch(typeof(HUDManager), "Update")]
		[HarmonyPostfix]
		private static void HUDManagerUpdate(HUDManager __instance)
		{
			//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_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 (aspectAutoDetect && Time.time > prevTime + aspectUpdateTime)
			{
				Vector2 renderingDisplaySize = ((Graphic)__instance.playerScreenTexture).canvas.renderingDisplaySize;
				float num = renderingDisplaySize.x / renderingDisplaySize.y;
				if (!Mathf.Approximately(num, prevAspect))
				{
					ChangeAspectRatio(num);
					prevAspect = num;
					Debug.Log((object)("New Aspect Ratio: " + num));
				}
				prevTime = Time.time;
			}
		}

		[HarmonyPatch(typeof(HUDManager), "UpdateScanNodes")]
		[HarmonyPostfix]
		private static void HUDManagerUpdateScanNodes(PlayerControllerB playerScript, HUDManager __instance, Dictionary<RectTransform, ScanNodeProperties> ___scanNodes)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			RectTransform[] scanElements = __instance.scanElements;
			RectTransform val = default(RectTransform);
			if (!((Component)__instance.playerScreenTexture).gameObject.TryGetComponent<RectTransform>(ref val))
			{
				return;
			}
			Rect rect = val.rect;
			for (int i = 0; i < scanElements.Length; i++)
			{
				if (___scanNodes.TryGetValue(scanElements[i], out var value))
				{
					Vector3 val2 = playerScript.gameplayCamera.WorldToViewportPoint(((Component)value).transform.position);
					scanElements[i].anchoredPosition = new Vector2(((Rect)(ref rect)).xMin + ((Rect)(ref rect)).width * val2.x, ((Rect)(ref rect)).yMin + ((Rect)(ref rect)).height * val2.y);
				}
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LCUltrawide";

		public const string PLUGIN_NAME = "LCUltrawide";

		public const string PLUGIN_VERSION = "1.1.1";
	}
}

BooBoo Building/BepInEx/plugins/Suskitech-AlwaysHearActiveWalkies/AlwaysHearWalkie.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LCAlwaysHearWalkieMod.Patches;
using Microsoft.CodeAnalysis;
using UnityEngine;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BepInEx5.PluginTemplate
{
	[BepInPlugin("suskitech.LCAlwaysHearActiveWalkie", "LC Always Hear Active Walkies", "1.4.3")]
	public class LCAlwaysHearWalkieMod : BaseUnityPlugin
	{
		public static ManualLogSource Log;

		private const string modGUID = "suskitech.LCAlwaysHearActiveWalkie";

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

		private const string modVersion = "1.4.3";

		private readonly Harmony harmony = new Harmony("suskitech.LCAlwaysHearActiveWalkie");

		private static LCAlwaysHearWalkieMod Instance;

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			Log = Logger.CreateLogSource("suskitech.LCAlwaysHearActiveWalkie");
			Log.LogInfo((object)"\\ /");
			Log.LogInfo((object)"/|\\");
			Log.LogInfo((object)" |----|");
			Log.LogInfo((object)" |[__]| Always Hear Active Walkies");
			Log.LogInfo((object)" |.  .| Version 1.4.3 Loaded");
			Log.LogInfo((object)" |____|");
			harmony.PatchAll(typeof(LCAlwaysHearWalkieMod));
			harmony.PatchAll(typeof(PlayerControllerBPatch));
			harmony.PatchAll(typeof(WalkieTalkiePatch));
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "AlwaysHearWalkie";

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

		public const string PLUGIN_VERSION = "1.4.3";
	}
}
namespace LCAlwaysHearWalkieMod.Patches
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		private static float AudibleDistance = 20f;

		private static float throttleInterval = 0.35f;

		private static float throttle = 0f;

		private static float AverageDistanceToHeldWalkie = 2f;

		private static float WalkieRecordingRange = 20f;

		private static float PlayerToPlayerSpatialHearingRange = 20f;

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void alwaysHearWalkieTalkiesPatch(ref bool ___holdingWalkieTalkie, ref PlayerControllerB __instance)
		{
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0303: Unknown result type (might be due to invalid IL or missing references)
			//IL_034d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			throttle += Time.deltaTime;
			if (throttle < throttleInterval)
			{
				return;
			}
			throttle = 0f;
			if ((Object)(object)__instance == (Object)null || (Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)__instance != (Object)(object)GameNetworkManager.Instance.localPlayerController || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null)
			{
				return;
			}
			if (!GameNetworkManager.Instance.localPlayerController.isPlayerDead)
			{
				List<WalkieTalkie> list = new List<WalkieTalkie>();
				List<WalkieTalkie> list2 = new List<WalkieTalkie>();
				for (int i = 0; i < WalkieTalkie.allWalkieTalkies.Count; i++)
				{
					float num = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[i]).transform.position, ((Component)__instance).transform.position);
					if (num <= AudibleDistance)
					{
						if (((GrabbableObject)WalkieTalkie.allWalkieTalkies[i]).isBeingUsed)
						{
							list.Add(WalkieTalkie.allWalkieTalkies[i]);
						}
					}
					else
					{
						list2.Add(WalkieTalkie.allWalkieTalkies[i]);
					}
				}
				bool flag = list.Count > 0;
				if (flag != __instance.holdingWalkieTalkie)
				{
					___holdingWalkieTalkie = flag;
					for (int j = 0; j < list2.Count; j++)
					{
						if (j < list.Count)
						{
							list2[j].thisAudio.Stop();
						}
					}
				}
				if (!flag)
				{
					return;
				}
			}
			PlayerControllerB val = ((!GameNetworkManager.Instance.localPlayerController.isPlayerDead || !((Object)(object)GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript != (Object)null)) ? GameNetworkManager.Instance.localPlayerController : GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript);
			for (int k = 0; k < StartOfRound.Instance.allPlayerScripts.Length; k++)
			{
				PlayerControllerB val2 = StartOfRound.Instance.allPlayerScripts[k];
				if ((!val2.isPlayerControlled && !val2.isPlayerDead) || (Object)(object)val2 == (Object)(object)GameNetworkManager.Instance.localPlayerController || val2.isPlayerDead || !val2.holdingWalkieTalkie)
				{
					continue;
				}
				float num2 = Vector3.Distance(((Component)val).transform.position, ((Component)val2).transform.position);
				float num3 = float.MaxValue;
				float num4 = float.MaxValue;
				for (int l = 0; l < WalkieTalkie.allWalkieTalkies.Count; l++)
				{
					if (!((GrabbableObject)WalkieTalkie.allWalkieTalkies[l]).isBeingUsed)
					{
						continue;
					}
					float num5 = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[l].target).transform.position, ((Component)val).transform.position);
					if (num5 < num4)
					{
						num4 = num5;
					}
					if (!WalkieTalkie.allWalkieTalkies[l].speakingIntoWalkieTalkie)
					{
						float num6 = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[l]).transform.position, ((Component)val2).transform.position);
						if (num6 < num3)
						{
							num3 = num6;
						}
					}
				}
				float num7 = Mathf.Min(1f - Mathf.InverseLerp(AverageDistanceToHeldWalkie, WalkieRecordingRange, num3), 1f - Mathf.InverseLerp(AverageDistanceToHeldWalkie, WalkieRecordingRange, num4));
				float num8 = 1f - Mathf.InverseLerp(0f, PlayerToPlayerSpatialHearingRange, num2);
				val2.voicePlayerState.Volume = Mathf.Max(num7, num8);
				if (val2.speakingToWalkieTalkie && num7 > num8)
				{
					makePlayerSoundWalkieTalkie(val2);
				}
				else
				{
					makePlayerSoundSpatial(val2);
				}
			}
		}

		private static void makePlayerSoundWalkieTalkie(PlayerControllerB playerController)
		{
			AudioSource currentVoiceChatAudioSource = playerController.currentVoiceChatAudioSource;
			AudioLowPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>();
			AudioHighPassFilter component2 = ((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>();
			OccludeAudio component3 = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>();
			((Behaviour)component2).enabled = true;
			((Behaviour)component).enabled = true;
			component3.overridingLowPass = true;
			currentVoiceChatAudioSource.spatialBlend = 0f;
			playerController.currentVoiceChatIngameSettings.set2D = true;
			currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[playerController.playerClientId];
			currentVoiceChatAudioSource.bypassListenerEffects = false;
			currentVoiceChatAudioSource.bypassEffects = false;
			currentVoiceChatAudioSource.panStereo = (GameNetworkManager.Instance.localPlayerController.isPlayerDead ? 0f : 0.4f);
			component3.lowPassOverride = 4000f;
			component.lowpassResonanceQ = 3f;
		}

		private static void makePlayerSoundSpatial(PlayerControllerB playerController)
		{
			AudioSource currentVoiceChatAudioSource = playerController.currentVoiceChatAudioSource;
			AudioLowPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>();
			AudioHighPassFilter component2 = ((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>();
			OccludeAudio component3 = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>();
			((Behaviour)component2).enabled = false;
			((Behaviour)component).enabled = true;
			component3.overridingLowPass = playerController.voiceMuffledByEnemy;
			currentVoiceChatAudioSource.spatialBlend = 1f;
			playerController.currentVoiceChatIngameSettings.set2D = false;
			currentVoiceChatAudioSource.bypassListenerEffects = false;
			currentVoiceChatAudioSource.bypassEffects = false;
			currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[playerController.playerClientId];
			component.lowpassResonanceQ = 1f;
		}
	}
	[HarmonyPatch(typeof(WalkieTalkie))]
	internal class WalkieTalkiePatch
	{
		[HarmonyPatch("EnableWalkieTalkieListening")]
		[HarmonyPrefix]
		private static bool alwaysHearWalkieTalkiesEnableWalkieTalkieListeningPatch(bool enable)
		{
			if (!enable)
			{
				return false;
			}
			return true;
		}
	}
}

BooBoo Building/BepInEx/plugins/Sv_Matt-HideModList/HideModList.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("HideModList")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Hides the LC api modlist info")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("HideModList")]
[assembly: AssemblyTitle("HideModList")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace HideModList
{
	[HarmonyPatch(typeof(HUDManager), "DisplayTip")]
	public static class DisplayTipPatch
	{
		public static bool Prefix(HUDManager __instance, string headerText, string bodyText, bool isWarning = false, bool useSave = false, string prefsKey = "LC_Tip1")
		{
			if (headerText.StartsWith("Mod List"))
			{
				return false;
			}
			return true;
		}
	}
	[BepInPlugin("HideModList", "HideModList", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private void Awake()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			Harmony val = new Harmony("plugin.HideModList");
			val.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin HideModList is loaded!");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "HideModList";

		public const string PLUGIN_NAME = "HideModList";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

BooBoo Building/BepInEx/plugins/tinyhoot-ShipLobby/ShipLobby/ShipLobby.dll

Decompiled 9 months ago
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Unity.Netcode;
using UnityEngine;

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

		public const string NAME = "ShipLobby";

		public const string VERSION = "1.0.2";

		internal static ManualLogSource Log;

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

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "Singleton_OnClientConnectedCallback")]
		private static void LogConnect()
		{
			ShipLobby.Log.LogDebug((object)"Player connected.");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "Singleton_OnClientDisconnectCallback")]
		private static void LogDisconnect()
		{
			ShipLobby.Log.LogDebug((object)"Player disconnected.");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "ConnectionApproval")]
		private static void FixConnectionApproval(GameNetworkManager __instance, ConnectionApprovalResponse response)
		{
			if (!response.Approved && !(response.Reason != "Game has already started!") && __instance.gameHasStarted && StartOfRound.Instance.inShipPhase)
			{
				ShipLobby.Log.LogDebug((object)"Approving incoming late connection.");
				response.Reason = "";
				response.Approved = true;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(QuickMenuManager), "InviteFriendsButton")]
		private static void FixFriendInviteButton()
		{
			if (GameNetworkManager.Instance.gameHasStarted && StartOfRound.Instance.inShipPhase)
			{
				GameNetworkManager.Instance.InviteFriendsUI();
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(GameNetworkManager), "LeaveLobbyAtGameStart")]
		private static bool PreventSteamLobbyLeaving(GameNetworkManager __instance)
		{
			ShipLobby.Log.LogDebug((object)"Preventing the closing of Steam lobby.");
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(StartOfRound), "StartGame")]
		private static void CloseSteamLobby(StartOfRound __instance)
		{
			if (((NetworkBehaviour)__instance).IsServer && __instance.inShipPhase)
			{
				ShipLobby.Log.LogDebug((object)"Setting lobby to not joinable.");
				GameNetworkManager.Instance.SetLobbyJoinable(false);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "EndOfGame")]
		private static IEnumerator ReopenSteamLobby(IEnumerator coroutine, StartOfRound __instance)
		{
			while (coroutine.MoveNext())
			{
				yield return coroutine.Current;
			}
			if (!((NetworkBehaviour)__instance).IsServer)
			{
				yield break;
			}
			yield return (object)new WaitForSeconds(0.5f);
			yield return (object)new WaitUntil((Func<bool>)(() => !__instance.firingPlayersCutsceneRunning));
			ShipLobby.Log.LogDebug((object)"Reopening lobby, setting to joinable.");
			GameNetworkManager instance = GameNetworkManager.Instance;
			if (instance.currentLobby.HasValue)
			{
				instance.SetLobbyJoinable(true);
				if ((Object)(object)_quickMenuManager == (Object)null)
				{
					_quickMenuManager = Object.FindObjectOfType<QuickMenuManager>();
				}
				_quickMenuManager.inviteFriendsTextAlpha.alpha = 1f;
			}
		}
	}
}

BooBoo Building/BepInEx/plugins/tinyhoot-ShipLoot/ShipLoot/ShipLoot.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.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;

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

		public const string NAME = "ShipLoot";

		public const string VERSION = "1.0";

		internal static ManualLogSource Log;

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

		private static TextMeshProUGUI _textMesh;

		private static float _displayTimeLeft;

		private const float DisplayTime = 5f;

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

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

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

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

BooBoo Building/BepInEx/plugins/wallen-ChangeName/ChangeName.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.ServerAPI;
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("ChangeName")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Change in-game name")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+9ad07e918fa6011a98cef2e1281a0a7577b70a07")]
[assembly: AssemblyProduct("ChangeName")]
[assembly: AssemblyTitle("ChangeName")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ChangeName
{
	[BepInPlugin("me.wallen.changename", "Change Player Names", "1.0.0")]
	public class ChangeNamePlugin : BaseUnityPlugin
	{
		private const string GUID = "me.wallen.changename";

		private const string NAME = "Change Player Names";

		private const string VERSION = "1.0.0";

		private static ChangeNamePlugin Instance;

		private void Awake()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			Instance = this;
			LogInfo("Loading...");
			Harmony val = new Harmony("me.wallen.changename");
			val.PatchAll();
			Networking.GetString = (Action<string, string>)Delegate.Combine(Networking.GetString, new Action<string, string>(NameDatabase.NDNetGetString));
			LogInfo("Loading Complete!");
		}

		internal static void LogDebug(string message)
		{
			Instance.Log(message, (LogLevel)32);
		}

		internal static void LogInfo(string message)
		{
			Instance.Log(message, (LogLevel)16);
		}

		internal static void LogWarning(string message)
		{
			Instance.Log(message, (LogLevel)4);
		}

		internal static void LogError(string message)
		{
			Instance.Log(message, (LogLevel)2);
		}

		internal static void LogError(Exception ex)
		{
			Instance.Log(ex.Message + "\n" + ex.StackTrace, (LogLevel)2);
		}

		private void Log(string message, LogLevel logLevel)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			((BaseUnityPlugin)this).Logger.Log(logLevel, (object)message);
		}
	}
	internal static class NameDatabase
	{
		internal static bool shouldUpdateNames = false;

		internal static bool shouldSendNames = false;

		public const string SIG_BEGIN_UPDATE_NAMES = "CHANGE_NAME_BEGIN_UPDATE_NAMES";

		public const string SIG_UPDATE_NAME = "CHANGE_NAME_UPDATE_NAME";

		public const string SIG_END_UPDATE_NAMES = "CHANGE_NAME_END_UPDATE_NAMES";

		public const string SIG_PLAYER_JOIN = "CHANGE_NAME_PLAYER_JOIN";

		public const string SIG_NEW_LEVEL = "CHANGE_NAME_NEW_LEVEL";

		private const string SIG_NEW_ROUND = "CHANGE_NAME_NEW_ROUND";

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

		internal static string GetName(ulong id)
		{
			if (!names.ContainsKey(id))
			{
				ChangeNamePlugin.LogWarning("[NameDatabase.GetName] Failed to get name");
				return "";
			}
			return names[id];
		}

		internal static void SetName(ulong id, string name)
		{
			if (!names.ContainsKey(id))
			{
				names.Add(id, name);
			}
			else
			{
				names[id] = name;
			}
		}

		internal static bool HasName(string name)
		{
			return names.ContainsValue(name);
		}

		internal static bool HasId(ulong id)
		{
			return names.ContainsKey(id);
		}

		internal static ulong GetUsableIdFromPlayer(PlayerControllerB player)
		{
			if (!GameNetworkManager.Instance.disableSteam)
			{
				return player.playerSteamId;
			}
			return player.playerClientId;
		}

		internal static void UpdateName(string oldName, string newName)
		{
			if (!names.ContainsValue(oldName))
			{
				ChangeNamePlugin.LogWarning("[NameDatabase.UpdateName] Tried to update name " + oldName + " but it does not exist");
				ChangeNamePlugin.LogWarning(names.ToString());
			}
			else
			{
				ulong key = names.FirstOrDefault((KeyValuePair<ulong, string> x) => x.Value == oldName).Key;
				names[key] = newName;
			}
			shouldUpdateNames = true;
		}

		internal static int NumberOfNames()
		{
			return names.Count;
		}

		internal static void NDNetGetString(string data, string signature)
		{
			switch (signature)
			{
			case "CHANGE_NAME_PLAYER_JOIN":
			case "CHANGE_NAME_NEW_ROUND":
				if (((NetworkBehaviour)StartOfRound.Instance).IsHost)
				{
					shouldSendNames = true;
				}
				break;
			case "CHANGE_NAME_BEGIN_UPDATE_NAMES":
				ChangeNamePlugin.LogInfo("[NameDatabase] Beginning name update process.");
				break;
			case "CHANGE_NAME_UPDATE_NAME":
			{
				KeyValuePair<ulong, string>? keyValuePair = DecodeName(data);
				if (keyValuePair.HasValue)
				{
					KeyValuePair<ulong, string> value = keyValuePair.Value;
					ChangeNamePlugin.LogInfo("[NameDatabase] New name received: " + value.Key + " : " + value.Value);
					names[value.Key] = value.Value;
				}
				break;
			}
			case "CHANGE_NAME_END_UPDATE_NAMES":
				ChangeNamePlugin.LogInfo("[NameDatabase] End of name update process.");
				shouldUpdateNames = true;
				break;
			}
		}

		internal static void NDNetSendNames()
		{
			Networking.Broadcast(string.Empty, "CHANGE_NAME_BEGIN_UPDATE_NAMES");
			foreach (KeyValuePair<ulong, string> name in names)
			{
				string text = EncodeName(name);
				Networking.Broadcast(text, "CHANGE_NAME_UPDATE_NAME");
			}
			Networking.Broadcast(string.Empty, "CHANGE_NAME_END_UPDATE_NAMES");
		}

		private static string EncodeName(KeyValuePair<ulong, string> namePair)
		{
			return $"{namePair.Key}:{namePair.Value}";
		}

		private static KeyValuePair<ulong, string>? DecodeName(string encoded)
		{
			string[] array = encoded.Split(':');
			if (array.Length == 2 && ulong.TryParse(array[0], out var result))
			{
				return new KeyValuePair<ulong, string>(result, array[1]);
			}
			return null;
		}

		private static string EncodeNames(Dictionary<ulong, string> names)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (KeyValuePair<ulong, string> name in names)
			{
				stringBuilder.Append($"{name.Key}:{name.Value};");
			}
			return stringBuilder.ToString();
		}

		private static Dictionary<ulong, string> DecodeNames(string encoded)
		{
			string[] array = encoded.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
			Dictionary<ulong, string> dictionary = new Dictionary<ulong, string>();
			string[] array2 = array;
			foreach (string text in array2)
			{
				string[] array3 = text.Split(':');
				dictionary[ulong.Parse(array3[0])] = array3[1];
			}
			return dictionary;
		}

		private static string DictionaryToString(Dictionary<ulong, string> dictionary)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (KeyValuePair<ulong, string> item in dictionary)
			{
				stringBuilder.AppendLine($"Key: {item.Key}, Value: {item.Value}");
			}
			return stringBuilder.ToString();
		}
	}
}
namespace ChangeName.Patches
{
	[HarmonyPatch(typeof(HUDManager), "AddChatMessage")]
	internal class HUDManager_AddChatMessage
	{
		private static string lastChatMessage = "";

		private static void Postfix(HUDManager __instance, string chatMessage, string nameOfUserWhoTyped)
		{
			if (lastChatMessage == chatMessage)
			{
				return;
			}
			lastChatMessage = chatMessage;
			ChangeNamePlugin.LogDebug(chatMessage);
			if (chatMessage.Contains("!name"))
			{
				string text = chatMessage.Substring(chatMessage.IndexOf("!name") + "!name".Length).Trim();
				if (NameDatabase.HasName(text))
				{
					__instance.AddTextToChatOnServer("Duplicate names are not allowed!", -1);
				}
				else if (((NetworkBehaviour)__instance.playersManager).IsHost)
				{
					NameDatabase.UpdateName(nameOfUserWhoTyped, text);
					NameDatabase.shouldSendNames = true;
					NameDatabase.shouldUpdateNames = true;
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
	internal class PlayerControllerB_ConnectClientToPlayerObject
	{
		private static void Postfix(PlayerControllerB __instance)
		{
			ChangeNamePlugin.LogDebug("Steam Disabled: " + GameNetworkManager.Instance.disableSteam);
			ChangeNamePlugin.LogDebug("Is Host: " + ((NetworkBehaviour)__instance).IsHost);
			ChangeNamePlugin.LogDebug("Player steam ID: " + __instance.playerSteamId);
			ChangeNamePlugin.LogDebug("Player client ID: " + __instance.playerClientId);
			ChangeNamePlugin.LogDebug("Actual client ID: " + __instance.actualClientId);
			ChangeNamePlugin.LogDebug("Player Username: " + __instance.playerUsername);
			Networking.Broadcast("", "CHANGE_NAME_PLAYER_JOIN");
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "Update")]
	internal class PlayerControllerB_Update
	{
		private static float lastUpdateTime;

		private static void Postfix(PlayerControllerB __instance)
		{
			if (!(lastUpdateTime + 2f < Time.time))
			{
				return;
			}
			if (((NetworkBehaviour)__instance).IsHost)
			{
				PlayerControllerB[] allPlayerScripts = __instance.playersManager.allPlayerScripts;
				foreach (PlayerControllerB val in allPlayerScripts)
				{
					if (!NameDatabase.HasId(NameDatabase.GetUsableIdFromPlayer(val)))
					{
						NameDatabase.SetName(NameDatabase.GetUsableIdFromPlayer(val), val.playerUsername);
					}
				}
				if (NameDatabase.shouldSendNames)
				{
					NameDatabase.NDNetSendNames();
					NameDatabase.shouldSendNames = false;
				}
			}
			if (NameDatabase.shouldUpdateNames)
			{
				PlayerControllerB[] allPlayerScripts2 = __instance.playersManager.allPlayerScripts;
				foreach (PlayerControllerB val2 in allPlayerScripts2)
				{
					string name = NameDatabase.GetName(NameDatabase.GetUsableIdFromPlayer(val2));
					foreach (TransformAndName radarTarget in StartOfRound.Instance.mapScreen.radarTargets)
					{
						Transform transform = radarTarget.transform;
						if (radarTarget.name == val2.playerUsername)
						{
							StartOfRound.Instance.mapScreen.ChangeNameOfTargetTransform(transform, name);
						}
					}
					val2.playerUsername = name;
					((TMP_Text)val2.usernameBillboardText).text = name;
				}
				NameDatabase.shouldUpdateNames = false;
			}
			lastUpdateTime = Time.time;
		}
	}
	[HarmonyPatch(typeof(StartOfRound), "ArriveAtLevel")]
	internal class StartOfRound_ArriveAtLevel
	{
		private static void Postfix(StartOfRound __instance)
		{
		}
	}
}

BooBoo Building/BepInEx/plugins/zatrit-MouseBind/MouseBind.dll

Decompiled 9 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MouseBind.Patches;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MouseBind")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Allows to bind voice chat on mouse buttons")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MouseBind")]
[assembly: AssemblyTitle("MouseBind")]
[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 MouseBind
{
	[BepInPlugin("MouseBind", "MouseBind", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private void Awake()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			new Harmony("MouseBind").PatchAll(typeof(AllowMouseBindings));
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "MouseBind";

		public const string PLUGIN_NAME = "MouseBind";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace MouseBind.Patches
{
	[HarmonyPatch(typeof(IngamePlayerSettings), "RebindKey")]
	public class AllowMouseBindings
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> codes)
		{
			return codes.Where(delegate(CodeInstruction code)
			{
				bool num = code.opcode == OpCodes.Ldstr && CodeInstructionExtensions.OperandIs(code, (object)"Mouse");
				bool flag = CodeInstructionExtensions.Calls(code, typeof(RebindingOperation).GetMethod("WithControlsExcluding"));
				return !num && !flag;
			});
		}
	}
}