Decompiled source of BossAPI v1.0.1

BepInEx/plugins/LethalCompanyInputUtils.dll

Decompiled 6 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));
		}
	}
}

BepInEx/plugins/LethalLib.dll

Decompiled 6 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using LethalLib.Extras;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using On;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LethalLib")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Mod for Lethal Company")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+7c7b4f966a6195fee029a3973eece88a0d72f551")]
[assembly: AssemblyProduct("LethalLib")]
[assembly: AssemblyTitle("LethalLib")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalLib
{
	[BepInPlugin("evaisa.lethallib", "LethalLib", "0.10.1")]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGUID = "evaisa.lethallib";

		public const string ModName = "LethalLib";

		public const string ModVersion = "0.10.1";

		public static AssetBundle MainAssets;

		public static ManualLogSource logger;

		public static ConfigFile config;

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

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

		private static string GetLineOrIL(StackFrame instance)
		{
			int fileLineNumber = instance.GetFileLineNumber();
			if (fileLineNumber == -1 || fileLineNumber == 0)
			{
				return "IL_" + instance.GetILOffset().ToString("X4");
			}
			return fileLineNumber.ToString();
		}
	}
}
namespace LethalLib.Modules
{
	public class ContentLoader
	{
		public class CustomContent
		{
			private string id = "";

			public string ID => id;

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

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

			public string contentPath = "";

			internal Item item;

			public Item Item => item;

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

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

			public string buyNode1Path = null;

			public string buyNode2Path = null;

			public string itemInfoPath = null;

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

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

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

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

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

			public string[] levelOverrides = null;

			public int Rarity => rarity;

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

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

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

			internal UnlockableItem unlockable;

			public string contentPath = "";

			public int initPrice = 0;

			public string buyNode1Path = null;

			public string buyNode2Path = null;

			public string itemInfoPath = null;

			public StoreType storeType = StoreType.None;

			public UnlockableItem UnlockableItem => unlockable;

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

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

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

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

			public string contentPath = "";

			internal EnemyType enemy;

			public string infoNodePath = null;

			public string infoKeywordPath = null;

			public int rarity = 0;

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

			public string[] levelOverrides = null;

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

			public EnemyType Enemy => enemy;

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

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

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

			public string contentPath = "";

			internal SpawnableMapObjectDef hazard;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;

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

			public string[] levelOverrides = null;

			public SpawnableMapObjectDef Hazard => hazard;

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

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

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

			public string contentPath = "";

			internal SpawnableOutsideObjectDef mapObject;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;

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

			public string[] levelOverrides = null;

			public SpawnableOutsideObjectDef MapObject => mapObject;

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

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

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

		public PluginInfo modInfo;

		private AssetBundle modBundle;

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

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

		public string modName => modInfo.Metadata.Name;

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

		public string modGUID => modInfo.Metadata.GUID;

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

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

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

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

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

			public Levels.LevelTypes LevelTypes;

			public int lineIndex = -1;
		}

		public class CustomGraphLine
		{
			public GraphLine graphLine;

			public Levels.LevelTypes LevelTypes;
		}

		public class CustomDungeon
		{
			public int rarity;

			public DungeonFlow dungeonFlow;

			public Levels.LevelTypes LevelTypes;

			public string[] levelOverrides;

			public int dungeonIndex = -1;

			public AudioClip firstTimeDungeonAudio;
		}

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

			public static hook_Start <1>__RoundManager_Start;

			public static hook_Start <2>__StartOfRound_Start;
		}

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

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

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

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

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

		public static void Init()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_0053: 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: Expected O, but got Unknown
			object obj = <>O.<0>__RoundManager_GenerateNewFloor;
			if (obj == null)
			{
				hook_GenerateNewFloor val = RoundManager_GenerateNewFloor;
				<>O.<0>__RoundManager_GenerateNewFloor = val;
				obj = (object)val;
			}
			RoundManager.GenerateNewFloor += (hook_GenerateNewFloor)obj;
			object obj2 = <>O.<1>__RoundManager_Start;
			if (obj2 == null)
			{
				hook_Start val2 = RoundManager_Start;
				<>O.<1>__RoundManager_Start = val2;
				obj2 = (object)val2;
			}
			RoundManager.Start += (hook_Start)obj2;
			object obj3 = <>O.<2>__StartOfRound_Start;
			if (obj3 == null)
			{
				hook_Start val3 = StartOfRound_Start;
				<>O.<2>__StartOfRound_Start = val3;
				obj3 = (object)val3;
			}
			StartOfRound.Start += (hook_Start)obj3;
		}

		private static void StartOfRound_Start(orig_Start orig, StartOfRound self)
		{
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Expected O, but got Unknown
			foreach (CustomDungeon dungeon in customDungeons)
			{
				SelectableLevel[] levels = self.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = dungeon.LevelTypes.HasFlag(Levels.LevelTypes.All) || (dungeon.levelOverrides != null && dungeon.levelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)
					{
						Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
						if ((flag || dungeon.LevelTypes.HasFlag(levelTypes)) && !val.dungeonFlowTypes.Any((IntWithRarity rarityInt) => rarityInt.id == dungeon.dungeonIndex))
						{
							List<IntWithRarity> list = val.dungeonFlowTypes.ToList();
							list.Add(new IntWithRarity
							{
								id = dungeon.dungeonIndex,
								rarity = dungeon.rarity
							});
							val.dungeonFlowTypes = list.ToArray();
						}
					}
				}
			}
			Plugin.logger.LogInfo((object)"Added custom dungeons to levels");
			orig.Invoke(self);
		}

		private static void RoundManager_Start(orig_Start orig, RoundManager self)
		{
			foreach (CustomDungeon customDungeon in customDungeons)
			{
				if (self.dungeonFlowTypes.Contains(customDungeon.dungeonFlow))
				{
					continue;
				}
				List<DungeonFlow> list = self.dungeonFlowTypes.ToList();
				list.Add(customDungeon.dungeonFlow);
				self.dungeonFlowTypes = list.ToArray();
				int dungeonIndex = self.dungeonFlowTypes.Length - 1;
				customDungeon.dungeonIndex = dungeonIndex;
				List<AudioClip> list2 = self.firstTimeDungeonAudios.ToList();
				if (list2.Count != self.dungeonFlowTypes.Length - 1)
				{
					while (list2.Count < self.dungeonFlowTypes.Length - 1)
					{
						list2.Add(null);
					}
				}
				list2.Add(customDungeon.firstTimeDungeonAudio);
				self.firstTimeDungeonAudios = list2.ToArray();
			}
			orig.Invoke(self);
		}

		private static void RoundManager_GenerateNewFloor(orig_GenerateNewFloor orig, RoundManager self)
		{
			string name = ((Object)self.currentLevel).name;
			if (Enum.IsDefined(typeof(Levels.LevelTypes), name))
			{
				Levels.LevelTypes levelEnum = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name);
				int index = 0;
				self.dungeonGenerator.Generator.DungeonFlow.Lines.ForEach(delegate(GraphLine line)
				{
					foreach (CustomDungeonArchetype customDungeonArchetype in customDungeonArchetypes)
					{
						if (customDungeonArchetype.LevelTypes.HasFlag(levelEnum) && !line.DungeonArchetypes.Contains(customDungeonArchetype.archeType) && (customDungeonArchetype.lineIndex == -1 || customDungeonArchetype.lineIndex == index))
						{
							line.DungeonArchetypes.Add(customDungeonArchetype.archeType);
							Plugin.logger.LogInfo((object)("Added " + ((Object)customDungeonArchetype.archeType).name + " to " + name));
						}
					}
					foreach (DungeonArchetype dungeonArchetype in line.DungeonArchetypes)
					{
						string name2 = ((Object)dungeonArchetype).name;
						if (extraTileSets.ContainsKey(name2))
						{
							TileSet val4 = extraTileSets[name2];
							if (!dungeonArchetype.TileSets.Contains(val4))
							{
								dungeonArchetype.TileSets.Add(val4);
								Plugin.logger.LogInfo((object)("Added " + ((Object)val4).name + " to " + name));
							}
						}
						foreach (TileSet tileSet in dungeonArchetype.TileSets)
						{
							string name3 = ((Object)tileSet).name;
							if (extraRooms.ContainsKey(name3))
							{
								GameObjectChance item = extraRooms[name3];
								if (!tileSet.TileWeights.Weights.Contains(item))
								{
									tileSet.TileWeights.Weights.Add(item);
								}
							}
						}
					}
					index++;
				});
				foreach (CustomGraphLine customGraphLine in customGraphLines)
				{
					if (customGraphLine.LevelTypes.HasFlag(levelEnum) && !self.dungeonGenerator.Generator.DungeonFlow.Lines.Contains(customGraphLine.graphLine))
					{
						self.dungeonGenerator.Generator.DungeonFlow.Lines.Add(customGraphLine.graphLine);
					}
				}
			}
			orig.Invoke(self);
			NetworkManager val = Object.FindObjectOfType<NetworkManager>();
			RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>();
			RandomMapObject[] array2 = array;
			foreach (RandomMapObject val2 in array2)
			{
				for (int j = 0; j < val2.spawnablePrefabs.Count; j++)
				{
					string prefabName = ((Object)val2.spawnablePrefabs[j]).name;
					NetworkPrefab val3 = val.NetworkConfig.Prefabs.m_Prefabs.First((NetworkPrefab x) => ((Object)x.Prefab).name == prefabName);
					if (val3 != null && (Object)(object)val3.Prefab != (Object)(object)val2.spawnablePrefabs[j])
					{
						val2.spawnablePrefabs[j] = val3.Prefab;
					}
				}
			}
		}

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

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

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

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

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

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

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

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

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

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

			public TerminalKeyword keyword;
		}

		public enum SpawnType
		{
			Default,
			Daytime,
			Outside
		}

		public class SpawnableEnemy
		{
			public EnemyType enemy;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public SpawnType spawnType;

			public TerminalNode terminalNode;

			public TerminalKeyword infoKeyword;

			public string modName;

			public string[] spawnLevelOverrides;

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

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

			public static hook_Start <1>__Terminal_Start;
		}

		public static Terminal terminal;

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

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

		public static void Init()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			object obj = <>O.<0>__RegisterLevelEnemies;
			if (obj == null)
			{
				hook_Awake val = RegisterLevelEnemies;
				<>O.<0>__RegisterLevelEnemies = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__Terminal_Start;
			if (obj2 == null)
			{
				hook_Start val2 = Terminal_Start;
				<>O.<1>__Terminal_Start = val2;
				obj2 = (object)val2;
			}
			Terminal.Start += (hook_Start)obj2;
		}

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

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

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

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

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

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

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

			public string itemName;

			public string assetName;
		}

		public struct BuyableItemAssetInfo
		{
			public Item itemAsset;

			public TerminalKeyword keyword;
		}

		public class ScrapItem
		{
			public Item item;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public string[] spawnLevelOverrides;

			public string modName;

			public ScrapItem(Item item, int rarity, Levels.LevelTypes spawnLevels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null)
			{
				this.item = item;
				this.rarity = rarity;
				this.spawnLevels = spawnLevels;
				this.spawnLevelOverrides = spawnLevelOverrides;
			}
		}

		public class PlainItem
		{
			public Item item;

			public string modName;

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

		public class ShopItem
		{
			public Item item;

			public TerminalNode buyNode1;

			public TerminalNode buyNode2;

			public TerminalNode itemInfo;

			public int price;

			public string modName;

			public ShopItem(Item item, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = 0)
			{
				this.item = item;
				this.price = price;
				if ((Object)(object)buyNode1 != (Object)null)
				{
					this.buyNode1 = buyNode1;
				}
				if ((Object)(object)buyNode2 != (Object)null)
				{
					this.buyNode2 = buyNode2;
				}
				if ((Object)(object)itemInfo != (Object)null)
				{
					this.itemInfo = itemInfo;
				}
			}
		}

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

			public static hook_Start <1>__StartOfRound_Start;

			public static hook_Awake <2>__Terminal_Awake;
		}

		public static ConfigEntry<bool> useSavedataFix;

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

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

		public static Terminal terminal;

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

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

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

		public static void Init()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			useSavedataFix = Plugin.config.Bind<bool>("Items", "EnableItemSaveFix", false, "Allow for LethalLib to store/reorder the item list, which should fix issues where items get reshuffled when loading an old save. This is experimental and may cause save corruptions occasionally.");
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__StartOfRound_Start;
			if (obj2 == null)
			{
				hook_Start val2 = StartOfRound_Start;
				<>O.<1>__StartOfRound_Start = val2;
				obj2 = (object)val2;
			}
			StartOfRound.Start += (hook_Start)obj2;
			object obj3 = <>O.<2>__Terminal_Awake;
			if (obj3 == null)
			{
				hook_Awake val3 = Terminal_Awake;
				<>O.<2>__Terminal_Awake = val3;
				obj3 = (object)val3;
			}
			Terminal.Awake += (hook_Awake)obj3;
		}

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

		private static void Terminal_Awake(orig_Awake orig, Terminal self)
		{
			//IL_0304: 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)
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Expected O, but got Unknown
			//IL_0349: 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_0383: Unknown result type (might be due to invalid IL or missing references)
			//IL_038b: Expected O, but got Unknown
			//IL_03ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0409: Expected O, but got Unknown
			//IL_049d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b7: Expected O, but got Unknown
			terminal = self;
			List<Item> list = self.buyableItemsList.ToList();
			TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result;
			TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			Plugin.logger.LogInfo((object)$"Adding {shopItems.Count} items to terminal");
			foreach (ShopItem item in shopItems)
			{
				if (list.Any((Item x) => x.itemName == item.item.itemName))
				{
					Plugin.logger.LogInfo((object)("Item " + item.item.itemName + " already exists in terminal, skipping"));
					continue;
				}
				if (item.price == -1)
				{
					item.price = item.item.creditsWorth;
				}
				else
				{
					item.item.creditsWorth = item.price;
				}
				list.Add(item.item);
				string itemName = item.item.itemName;
				char c = itemName[itemName.Length - 1];
				string text = itemName;
				TerminalNode val3 = item.buyNode2;
				if ((Object)(object)val3 == (Object)null)
				{
					val3 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val3).name = itemName.Replace(" ", "-") + "BuyNode2";
					val3.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n";
					val3.clearPreviousText = true;
					val3.maxCharactersToType = 15;
				}
				val3.buyItemIndex = list.Count - 1;
				val3.isConfirmationNode = false;
				val3.itemCost = item.price;
				val3.playSyncedClip = 0;
				TerminalNode val4 = item.buyNode1;
				if ((Object)(object)val4 == (Object)null)
				{
					val4 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val4).name = itemName.Replace(" ", "-") + "BuyNode1";
					val4.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n";
					val4.clearPreviousText = true;
					val4.maxCharactersToType = 35;
				}
				val4.buyItemIndex = list.Count - 1;
				val4.isConfirmationNode = true;
				val4.overrideOptions = true;
				val4.itemCost = item.price;
				val4.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2]
				{
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"),
						result = val3
					},
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"),
						result = result
					}
				};
				TerminalKeyword val5 = TerminalUtils.CreateTerminalKeyword(itemName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val);
				List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList();
				list2.Add(val5);
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list3 = val.compatibleNouns.ToList();
				list3.Add(new CompatibleNoun
				{
					noun = val5,
					result = val4
				});
				val.compatibleNouns = list3.ToArray();
				TerminalNode val6 = item.itemInfo;
				if ((Object)(object)val6 == (Object)null)
				{
					val6 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val6).name = itemName.Replace(" ", "-") + "InfoNode";
					val6.displayText = "[No information about this object was found.]\n\n";
					val6.clearPreviousText = true;
					val6.maxCharactersToType = 25;
				}
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list4 = val2.compatibleNouns.ToList();
				list4.Add(new CompatibleNoun
				{
					noun = val5,
					result = val6
				});
				val2.compatibleNouns = list4.ToArray();
				BuyableItemAssetInfo buyableItemAssetInfo = default(BuyableItemAssetInfo);
				buyableItemAssetInfo.itemAsset = item.item;
				buyableItemAssetInfo.keyword = val5;
				BuyableItemAssetInfo item2 = buyableItemAssetInfo;
				buyableItemAssetInfos.Add(item2);
			}
			self.buyableItemsList = list.ToArray();
			orig.Invoke(self);
		}

		private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self)
		{
			//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_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			orig.Invoke(self);
			foreach (ScrapItem scrapItem in scrapItems)
			{
				SelectableLevel[] levels = self.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = scrapItem.spawnLevels.HasFlag(Levels.LevelTypes.All) || (scrapItem.spawnLevelOverrides != null && scrapItem.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (flag || scrapItem.spawnLevels.HasFlag(levelTypes))
					{
						SpawnableItemWithRarity item2 = new SpawnableItemWithRarity
						{
							spawnableItem = scrapItem.item,
							rarity = scrapItem.rarity
						};
						if (!val.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem.item))
						{
							val.spawnableScrap.Add(item2);
						}
					}
				}
			}
			foreach (ScrapItem scrapItem2 in scrapItems)
			{
				if (!self.allItemsList.itemsList.Contains(scrapItem2.item))
				{
					if (scrapItem2.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(scrapItem2.modName + " registered item: " + scrapItem2.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered item: " + scrapItem2.item.itemName));
					}
					LethalLibItemList.Add(scrapItem2.item);
					self.allItemsList.itemsList.Add(scrapItem2.item);
				}
			}
			foreach (ShopItem shopItem in shopItems)
			{
				if (!self.allItemsList.itemsList.Contains(shopItem.item))
				{
					if (shopItem.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(shopItem.modName + " registered item: " + shopItem.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered item: " + shopItem.item.itemName));
					}
					LethalLibItemList.Add(shopItem.item);
					self.allItemsList.itemsList.Add(shopItem.item);
				}
			}
			foreach (PlainItem plainItem in plainItems)
			{
				if (!self.allItemsList.itemsList.Contains(plainItem.item))
				{
					if (plainItem.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(plainItem.modName + " registered item: " + plainItem.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered item: " + plainItem.item.itemName));
					}
					LethalLibItemList.Add(plainItem.item);
					self.allItemsList.itemsList.Add(plainItem.item);
				}
			}
		}

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

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

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

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

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

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

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

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

			public SpawnableOutsideObjectWithRarity outsideObject;

			public Levels.LevelTypes levels;

			public string[] spawnLevelOverrides;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;
		}

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

			public static hook_SpawnMapObjects <1>__RoundManager_SpawnMapObjects;
		}

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

		public static void Init()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__RoundManager_SpawnMapObjects;
			if (obj2 == null)
			{
				hook_SpawnMapObjects val2 = RoundManager_SpawnMapObjects;
				<>O.<1>__RoundManager_SpawnMapObjects = val2;
				obj2 = (object)val2;
			}
			RoundManager.SpawnMapObjects += (hook_SpawnMapObjects)obj2;
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		internal static void Init()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			object obj = <>O.<0>__GameNetworkManager_Start;
			if (obj == null)
			{
				hook_Start val = GameNetworkManager_Start;
				<>O.<0>__GameNetworkManager_Start = val;
				obj = (object)val;
			}
			GameNetworkManager.Start += (hook_Start)obj;
		}

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

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

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

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

		public static void Init()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
		}

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

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

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

		public static void RegisterPlayerRagdoll(string id, GameObject ragdoll)
		{
			Plugin.logger.LogInfo((object)("Registering player ragdoll " + id));
			ragdollRefs.Add(id, ragdoll);
		}
	}
	public class Shaders
	{
		public static void FixShaders(GameObject gameObject)
		{
			Renderer[] componentsInChildren = gameObject.GetComponentsInChildren<Renderer>();
			foreach (Renderer val in componentsInChildren)
			{
				Material[] materials = val.materials;
				foreach (Material val2 in materials)
				{
					if (((Object)val2.shader).name.Contains("Standard"))
					{
						val2.shader = Shader.Find("HDRP/Lit");
					}
				}
			}
		}
	}
	public class TerminalUtils
	{
		public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, CompatibleNoun[] compatibleNouns = null, TerminalNode specialKeywordResult = null, TerminalKeyword defaultVerb = null, bool accessTerminalObjects = false)
		{
			TerminalKeyword val = ScriptableObject.CreateInstance<TerminalKeyword>();
			((Object)val).name = word;
			val.word = word;
			val.isVerb = isVerb;
			val.compatibleNouns = compatibleNouns;
			val.specialKeywordResult = specialKeywordResult;
			val.defaultVerb = defaultVerb;
			val.accessTerminalObjects = accessTerminalObjects;
			return val;
		}
	}
	public enum StoreType
	{
		None,
		ShipUpgrade,
		Decor
	}
	public class Unlockables
	{
		public class RegisteredUnlockable
		{
			public UnlockableItem unlockable;

			public StoreType StoreType;

			public TerminalNode buyNode1;

			public TerminalNode buyNode2;

			public TerminalNode itemInfo;

			public int price;

			public string modName;

			public bool disabled = false;

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

		public struct BuyableUnlockableAssetInfo
		{
			public UnlockableItem itemAsset;

			public TerminalKeyword keyword;
		}

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

			public static hook_Start <1>__Terminal_Start;

			public static hook_TextPostProcess <2>__Terminal_TextPostProcess;
		}

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

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

		public static void Init()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_0053: 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: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__Terminal_Start;
			if (obj2 == null)
			{
				hook_Start val2 = Terminal_Start;
				<>O.<1>__Terminal_Start = val2;
				obj2 = (object)val2;
			}
			Terminal.Start += (hook_Start)obj2;
			object obj3 = <>O.<2>__Terminal_TextPostProcess;
			if (obj3 == null)
			{
				hook_TextPostProcess val3 = Terminal_TextPostProcess;
				<>O.<2>__Terminal_TextPostProcess = val3;
				obj3 = (object)val3;
			}
			Terminal.TextPostProcess += (hook_TextPostProcess)obj3;
		}

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

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

		private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self)
		{
			orig.Invoke(self);
			Plugin.logger.LogInfo((object)$"Adding {registeredUnlockables.Count} unlockables to unlockables list");
			foreach (RegisteredUnlockable unlockable in registeredUnlockables)
			{
				unlockable.disabled = false;
				if (self.unlockablesList.unlockables.Any((UnlockableItem x) => x.unlockableName == unlockable.unlockable.unlockableName))
				{
					Plugin.logger.LogInfo((object)("Unlockable " + unlockable.unlockable.unlockableName + " already exists in unlockables list, skipping"));
					continue;
				}
				if ((Object)(object)unlockable.unlockable.prefabObject != (Object)null)
				{
					PlaceableShipObject componentInChildren = unlockable.unlockable.prefabObject.GetComponentInChildren<PlaceableShipObject>();
					if ((Object)(object)componentInChildren != (Object)null)
					{
						componentInChildren.unlockableID = self.unlockablesList.unlockables.Count;
					}
				}
				self.unlockablesList.unlockables.Add(unlockable.unlockable);
			}
		}

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

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

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

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

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

		public static void DisableUnlockable(UnlockableItem unlockable)
		{
			RegisteredUnlockable registeredUnlockable = registeredUnlockables.Find((RegisteredUnlockable unlock) => unlock.unlockable == unlockable);
			if (registeredUnlockable != null)
			{
				registeredUnlockable.disabled = true;
				if ((Object)(object)StartOfRound.Instance != (Object)null)
				{
					StartOfRound.Instance.unlockablesList.unlockables.Remove(registeredUnlockable.unlockable);
				}
			}
		}

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

			public static hook_Start <1>__MenuManager_Start;
		}

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

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

		public static void Init()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			Plugin.logger.LogInfo((object)"Utilities.Init()");
			object obj = <>O.<0>__StartOfRound_Start;
			if (obj == null)
			{
				hook_Start val = StartOfRound_Start;
				<>O.<0>__StartOfRound_Start = val;
				obj = (object)val;
			}
			StartOfRound.Start += (hook_Start)obj;
			object obj2 = <>O.<1>__MenuManager_Start;
			if (obj2 == null)
			{
				hook_Start val2 = MenuManager_Start;
				<>O.<1>__MenuManager_Start = val2;
				obj2 = (object)val2;
			}
			MenuManager.Start += (hook_Start)obj2;
		}

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

		private static void MenuManager_Start(orig_Start orig, MenuManager self)
		{
			orig.Invoke(self);
			if ((Object)(object)((Component)self).GetComponent<AudioSource>() == (Object)null)
			{
				return;
			}
			AudioMixer audioMixer = ((Component)self).GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer;
			List<GameObject> list = new List<GameObject>();
			for (int num = prefabsToFix.Count - 1; num >= 0; num--)
			{
				GameObject val = prefabsToFix[num];
				AudioSource[] componentsInChildren = val.GetComponentsInChildren<AudioSource>();
				AudioSource[] array = componentsInChildren;
				foreach (AudioSource val2 in array)
				{
					if (!((Object)(object)val2.outputAudioMixerGroup == (Object)null) && ((Object)val2.outputAudioMixerGroup.audioMixer).name == "NonDiagetic")
					{
						AudioMixerGroup val3 = audioMixer.FindMatchingGroups(((Object)val2.outputAudioMixerGroup).name)[0];
						if ((Object)(object)val3 != (Object)null)
						{
							val2.outputAudioMixerGroup = val3;
							Plugin.logger.LogInfo((object)("Set mixer group for " + ((Object)val2).name + " in " + ((Object)val).name + " to NonDiagetic:" + ((Object)val3).name));
							list.Add(val);
						}
					}
				}
			}
			foreach (GameObject item in list)
			{
				prefabsToFix.Remove(item);
			}
		}

		public static void FixMixerGroups(GameObject prefab)
		{
			if (!fixedPrefabs.Contains(prefab))
			{
				fixedPrefabs.Add(prefab);
				prefabsToFix.Add(prefab);
			}
		}
	}
	public class Weathers
	{
		public class CustomWeather
		{
			public string name;

			public int weatherVariable1;

			public int weatherVariable2;

			public WeatherEffect weatherEffect;

			public Levels.LevelTypes levels;

			public string[] spawnLevelOverrides;

			public CustomWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null, int weatherVariable1 = 0, int weatherVariable2 = 0)
			{
				this.name = name;
				this.weatherVariable1 = weatherVariable1;
				this.weatherVariable2 = weatherVariable2;
				this.weatherEffect = weatherEffect;
				this.levels = levels;
				this.spawnLevelOverrides = spawnLevelOverrides;
			}
		}

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

			public static hook_Awake <1>__StartOfRound_Awake;
		}

		public static Dictionary<int, CustomWeather> customWeathers = new Dictionary<int, CustomWeather>();

		public static int numCustomWeathers = 0;

		public static void Init()
		{
			//IL_002f: 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_0050: Expected O, but got Unknown
			//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_0071: Expected O, but got Unknown
			new Hook((MethodBase)typeof(Enum).GetMethod("ToString", new Type[0]), typeof(Weathers).GetMethod("ToStringHook"));
			object obj = <>O.<0>__TimeOfDay_Awake;
			if (obj == null)
			{
				hook_Awake val = TimeOfDay_Awake;
				<>O.<0>__TimeOfDay_Awake = val;
				obj = (object)val;
			}
			TimeOfDay.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__StartOfRound_Awake;
			if (obj2 == null)
			{
				hook_Awake val2 = StartOfRound_Awake;
				<>O.<1>__StartOfRound_Awake = val2;
				obj2 = (object)val2;
			}
			StartOfRound.Awake += (hook_Awake)obj2;
		}

		private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self)
		{
			//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_0126: 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_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Expected O, but got Unknown
			foreach (KeyValuePair<int, CustomWeather> customWeather in customWeathers)
			{
				SelectableLevel[] levels = self.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = customWeather.Value.levels.HasFlag(Levels.LevelTypes.All) || (customWeather.Value.spawnLevelOverrides != null && customWeather.Value.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)
					{
						Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
						List<RandomWeatherWithVariables> list = val.randomWeathers.ToList();
						if (flag || customWeather.Value.levels.HasFlag(levelTypes))
						{
							list.Add(new RandomWeatherWithVariables
							{
								weatherType = (LevelWeatherType)customWeather.Key,
								weatherVariable = customWeather.Value.weatherVariable1,
								weatherVariable2 = customWeather.Value.weatherVariable2
							});
							Plugin.logger.LogInfo((object)$"Added weather {customWeather.Value.name} to level {((Object)val).name} at weather index: {customWeather.Key}");
						}
						val.randomWeathers = list.ToArray();
					}
				}
			}
			orig.Invoke(self);
		}

		private static void TimeOfDay_Awake(orig_Awake orig, TimeOfDay self)
		{
			List<WeatherEffect> list = self.effects.ToList();
			int num = 0;
			foreach (KeyValuePair<int, CustomWeather> customWeather in customWeathers)
			{
				if (customWeather.Key > num)
				{
					num = customWeather.Key;
				}
			}
			while (list.Count <= num)
			{
				list.Add(null);
			}
			foreach (KeyValuePair<int, CustomWeather> customWeather2 in customWeathers)
			{
				list[customWeather2.Key] = customWeather2.Value.weatherEffect;
			}
			self.effects = list.ToArray();
			orig.Invoke(self);
		}

		public static string ToStringHook(Func<Enum, string> orig, Enum self)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected I4, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected I4, but got Unknown
			if (self.GetType() == typeof(LevelWeatherType) && customWeathers.ContainsKey((int)(LevelWeatherType)(object)self))
			{
				return customWeathers[(int)(LevelWeatherType)(object)self].name;
			}
			return orig(self);
		}

		public static void RegisterWeather(WeatherDef weather)
		{
			RegisterWeather(weather.weatherName, weather.weatherEffect, weather.levels, weather.levelOverrides, weather.weatherVariable1, weather.weatherVariable2);
		}

		public static void RegisterWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, int weatherVariable1 = 0, int weatherVariable2 = 0)
		{
			Array values = Enum.GetValues(typeof(LevelWeatherType));
			int num = values.Length - 1;
			num += numCustomWeathers;
			numCustomWeathers++;
			Plugin.logger.LogInfo((object)$"Registering weather {name} at index {num - 1}");
			customWeathers.Add(num, new CustomWeather(name, weatherEffect, levels, null, weatherVariable1, weatherVariable2));
		}

		public static void RegisterWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null, int weatherVariable1 = 0, int weatherVariable2 = 0)
		{
			Array values = Enum.GetValues(typeof(LevelWeatherType));
			int num = values.Length - 1;
			num += numCustomWeathers;
			numCustomWeathers++;
			Plugin.logger.LogInfo((object)$"Registering weather {name} at index {num - 1}");
			customWeathers.Add(num, new CustomWeather(name, weatherEffect, levels, spawnLevelOverrides, weatherVariable1, weatherVariable2));
		}

		public static void RemoveWeather(string levelName, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			foreach (KeyValuePair<int, CustomWeather> entry in customWeathers)
			{
				if (!(entry.Value.name == levelName) || !((Object)(object)StartOfRound.Instance != (Object)null))
				{
					continue;
				}
				SelectableLevel[] levels = StartOfRound.Instance.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (flag || levelFlags.HasFlag(levelTypes))
					{
						List<RandomWeatherWithVariables> list = val.randomWeathers.ToList();
						list.RemoveAll((RandomWeatherWithVariables item) => (int)item.weatherType == entry.Key);
						val.randomWeathers = list.ToArray();
					}
				}
			}
		}
	}
}
namespace LethalLib.Extras
{
	[CreateAssetMenu(menuName = "ScriptableObjects/DungeonDef")]
	public class DungeonDef : ScriptableObject
	{
		public DungeonFlow dungeonFlow;

		[Range(0f, 300f)]
		public int rarity;

		public AudioClip firstTimeDungeonAudio;
	}
	[CreateAssetMenu(menuName = "ScriptableObjects/DungeonGraphLine")]
	public class DungeonGraphLineDef : ScriptableObject
	{
		public GraphLine graphLine;
	}
	[CreateAssetMenu(menuName = "ScriptableObjects/GameObjectChance")]
	public class GameObjectChanceDef : ScriptableObject
	{
		public GameObjectChance gameObjectChance;
	}
	[CreateAssetMenu(menuName = "ScriptableObjects/SpawnableMapObject")]
	public class SpawnableMapObjectDef : ScriptableObject
	{
		public SpawnableMapObject spawnableMapObject;
	}
	[CreateAssetMenu(menuName = "ScriptableObjects/SpawnableOutsideObject")]
	public class SpawnableOutsideObjectDef : ScriptableObject
	{
		public SpawnableOutsideObjectWithRarity spawnableMapObject;
	}
	[CreateAssetMenu(menuName = "ScriptableObjects/UnlockableItem")]
	public class UnlockableItemDef : ScriptableObject
	{
		public StoreType storeType = StoreType.None;

		public UnlockableItem unlockable;
	}
	[CreateAssetMenu(menuName = "ScriptableObjects/WeatherDef")]
	public class WeatherDef : ScriptableObject
	{
		public string weatherName;

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

		public string[] levelOverrides;

		public int weatherVariable1;

		public int weatherVariable2;

		public WeatherEffect weatherEffect;
	}
}

BepInEx/plugins/TerminalApi.dll

Decompiled 6 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using TerminalApi.Classes;
using TerminalApi.Interfaces;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("NotAtomicBomb")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Terminal Api for the terminal in Lethal Company")]
[assembly: AssemblyFileVersion("1.5.1.0")]
[assembly: AssemblyInformationalVersion("1.5.1+9b12d17b39fe1f9518b55effc9f9d6af53ea5e0d")]
[assembly: AssemblyProduct("TerminalApi")]
[assembly: AssemblyTitle("TerminalApi")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/NotAtomicBomb/TerminalApi")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

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

		internal CommandInfo CommandInfo { get; set; }

		internal TerminalKeyword Keyword { get; set; }

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

		public ManualLogSource Log;

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

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

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

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

		public static Terminal Terminal { get; internal set; }

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

		public static string CurrentText => Terminal.currentText;

		public static TMP_InputField ScreenText => Terminal.screenText;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		public const string PLUGIN_NAME = "TerminalApi";

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

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

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

			public string SubmittedText { get; set; }
		}

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

		public class TerminalTextChangedEventArgs : TerminalEventArgs
		{
			public string NewText;

			public string CurrentInputText;
		}

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

		public static event TerminalEventHandler TerminalAwake;

		public static event TerminalEventHandler TerminalWaking;

		public static event TerminalEventHandler TerminalStarted;

		public static event TerminalEventHandler TerminalStarting;

		public static event TerminalEventHandler TerminalBeginUsing;

		public static event TerminalEventHandler TerminalBeganUsing;

		public static event TerminalEventHandler TerminalExited;

		public static event TerminalParseSentenceEventHandler TerminalParsedSentence;

		public static event TerminalTextChangedEventHandler TerminalTextChanged;

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

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

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

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

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

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

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

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

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

		public string Category { get; set; }

		public string Description { get; set; }

		public TerminalNode TriggerNode { get; set; }

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

patchers/BepInEx.MonoMod.HookGenPatcher/BepInEx.MonoMod.HookGenPatcher.dll

Decompiled 6 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using BepInEx.Configuration;
using BepInEx.Logging;
using Mono.Cecil;
using MonoMod;
using MonoMod.RuntimeDetour.HookGen;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Bepinex.Monomod.HookGenPatcher")]
[assembly: AssemblyDescription("Runtime HookGen for BepInEx")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HarbingerOfMe")]
[assembly: AssemblyProduct("Bepinex.Monomod.HookGenPatcher")]
[assembly: AssemblyCopyright("HarbingerOfMe-2022")]
[assembly: AssemblyTrademark("MIT")]
[assembly: ComVisible(false)]
[assembly: Guid("12032e45-9577-4195-8f4f-a729911b2f08")]
[assembly: AssemblyFileVersion("1.2.1.0")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("1.2.1.0")]
namespace BepInEx.MonoMod.HookGenPatcher;

public static class HookGenPatcher
{
	internal static ManualLogSource Logger = Logger.CreateLogSource("HookGenPatcher");

	private const string CONFIG_FILE_NAME = "HookGenPatcher.cfg";

	private static readonly ConfigFile Config = new ConfigFile(Path.Combine(Paths.ConfigPath, "HookGenPatcher.cfg"), true);

	private const char EntrySeparator = ',';

	private static readonly ConfigEntry<string> AssemblyNamesToHookGenPatch = Config.Bind<string>("General", "MMHOOKAssemblyNames", "Assembly-CSharp.dll", $"Assembly names to make mmhooks for, separate entries with : {','} ");

	private static readonly ConfigEntry<bool> preciseHash = Config.Bind<bool>("General", "Preciser filehashing", false, "Hash file using contents instead of size. Minor perfomance impact.");

	private static bool skipHashing => !preciseHash.Value;

	public static IEnumerable<string> TargetDLLs { get; } = new string[0];


	public static void Initialize()
	{
		//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cf: Expected O, but got Unknown
		//IL_0237: Unknown result type (might be due to invalid IL or missing references)
		//IL_023e: Expected O, but got Unknown
		//IL_0278: Unknown result type (might be due to invalid IL or missing references)
		//IL_0282: Expected O, but got Unknown
		//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ce: Expected O, but got Unknown
		string[] array = AssemblyNamesToHookGenPatch.Value.Split(new char[1] { ',' });
		string text = Path.Combine(Paths.PluginPath, "MMHOOK");
		string[] array2 = array;
		foreach (string text2 in array2)
		{
			string text3 = "MMHOOK_" + text2;
			string text4 = Path.Combine(Paths.ManagedPath, text2);
			string text5 = Path.Combine(text, text3);
			bool flag = true;
			string[] files = Directory.GetFiles(Paths.PluginPath, text3, SearchOption.AllDirectories);
			foreach (string text6 in files)
			{
				if (Path.GetFileName(text6).Equals(text3))
				{
					text5 = text6;
					Logger.LogInfo((object)"Previous MMHOOK location found. Using that location to save instead.");
					flag = false;
					break;
				}
			}
			if (flag)
			{
				Directory.CreateDirectory(text);
			}
			FileInfo fileInfo = new FileInfo(text4);
			long length = fileInfo.Length;
			long num = 0L;
			if (File.Exists(text5))
			{
				try
				{
					AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text5);
					try
					{
						if (val.MainModule.GetType("BepHookGen.size" + length) != null)
						{
							if (skipHashing)
							{
								Logger.LogInfo((object)"Already ran for this version, reusing that file.");
								continue;
							}
							num = fileInfo.makeHash();
							if (val.MainModule.GetType("BepHookGen.content" + num) != null)
							{
								Logger.LogInfo((object)"Already ran for this version, reusing that file.");
								continue;
							}
						}
					}
					finally
					{
						((IDisposable)val)?.Dispose();
					}
				}
				catch (BadImageFormatException)
				{
					Logger.LogWarning((object)("Failed to read " + Path.GetFileName(text5) + ", probably corrupted, remaking one."));
				}
			}
			Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1");
			Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0");
			MonoModder val2 = new MonoModder
			{
				InputPath = text4,
				OutputPath = text5,
				ReadingMode = (ReadingMode)2
			};
			try
			{
				IAssemblyResolver assemblyResolver = val2.AssemblyResolver;
				IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
				if (obj != null)
				{
					((BaseAssemblyResolver)obj).AddSearchDirectory(Paths.BepInExAssemblyDirectory);
				}
				val2.Read();
				val2.MapDependencies();
				if (File.Exists(text5))
				{
					Logger.LogDebug((object)("Clearing " + text5));
					File.Delete(text5);
				}
				Logger.LogInfo((object)"Starting HookGenerator");
				HookGenerator val3 = new HookGenerator(val2, Path.GetFileName(text5));
				ModuleDefinition outputModule = val3.OutputModule;
				try
				{
					val3.Generate();
					outputModule.Types.Add(new TypeDefinition("BepHookGen", "size" + length, (TypeAttributes)1, outputModule.TypeSystem.Object));
					if (!skipHashing)
					{
						outputModule.Types.Add(new TypeDefinition("BepHookGen", "content" + ((num == 0L) ? fileInfo.makeHash() : num), (TypeAttributes)1, outputModule.TypeSystem.Object));
					}
					outputModule.Write(text5);
				}
				finally
				{
					((IDisposable)outputModule)?.Dispose();
				}
				Logger.LogInfo((object)"Done.");
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}
	}

	public static void Patch(AssemblyDefinition _)
	{
	}

	private static long makeHash(this FileInfo fileInfo)
	{
		FileStream inputStream = fileInfo.OpenRead();
		byte[] value = null;
		using (MD5 mD = new MD5CryptoServiceProvider())
		{
			value = mD.ComputeHash(inputStream);
		}
		long num = BitConverter.ToInt64(value, 0);
		if (num == 0L)
		{
			return 1L;
		}
		return num;
	}
}

patchers/BepInEx.MonoMod.HookGenPatcher/MonoMod.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2021 0x0ade")]
[assembly: AssemblyDescription("General purpose .NET assembly modding \"basework\". This package contains the core IL patcher and relinker.")]
[assembly: AssemblyFileVersion("21.8.5.1")]
[assembly: AssemblyInformationalVersion("21.08.05.01")]
[assembly: AssemblyProduct("MonoMod")]
[assembly: AssemblyTitle("MonoMod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("21.8.5.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace MonoMod
{
	[MonoMod__SafeToCopy__]
	public class MonoModAdded : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModConstructor : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModCustomAttributeAttribute : Attribute
	{
		public MonoModCustomAttributeAttribute(string h)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModCustomMethodAttributeAttribute : Attribute
	{
		public MonoModCustomMethodAttributeAttribute(string h)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModEnumReplace : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModForceCall : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModForceCallvirt : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	[Obsolete("Use MonoModLinkFrom or RuntimeDetour / HookGen instead.")]
	public class MonoModHook : Attribute
	{
		public string FindableID;

		public Type Type;

		public MonoModHook(string findableID)
		{
			FindableID = findableID;
		}

		public MonoModHook(Type type)
		{
			Type = type;
			FindableID = type.FullName;
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModIfFlag : Attribute
	{
		public MonoModIfFlag(string key)
		{
		}

		public MonoModIfFlag(string key, bool fallback)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModIgnore : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	public class MonoModLinkFrom : Attribute
	{
		public string FindableID;

		public Type Type;

		public MonoModLinkFrom(string findableID)
		{
			FindableID = findableID;
		}

		public MonoModLinkFrom(Type type)
		{
			Type = type;
			FindableID = type.FullName;
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModLinkTo : Attribute
	{
		public MonoModLinkTo(string t)
		{
		}

		public MonoModLinkTo(Type t)
		{
		}

		public MonoModLinkTo(string t, string n)
		{
		}

		public MonoModLinkTo(Type t, string n)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModNoNew : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOnPlatform : Attribute
	{
		public MonoModOnPlatform(params Platform[] p)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOriginal : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOriginalName : Attribute
	{
		public MonoModOriginalName(string n)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModPatch : Attribute
	{
		public MonoModPatch(string name)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModPublic : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModRemove : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModReplace : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModTargetModule : Attribute
	{
		public MonoModTargetModule(string name)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	internal class MonoMod__SafeToCopy__ : Attribute
	{
	}
	public delegate bool MethodParser(MonoModder modder, MethodBody body, Instruction instr, ref int instri);
	public delegate void MethodRewriter(MonoModder modder, MethodDefinition method);
	public delegate void MethodBodyRewriter(MonoModder modder, MethodBody body, Instruction instr, int instri);
	public delegate ModuleDefinition MissingDependencyResolver(MonoModder modder, ModuleDefinition main, string name, string fullName);
	public delegate void PostProcessor(MonoModder modder);
	public delegate void ModReadEventHandler(MonoModder modder, ModuleDefinition mod);
	public class RelinkMapEntry
	{
		public string Type;

		public string FindableID;

		public RelinkMapEntry()
		{
		}

		public RelinkMapEntry(string type, string findableID)
		{
			Type = type;
			FindableID = findableID;
		}
	}
	public enum DebugSymbolFormat
	{
		Auto,
		MDB,
		PDB
	}
	public class MonoModder : IDisposable
	{
		public static readonly bool IsMono = (object)Type.GetType("Mono.Runtime") != null;

		public static readonly Version Version = typeof(MonoModder).Assembly.GetName().Version;

		public Dictionary<string, object> SharedData = new Dictionary<string, object>();

		public Dictionary<string, object> RelinkMap = new Dictionary<string, object>();

		public Dictionary<string, ModuleDefinition> RelinkModuleMap = new Dictionary<string, ModuleDefinition>();

		public HashSet<string> SkipList = new HashSet<string>(EqualityComparer<string>.Default);

		public Dictionary<string, IMetadataTokenProvider> RelinkMapCache = new Dictionary<string, IMetadataTokenProvider>();

		public Dictionary<string, TypeReference> RelinkModuleMapCache = new Dictionary<string, TypeReference>();

		public Dictionary<string, OpCode> ForceCallMap = new Dictionary<string, OpCode>();

		public ModReadEventHandler OnReadMod;

		public PostProcessor PostProcessors;

		public Dictionary<string, Action<object, object[]>> CustomAttributeHandlers = new Dictionary<string, Action<object, object[]>> { 
		{
			"MonoMod.MonoModPublic",
			delegate
			{
			}
		} };

		public Dictionary<string, Action<object, object[]>> CustomMethodAttributeHandlers = new Dictionary<string, Action<object, object[]>>();

		public MissingDependencyResolver MissingDependencyResolver;

		public MethodParser MethodParser;

		public MethodRewriter MethodRewriter;

		public MethodBodyRewriter MethodBodyRewriter;

		public Stream Input;

		public string InputPath;

		public Stream Output;

		public string OutputPath;

		public List<string> DependencyDirs = new List<string>();

		public ModuleDefinition Module;

		public Dictionary<ModuleDefinition, List<ModuleDefinition>> DependencyMap = new Dictionary<ModuleDefinition, List<ModuleDefinition>>();

		public Dictionary<string, ModuleDefinition> DependencyCache = new Dictionary<string, ModuleDefinition>();

		public Func<ICustomAttributeProvider, TypeReference, bool> ShouldCleanupAttrib;

		public bool LogVerboseEnabled;

		public bool CleanupEnabled;

		public bool PublicEverything;

		public List<ModuleReference> Mods = new List<ModuleReference>();

		public bool Strict;

		public bool MissingDependencyThrow;

		public bool RemovePatchReferences;

		public bool PreventInline;

		public bool? UpgradeMSCORLIB;

		public ReadingMode ReadingMode = (ReadingMode)1;

		public DebugSymbolFormat DebugSymbolOutputFormat;

		public int CurrentRID;

		protected IAssemblyResolver _assemblyResolver;

		protected ReaderParameters _readerParameters;

		protected WriterParameters _writerParameters;

		public bool GACEnabled;

		private string[] _GACPathsNone = new string[0];

		protected string[] _GACPaths;

		protected MethodDefinition _mmOriginalCtor;

		protected MethodDefinition _mmOriginalNameCtor;

		protected MethodDefinition _mmAddedCtor;

		protected MethodDefinition _mmPatchCtor;

		public virtual IAssemblyResolver AssemblyResolver
		{
			get
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Expected O, but got Unknown
				if (_assemblyResolver == null)
				{
					DefaultAssemblyResolver val = new DefaultAssemblyResolver();
					foreach (string dependencyDir in DependencyDirs)
					{
						((BaseAssemblyResolver)val).AddSearchDirectory(dependencyDir);
					}
					_assemblyResolver = (IAssemblyResolver)(object)val;
				}
				return _assemblyResolver;
			}
			set
			{
				_assemblyResolver = value;
			}
		}

		public virtual ReaderParameters ReaderParameters
		{
			get
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Expected O, but got Unknown
				if (_readerParameters == null)
				{
					_readerParameters = new ReaderParameters(ReadingMode)
					{
						AssemblyResolver = AssemblyResolver,
						ReadSymbols = true
					};
				}
				return _readerParameters;
			}
			set
			{
				_readerParameters = value;
			}
		}

		public virtual WriterParameters WriterParameters
		{
			get
			{
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0056: Unknown result type (might be due to invalid IL or missing references)
				//IL_005c: Expected O, but got Unknown
				//IL_0067: Expected O, but got Unknown
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Expected O, but got Unknown
				if (_writerParameters == null)
				{
					bool flag = DebugSymbolOutputFormat == DebugSymbolFormat.PDB;
					bool flag2 = DebugSymbolOutputFormat == DebugSymbolFormat.MDB;
					if (DebugSymbolOutputFormat == DebugSymbolFormat.Auto)
					{
						if ((PlatformHelper.Current & 0x25) == 37)
						{
							flag = true;
						}
						else
						{
							flag2 = true;
						}
					}
					WriterParameters val = new WriterParameters
					{
						WriteSymbols = true
					};
					object symbolWriterProvider;
					if (!flag)
					{
						if (!flag2)
						{
							symbolWriterProvider = null;
						}
						else
						{
							ISymbolWriterProvider val2 = (ISymbolWriterProvider)new MdbWriterProvider();
							symbolWriterProvider = val2;
						}
					}
					else
					{
						ISymbolWriterProvider val2 = (ISymbolWriterProvider)new NativePdbWriterProvider();
						symbolWriterProvider = val2;
					}
					val.SymbolWriterProvider = (ISymbolWriterProvider)symbolWriterProvider;
					_writerParameters = val;
				}
				return _writerParameters;
			}
			set
			{
				_writerParameters = value;
			}
		}

		public string[] GACPaths
		{
			get
			{
				if (!GACEnabled)
				{
					return _GACPathsNone;
				}
				if (_GACPaths != null)
				{
					return _GACPaths;
				}
				if (!IsMono)
				{
					string environmentVariable = Environment.GetEnvironmentVariable("windir");
					if (string.IsNullOrEmpty(environmentVariable))
					{
						return _GACPaths = _GACPathsNone;
					}
					environmentVariable = Path.Combine(environmentVariable, "Microsoft.NET");
					environmentVariable = Path.Combine(environmentVariable, "assembly");
					_GACPaths = new string[3]
					{
						Path.Combine(environmentVariable, "GAC_32"),
						Path.Combine(environmentVariable, "GAC_64"),
						Path.Combine(environmentVariable, "GAC_MSIL")
					};
				}
				else
				{
					List<string> list = new List<string>();
					string text = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName)), "gac");
					if (Directory.Exists(text))
					{
						list.Add(text);
					}
					string environmentVariable2 = Environment.GetEnvironmentVariable("MONO_GAC_PREFIX");
					if (!string.IsNullOrEmpty(environmentVariable2))
					{
						string[] array = environmentVariable2.Split(new char[1] { Path.PathSeparator });
						foreach (string text2 in array)
						{
							if (!string.IsNullOrEmpty(text2))
							{
								string path = text2;
								path = Path.Combine(path, "lib");
								path = Path.Combine(path, "mono");
								path = Path.Combine(path, "gac");
								if (Directory.Exists(path) && !list.Contains(path))
								{
									list.Add(path);
								}
							}
						}
					}
					_GACPaths = list.ToArray();
				}
				return _GACPaths;
			}
			set
			{
				GACEnabled = true;
				_GACPaths = value;
			}
		}

		public MonoModder()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			MethodParser = DefaultParser;
			MissingDependencyResolver = DefaultMissingDependencyResolver;
			PostProcessors = (PostProcessor)Delegate.Combine(PostProcessors, new PostProcessor(DefaultPostProcessor));
			string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DEPDIRS");
			if (!string.IsNullOrEmpty(environmentVariable))
			{
				foreach (string item in from dir in environmentVariable.Split(new char[1] { Path.PathSeparator })
					select dir.Trim())
				{
					IAssemblyResolver assemblyResolver = AssemblyResolver;
					IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
					if (obj != null)
					{
						((BaseAssemblyResolver)obj).AddSearchDirectory(item);
					}
					DependencyDirs.Add(item);
				}
			}
			LogVerboseEnabled = Environment.GetEnvironmentVariable("MONOMOD_LOG_VERBOSE") == "1";
			CleanupEnabled = Environment.GetEnvironmentVariable("MONOMOD_CLEANUP") != "0";
			PublicEverything = Environment.GetEnvironmentVariable("MONOMOD_PUBLIC_EVERYTHING") == "1";
			PreventInline = Environment.GetEnvironmentVariable("MONOMOD_PREVENTINLINE") == "1";
			Strict = Environment.GetEnvironmentVariable("MONOMOD_STRICT") == "1";
			MissingDependencyThrow = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") != "0";
			RemovePatchReferences = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_REMOVE_PATCH") != "0";
			string environmentVariable2 = Environment.GetEnvironmentVariable("MONOMOD_DEBUG_FORMAT");
			if (environmentVariable2 != null)
			{
				environmentVariable2 = environmentVariable2.ToLowerInvariant();
				if (environmentVariable2 == "pdb")
				{
					DebugSymbolOutputFormat = DebugSymbolFormat.PDB;
				}
				else if (environmentVariable2 == "mdb")
				{
					DebugSymbolOutputFormat = DebugSymbolFormat.MDB;
				}
			}
			string environmentVariable3 = Environment.GetEnvironmentVariable("MONOMOD_MSCORLIB_UPGRADE");
			UpgradeMSCORLIB = (string.IsNullOrEmpty(environmentVariable3) ? null : new bool?(environmentVariable3 != "0"));
			GACEnabled = Environment.GetEnvironmentVariable("MONOMOD_GAC_ENABLED") != "0";
			MonoModRulesManager.Register(this);
		}

		public virtual void ClearCaches(bool all = false, bool shareable = false, bool moduleSpecific = false)
		{
			if (all || shareable)
			{
				foreach (KeyValuePair<string, ModuleDefinition> item in DependencyCache)
				{
					item.Value.Dispose();
				}
				DependencyCache.Clear();
			}
			if (all || moduleSpecific)
			{
				RelinkMapCache.Clear();
				RelinkModuleMapCache.Clear();
			}
		}

		public virtual void Dispose()
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			ClearCaches(all: true);
			ModuleDefinition module = Module;
			if (module != null)
			{
				module.Dispose();
			}
			Module = null;
			((IDisposable)AssemblyResolver)?.Dispose();
			AssemblyResolver = null;
			foreach (ModuleDefinition mod in Mods)
			{
				if ((int)mod != 0)
				{
					mod.Dispose();
				}
			}
			foreach (List<ModuleDefinition> value in DependencyMap.Values)
			{
				foreach (ModuleDefinition item in value)
				{
					if (item != null)
					{
						item.Dispose();
					}
				}
			}
			DependencyMap.Clear();
			Input?.Dispose();
			Output?.Dispose();
		}

		public virtual void Log(object value)
		{
			Log(value.ToString());
		}

		public virtual void Log(string text)
		{
			Console.Write("[MonoMod] ");
			Console.WriteLine(text);
		}

		public virtual void LogVerbose(object value)
		{
			if (LogVerboseEnabled)
			{
				Log(value);
			}
		}

		public virtual void LogVerbose(string text)
		{
			if (LogVerboseEnabled)
			{
				Log(text);
			}
		}

		private static ModuleDefinition _ReadModule(Stream input, ReaderParameters args)
		{
			if (args.ReadSymbols)
			{
				try
				{
					return ModuleDefinition.ReadModule(input, args);
				}
				catch
				{
					args.ReadSymbols = false;
					input.Seek(0L, SeekOrigin.Begin);
				}
			}
			return ModuleDefinition.ReadModule(input, args);
		}

		private static ModuleDefinition _ReadModule(string input, ReaderParameters args)
		{
			if (args.ReadSymbols)
			{
				try
				{
					return ModuleDefinition.ReadModule(input, args);
				}
				catch
				{
					args.ReadSymbols = false;
				}
			}
			return ModuleDefinition.ReadModule(input, args);
		}

		public virtual void Read()
		{
			if (Module != null)
			{
				return;
			}
			if (Input != null)
			{
				Log("Reading input stream into module.");
				Module = _ReadModule(Input, GenReaderParameters(mainModule: true));
			}
			else if (InputPath != null)
			{
				Log("Reading input file into module.");
				IAssemblyResolver assemblyResolver = AssemblyResolver;
				IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
				if (obj != null)
				{
					((BaseAssemblyResolver)obj).AddSearchDirectory(Path.GetDirectoryName(InputPath));
				}
				DependencyDirs.Add(Path.GetDirectoryName(InputPath));
				Module = _ReadModule(InputPath, GenReaderParameters(mainModule: true, InputPath));
			}
			string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_MODS");
			if (string.IsNullOrEmpty(environmentVariable))
			{
				return;
			}
			foreach (string item in from path in environmentVariable.Split(new char[1] { Path.PathSeparator })
				select path.Trim())
			{
				ReadMod(item);
			}
		}

		public virtual void MapDependencies()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			foreach (ModuleDefinition mod in Mods)
			{
				ModuleDefinition main = mod;
				MapDependencies(main);
			}
			MapDependencies(Module);
		}

		public virtual void MapDependencies(ModuleDefinition main)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (DependencyMap.ContainsKey(main))
			{
				return;
			}
			DependencyMap[main] = new List<ModuleDefinition>();
			Enumerator<AssemblyNameReference> enumerator = main.AssemblyReferences.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					AssemblyNameReference current = enumerator.Current;
					MapDependency(main, current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void MapDependency(ModuleDefinition main, AssemblyNameReference depRef)
		{
			MapDependency(main, depRef.Name, depRef.FullName, depRef);
		}

		public virtual void MapDependency(ModuleDefinition main, string name, string fullName = null, AssemblyNameReference depRef = null)
		{
			if (!DependencyMap.TryGetValue(main, out var value))
			{
				value = (DependencyMap[main] = new List<ModuleDefinition>());
			}
			if (fullName != null && (DependencyCache.TryGetValue(fullName, out var value2) || DependencyCache.TryGetValue(fullName + " [RT:" + main.RuntimeVersion + "]", out value2)))
			{
				LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) from cache");
				value.Add(value2);
				MapDependencies(value2);
				return;
			}
			if (DependencyCache.TryGetValue(name, out value2) || DependencyCache.TryGetValue(name + " [RT:" + main.RuntimeVersion + "]", out value2))
			{
				LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " (" + name + ") from cache");
				value.Add(value2);
				MapDependencies(value2);
				return;
			}
			string text = Path.GetExtension(name).ToLowerInvariant();
			bool flag = text == "pdb" || text == "mdb";
			string text2 = null;
			foreach (string dependencyDir in DependencyDirs)
			{
				text2 = Path.Combine(dependencyDir, name + ".dll");
				if (!File.Exists(text2))
				{
					text2 = Path.Combine(dependencyDir, name + ".exe");
				}
				if (!File.Exists(text2) && !flag)
				{
					text2 = Path.Combine(dependencyDir, name);
				}
				if (File.Exists(text2))
				{
					break;
				}
				text2 = null;
			}
			if (text2 == null && depRef != null)
			{
				try
				{
					AssemblyDefinition obj = AssemblyResolver.Resolve(depRef);
					value2 = ((obj != null) ? obj.MainModule : null);
				}
				catch
				{
				}
				if (value2 != null)
				{
					text2 = value2.FileName;
				}
			}
			if (text2 == null)
			{
				string[] gACPaths = GACPaths;
				for (int i = 0; i < gACPaths.Length; i++)
				{
					text2 = Path.Combine(gACPaths[i], name);
					if (Directory.Exists(text2))
					{
						string[] directories = Directory.GetDirectories(text2);
						int num = 0;
						int num2 = 0;
						for (int j = 0; j < directories.Length; j++)
						{
							string text3 = directories[j];
							if (text3.StartsWith(text2))
							{
								text3 = text3.Substring(text2.Length + 1);
							}
							Match match = Regex.Match(text3, "\\d+");
							if (match.Success)
							{
								int num3 = int.Parse(match.Value);
								if (num3 > num)
								{
									num = num3;
									num2 = j;
								}
							}
						}
						text2 = Path.Combine(directories[num2], name + ".dll");
						break;
					}
					text2 = null;
				}
			}
			if (text2 == null)
			{
				try
				{
					AssemblyDefinition obj3 = AssemblyResolver.Resolve(AssemblyNameReference.Parse(fullName ?? name));
					value2 = ((obj3 != null) ? obj3.MainModule : null);
				}
				catch
				{
				}
				if (value2 != null)
				{
					text2 = value2.FileName;
				}
			}
			if (value2 == null)
			{
				if (text2 != null && File.Exists(text2))
				{
					value2 = _ReadModule(text2, GenReaderParameters(mainModule: false, text2));
				}
				else if ((value2 = MissingDependencyResolver?.Invoke(this, main, name, fullName)) == null)
				{
					return;
				}
			}
			LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) loaded");
			value.Add(value2);
			if (fullName == null)
			{
				fullName = value2.Assembly.FullName;
			}
			DependencyCache[fullName] = value2;
			DependencyCache[name] = value2;
			MapDependencies(value2);
		}

		public virtual ModuleDefinition DefaultMissingDependencyResolver(MonoModder mod, ModuleDefinition main, string name, string fullName)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if (MissingDependencyThrow && Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") == "0")
			{
				Log("[MissingDependencyResolver] [WARNING] Use MMILRT.Modder.MissingDependencyThrow instead of setting the env var MONOMOD_DEPENDENCY_MISSING_THROW");
				MissingDependencyThrow = false;
			}
			if (MissingDependencyThrow || Strict)
			{
				throw new RelinkTargetNotFoundException("MonoMod cannot map dependency " + ((ModuleReference)main).Name + " -> ((" + fullName + "), (" + name + ")) - not found", (IMetadataTokenProvider)(object)main, (IMetadataTokenProvider)null);
			}
			return null;
		}

		public virtual void Write(Stream output = null, string outputPath = null)
		{
			output = output ?? Output;
			outputPath = outputPath ?? OutputPath;
			PatchRefsInType(PatchWasHere());
			if (output != null)
			{
				Log("[Write] Writing modded module into output stream.");
				Module.Write(output, WriterParameters);
			}
			else
			{
				Log("[Write] Writing modded module into output file.");
				Module.Write(outputPath, WriterParameters);
			}
		}

		public virtual ReaderParameters GenReaderParameters(bool mainModule, string path = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			ReaderParameters readerParameters = ReaderParameters;
			ReaderParameters val = new ReaderParameters(readerParameters.ReadingMode);
			val.AssemblyResolver = readerParameters.AssemblyResolver;
			val.MetadataResolver = readerParameters.MetadataResolver;
			val.InMemory = readerParameters.InMemory;
			val.MetadataImporterProvider = readerParameters.MetadataImporterProvider;
			val.ReflectionImporterProvider = readerParameters.ReflectionImporterProvider;
			val.ThrowIfSymbolsAreNotMatching = readerParameters.ThrowIfSymbolsAreNotMatching;
			val.ApplyWindowsRuntimeProjections = readerParameters.ApplyWindowsRuntimeProjections;
			val.SymbolStream = readerParameters.SymbolStream;
			val.SymbolReaderProvider = readerParameters.SymbolReaderProvider;
			val.ReadSymbols = readerParameters.ReadSymbols;
			if (path != null && !File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
			{
				val.ReadSymbols = false;
			}
			return val;
		}

		public virtual void ReadMod(string path)
		{
			if (Directory.Exists(path))
			{
				Log("[ReadMod] Loading mod dir: " + path);
				string text = ((ModuleReference)Module).Name.Substring(0, ((ModuleReference)Module).Name.Length - 3);
				string value = text.Replace(" ", "");
				if (!DependencyDirs.Contains(path))
				{
					IAssemblyResolver assemblyResolver = AssemblyResolver;
					IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
					if (obj != null)
					{
						((BaseAssemblyResolver)obj).AddSearchDirectory(path);
					}
					DependencyDirs.Add(path);
				}
				string[] files = Directory.GetFiles(path);
				foreach (string text2 in files)
				{
					if ((Path.GetFileName(text2).StartsWith(text) || Path.GetFileName(text2).StartsWith(value)) && text2.ToLower().EndsWith(".mm.dll"))
					{
						ReadMod(text2);
					}
				}
				return;
			}
			Log("[ReadMod] Loading mod: " + path);
			ModuleDefinition val = _ReadModule(path, GenReaderParameters(mainModule: false, path));
			string directoryName = Path.GetDirectoryName(path);
			if (!DependencyDirs.Contains(directoryName))
			{
				IAssemblyResolver assemblyResolver2 = AssemblyResolver;
				IAssemblyResolver obj2 = ((assemblyResolver2 is BaseAssemblyResolver) ? assemblyResolver2 : null);
				if (obj2 != null)
				{
					((BaseAssemblyResolver)obj2).AddSearchDirectory(directoryName);
				}
				DependencyDirs.Add(directoryName);
			}
			Mods.Add((ModuleReference)(object)val);
			OnReadMod?.Invoke(this, val);
		}

		public virtual void ReadMod(Stream stream)
		{
			Log($"[ReadMod] Loading mod: stream#{(uint)stream.GetHashCode()}");
			ModuleDefinition val = _ReadModule(stream, GenReaderParameters(mainModule: false));
			Mods.Add((ModuleReference)(object)val);
			OnReadMod?.Invoke(this, val);
		}

		public virtual void ParseRules(ModuleDefinition mod)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			TypeDefinition type = mod.GetType("MonoMod.MonoModRules");
			Type rulesTypeMMILRT = null;
			if (type != null)
			{
				rulesTypeMMILRT = this.ExecuteRules(type);
				mod.Types.Remove(type);
			}
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					ParseRulesInType(current, rulesTypeMMILRT);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void ParseRulesInType(TypeDefinition type, Type rulesTypeMMILRT = null)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_0377: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_0431: Unknown result type (might be due to invalid IL or missing references)
			//IL_0436: Unknown result type (might be due to invalid IL or missing references)
			Extensions.GetPatchFullName((MemberReference)(object)type);
			if (!MatchingConditionals((ICustomAttributeProvider)(object)type, Module))
			{
				return;
			}
			CustomAttribute customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomAttributeAttribute");
			CustomAttributeArgument val;
			if (customAttribute != null)
			{
				val = customAttribute.ConstructorArguments[0];
				MethodInfo method2 = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value);
				CustomAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
				{
					method2.Invoke(self, args);
				};
			}
			customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomMethodAttributeAttribute");
			if (customAttribute != null)
			{
				val = customAttribute.ConstructorArguments[0];
				MethodInfo method = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value);
				ParameterInfo[] parameters = method.GetParameters();
				if (parameters.Length == 2 && Extensions.IsCompatible(parameters[0].ParameterType, typeof(ILContext)))
				{
					CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
					{
						//IL_0024: Unknown result type (might be due to invalid IL or missing references)
						//IL_002e: Expected O, but got Unknown
						//IL_0029: Unknown result type (might be due to invalid IL or missing references)
						//IL_0033: Expected O, but got Unknown
						//IL_0040: Unknown result type (might be due to invalid IL or missing references)
						//IL_004a: Expected O, but got Unknown
						ILContext il = new ILContext((MethodDefinition)args[0]);
						il.Invoke((Manipulator)delegate
						{
							method.Invoke(self, new object[2]
							{
								il,
								args[1]
							});
						});
						if (il.IsReadOnly)
						{
							il.Dispose();
						}
					};
				}
				else
				{
					CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
					{
						method.Invoke(self, args);
					};
				}
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModHook"))
			{
				ParseLinkFrom((MemberReference)(object)type, val2);
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
			{
				ParseLinkFrom((MemberReference)(object)type, val2);
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
			{
				ParseLinkTo((MemberReference)(object)type, val2);
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore"))
			{
				return;
			}
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current, val2);
						}
						if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCall"))
						{
							ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Call;
						}
						else if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCallvirt"))
						{
							ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Callvirt;
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<FieldDefinition> enumerator2 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					FieldDefinition current2 = enumerator2.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current2, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current2, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current2, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current2, val2);
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<PropertyDefinition> enumerator3 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					PropertyDefinition current3 = enumerator3.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current3, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current3, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current3, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current3, val2);
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<TypeDefinition> enumerator4 = type.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					TypeDefinition current4 = enumerator4.Current;
					ParseRulesInType(current4, rulesTypeMMILRT);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
		}

		public virtual void ParseLinkFrom(MemberReference target, CustomAttribute hook)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			CustomAttributeArgument val = hook.ConstructorArguments[0];
			string key = (string)((CustomAttributeArgument)(ref val)).Value;
			object value;
			if (target is TypeReference)
			{
				value = Extensions.GetPatchFullName((MemberReference)(TypeReference)target);
			}
			else if (target is MethodReference)
			{
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(MethodReference)target).DeclaringType), Extensions.GetID((MethodReference)target, (string)null, (string)null, false, false));
			}
			else if (target is FieldReference)
			{
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(FieldReference)target).DeclaringType), ((MemberReference)(FieldReference)target).Name);
			}
			else
			{
				if (!(target is PropertyReference))
				{
					return;
				}
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(PropertyReference)target).DeclaringType), ((MemberReference)(PropertyReference)target).Name);
			}
			RelinkMap[key] = value;
		}

		public virtual void ParseLinkTo(MemberReference from, CustomAttribute hook)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			MemberReference obj = ((from is MethodReference) ? from : null);
			string key = ((obj != null) ? Extensions.GetID((MethodReference)(object)obj, (string)null, (string)null, true, false) : null) ?? Extensions.GetPatchFullName(from);
			CustomAttributeArgument val;
			if (hook.ConstructorArguments.Count == 1)
			{
				Dictionary<string, object> relinkMap = RelinkMap;
				val = hook.ConstructorArguments[0];
				relinkMap[key] = (string)((CustomAttributeArgument)(ref val)).Value;
			}
			else
			{
				Dictionary<string, object> relinkMap2 = RelinkMap;
				val = hook.ConstructorArguments[0];
				string type = (string)((CustomAttributeArgument)(ref val)).Value;
				val = hook.ConstructorArguments[1];
				relinkMap2[key] = new RelinkMapEntry(type, (string)((CustomAttributeArgument)(ref val)).Value);
			}
		}

		public virtual void RunCustomAttributeHandlers(ICustomAttributeProvider cap)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			if (!cap.HasCustomAttributes)
			{
				return;
			}
			CustomAttribute[] array = cap.CustomAttributes.ToArray();
			foreach (CustomAttribute val in array)
			{
				if (CustomAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out var value))
				{
					value?.Invoke(null, new object[2] { cap, val });
				}
				if (cap is MethodReference && CustomMethodAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out value))
				{
					value?.Invoke(null, new object[2]
					{
						(object)(MethodDefinition)cap,
						val
					});
				}
			}
		}

		public virtual void AutoPatch()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			Log("[AutoPatch] Parsing rules in loaded mods");
			foreach (ModuleDefinition mod4 in Mods)
			{
				ModuleDefinition mod = mod4;
				ParseRules(mod);
			}
			Log("[AutoPatch] PrePatch pass");
			foreach (ModuleDefinition mod5 in Mods)
			{
				ModuleDefinition mod2 = mod5;
				PrePatchModule(mod2);
			}
			Log("[AutoPatch] Patch pass");
			foreach (ModuleDefinition mod6 in Mods)
			{
				ModuleDefinition mod3 = mod6;
				PatchModule(mod3);
			}
			Log("[AutoPatch] PatchRefs pass");
			PatchRefs();
			if (PostProcessors != null)
			{
				Delegate[] invocationList = PostProcessors.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					Log($"[PostProcessor] PostProcessor pass #{i + 1}");
					((PostProcessor)invocationList[i])?.Invoke(this);
				}
			}
		}

		public virtual IMetadataTokenProvider Relinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return PostRelinker(MainRelinker(mtp, context) ?? mtp, context) ?? throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context);
			}
			catch (Exception ex)
			{
				throw new RelinkFailedException((string)null, ex, mtp, (IMetadataTokenProvider)(object)context);
			}
		}

		public virtual IMetadataTokenProvider MainRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			TypeReference val = (TypeReference)(object)((mtp is TypeReference) ? mtp : null);
			if (val != null)
			{
				if (((MemberReference)val).Module == Module)
				{
					return (IMetadataTokenProvider)(object)val;
				}
				if (((MemberReference)val).Module != null && !Mods.Contains((ModuleReference)(object)((MemberReference)val).Module))
				{
					return (IMetadataTokenProvider)(object)Module.ImportReference(val);
				}
				val = (TypeReference)(((object)Extensions.SafeResolve(val)) ?? ((object)val));
				TypeReference val2 = FindTypeDeep(Extensions.GetPatchFullName((MemberReference)(object)val));
				if (val2 == null)
				{
					if (RelinkMap.ContainsKey(((MemberReference)val).FullName))
					{
						return null;
					}
					throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context);
				}
				return (IMetadataTokenProvider)(object)Module.ImportReference(val2);
			}
			if (mtp is FieldReference || mtp is MethodReference || mtp is PropertyReference || mtp is EventReference)
			{
				return Extensions.ImportReference(Module, mtp);
			}
			throw new InvalidOperationException($"MonoMod default relinker can't handle metadata token providers of the type {((object)mtp).GetType()}");
		}

		public virtual IMetadataTokenProvider PostRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			return ResolveRelinkTarget(mtp) ?? mtp;
		}

		public virtual IMetadataTokenProvider ResolveRelinkTarget(IMetadataTokenProvider mtp, bool relink = true, bool relinkModule = true)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Expected O, but got Unknown
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Expected O, but got Unknown
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			string text = null;
			string text2;
			if (mtp is TypeReference)
			{
				text2 = ((MemberReference)(TypeReference)mtp).FullName;
			}
			else if (mtp is MethodReference)
			{
				text2 = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, false);
				text = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, true);
			}
			else if (mtp is FieldReference)
			{
				text2 = ((MemberReference)(FieldReference)mtp).FullName;
			}
			else
			{
				if (!(mtp is PropertyReference))
				{
					return null;
				}
				text2 = ((MemberReference)(PropertyReference)mtp).FullName;
			}
			if (RelinkMapCache.TryGetValue(text2, out var value))
			{
				return value;
			}
			if (relink && (RelinkMap.TryGetValue(text2, out var value2) || (text != null && RelinkMap.TryGetValue(text, out value2))))
			{
				if (value2 is IMetadataTokenProvider)
				{
					return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2);
				}
				if (value2 is RelinkMapEntry)
				{
					string type = ((RelinkMapEntry)value2).Type;
					string findableID = ((RelinkMapEntry)value2).FindableID;
					TypeReference obj = FindTypeDeep(type);
					TypeDefinition val2 = ((obj != null) ? Extensions.SafeResolve(obj) : null);
					if (val2 == null)
					{
						return RelinkMapCache[text2] = ResolveRelinkTarget(mtp, relink: false, relinkModule);
					}
					value2 = Extensions.FindMethod(val2, findableID, true) ?? ((object)Extensions.FindField(val2, findableID)) ?? ((object)(Extensions.FindProperty(val2, findableID) ?? null));
					if (value2 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} ({1}, {2}) (remap: {3})", "MonoMod relinker failed finding", type, findableID, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2);
				}
				if (value2 is string && mtp is TypeReference)
				{
					IMetadataTokenProvider val5 = (IMetadataTokenProvider)(object)FindTypeDeep((string)value2);
					if (val5 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", value2, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					value2 = Extensions.ImportReference(Module, ResolveRelinkTarget(val5, relink: false, relinkModule) ?? val5);
				}
				if (value2 is IMetadataTokenProvider)
				{
					Dictionary<string, IMetadataTokenProvider> relinkMapCache = RelinkMapCache;
					string key = text2;
					IMetadataTokenProvider val6 = (IMetadataTokenProvider)value2;
					IMetadataTokenProvider result = val6;
					relinkMapCache[key] = val6;
					return result;
				}
				throw new InvalidOperationException($"MonoMod doesn't support RelinkMap value of type {value2.GetType()} (remap: {mtp})");
			}
			if (relinkModule && mtp is TypeReference)
			{
				if (RelinkModuleMapCache.TryGetValue(text2, out var value3))
				{
					return (IMetadataTokenProvider)(object)value3;
				}
				value3 = (TypeReference)mtp;
				if (RelinkModuleMap.TryGetValue(value3.Scope.Name, out var value4))
				{
					TypeReference type2 = (TypeReference)(object)value4.GetType(((MemberReference)value3).FullName);
					if (type2 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", ((MemberReference)value3).FullName, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					return (IMetadataTokenProvider)(object)(RelinkModuleMapCache[text2] = Module.ImportReference(type2));
				}
				return (IMetadataTokenProvider)(object)Module.ImportReference(value3);
			}
			return null;
		}

		public virtual bool DefaultParser(MonoModder mod, MethodBody body, Instruction instr, ref int instri)
		{
			return true;
		}

		public virtual TypeReference FindType(string name)
		{
			return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, false);
		}

		public virtual TypeReference FindType(string name, bool runtimeName)
		{
			return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, runtimeName);
		}

		protected virtual TypeReference FindType(ModuleDefinition main, string fullName, Stack<ModuleDefinition> crawled)
		{
			TypeReference type;
			if ((type = main.GetType(fullName, false)) != null)
			{
				return type;
			}
			if (fullName.StartsWith("<PrivateImplementationDetails>/"))
			{
				return null;
			}
			if (crawled.Contains(main))
			{
				return null;
			}
			crawled.Push(main);
			foreach (ModuleDefinition item in DependencyMap[main])
			{
				if ((!RemovePatchReferences || !((AssemblyNameReference)item.Assembly.Name).Name.EndsWith(".mm")) && (type = FindType(item, fullName, crawled)) != null)
				{
					return type;
				}
			}
			return null;
		}

		public virtual TypeReference FindTypeDeep(string name)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			TypeReference val = FindType(name, runtimeName: false);
			if (val != null)
			{
				return val;
			}
			Stack<ModuleDefinition> crawled = new Stack<ModuleDefinition>();
			val = null;
			foreach (ModuleDefinition mod in Mods)
			{
				ModuleDefinition key = mod;
				foreach (ModuleDefinition item in DependencyMap[key])
				{
					if ((val = FindType(item, name, crawled)) != null)
					{
						IMetadataScope scope = val.Scope;
						AssemblyNameReference dllRef = (AssemblyNameReference)(object)((scope is AssemblyNameReference) ? scope : null);
						if (dllRef != null && !((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference n) => n.Name == dllRef.Name))
						{
							Module.AssemblyReferences.Add(dllRef);
						}
						return Module.ImportReference(val);
					}
				}
			}
			return null;
		}

		public virtual void PrePatchModule(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PrePatchType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<ModuleReference> enumerator2 = mod.ModuleReferences.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					ModuleReference current2 = enumerator2.Current;
					if (!Module.ModuleReferences.Contains(current2))
					{
						Module.ModuleReferences.Add(current2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<Resource> enumerator3 = mod.Resources.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					Resource current3 = enumerator3.Current;
					if (current3 is EmbeddedResource)
					{
						Module.Resources.Add((Resource)new EmbeddedResource(current3.Name.StartsWith(((AssemblyNameReference)mod.Assembly.Name).Name) ? (((AssemblyNameReference)Module.Assembly.Name).Name + current3.Name.Substring(((AssemblyNameReference)mod.Assembly.Name).Name.Length)) : current3.Name, current3.Attributes, ((EmbeddedResource)current3).GetResourceData()));
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
		}

		public virtual void PrePatchType(TypeDefinition type, bool forceAdd = false)
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Expected O, but got Unknown
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Expected O, but got Unknown
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type);
			if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module) || (((MemberReference)type).FullName == "MonoMod.MonoModRules" && !forceAdd))
			{
				return;
			}
			TypeReference val = (forceAdd ? null : Module.GetType(patchFullName, false));
			TypeDefinition val2 = ((val != null) ? Extensions.SafeResolve(val) : null);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModReplace") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove"))
			{
				if (val2 != null)
				{
					if (val2.DeclaringType == null)
					{
						Module.Types.Remove(val2);
					}
					else
					{
						val2.DeclaringType.NestedTypes.Remove(val2);
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			else if (val != null)
			{
				PrePatchNested(type);
				return;
			}
			LogVerbose("[PrePatchType] Adding " + patchFullName + " to the target module.");
			TypeDefinition val3 = new TypeDefinition(((TypeReference)type).Namespace, ((MemberReference)type).Name, type.Attributes, type.BaseType);
			Enumerator<GenericParameter> enumerator = ((TypeReference)type).GenericParameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					GenericParameter current = enumerator.Current;
					((TypeReference)val3).GenericParameters.Add(Extensions.Clone(current));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<InterfaceImplementation> enumerator2 = type.Interfaces.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					InterfaceImplementation current2 = enumerator2.Current;
					val3.Interfaces.Add(current2);
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			val3.ClassSize = type.ClassSize;
			if (type.DeclaringType != null)
			{
				val3.DeclaringType = Extensions.Relink((TypeReference)(object)type.DeclaringType, new Relinker(Relinker), (IGenericParameterProvider)(object)val3).Resolve();
				val3.DeclaringType.NestedTypes.Add(val3);
			}
			else
			{
				Module.Types.Add(val3);
			}
			val3.PackingSize = type.PackingSize;
			Extensions.AddRange<SecurityDeclaration>(val3.SecurityDeclarations, (IEnumerable<SecurityDeclaration>)type.SecurityDeclarations);
			val3.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
			val = (TypeReference)(object)val3;
			PrePatchNested(type);
		}

		protected virtual void PrePatchNested(TypeDefinition type)
		{
			for (int i = 0; i < type.NestedTypes.Count; i++)
			{
				PrePatchType(type.NestedTypes[i]);
			}
		}

		public virtual void PatchModule(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					if ((((TypeReference)current).Namespace == "MonoMod" || ((TypeReference)current).Namespace.StartsWith("MonoMod.")) && ((MemberReference)current.BaseType).FullName == "System.Attribute")
					{
						PatchType(current);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current2 = enumerator.Current;
					if ((!(((TypeReference)current2).Namespace == "MonoMod") && !((TypeReference)current2).Namespace.StartsWith("MonoMod.")) || !(((MemberReference)current2.BaseType).FullName == "System.Attribute"))
					{
						PatchType(current2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchType(TypeDefinition type)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type);
			TypeReference type2 = Module.GetType(patchFullName, false);
			if (type2 == null)
			{
				return;
			}
			TypeDefinition val = ((type2 != null) ? Extensions.SafeResolve(type2) : null);
			Enumerator<CustomAttribute> enumerator;
			if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module))
			{
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore") && val != null)
				{
					enumerator = type.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				PatchNested(type);
				return;
			}
			if (patchFullName == ((MemberReference)type).FullName)
			{
				LogVerbose("[PatchType] Patching type " + patchFullName);
			}
			else
			{
				LogVerbose("[PatchType] Patching type " + patchFullName + " (prefixed: " + ((MemberReference)type).FullName + ")");
			}
			enumerator = type.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current2 = enumerator.Current;
					if (!Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)val, ((MemberReference)current2.AttributeType).FullName))
					{
						val.CustomAttributes.Add(Extensions.Clone(current2));
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			HashSet<MethodDefinition> hashSet = new HashSet<MethodDefinition>();
			Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					PropertyDefinition current3 = enumerator2.Current;
					PatchProperty(val, current3, hashSet);
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			HashSet<MethodDefinition> hashSet2 = new HashSet<MethodDefinition>();
			Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					EventDefinition current4 = enumerator3.Current;
					PatchEvent(val, current4, hashSet2);
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodDefinition current5 = enumerator4.Current;
					if (!hashSet.Contains(current5) && !hashSet2.Contains(current5))
					{
						PatchMethod(val, current5);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModEnumReplace"))
			{
				int num = 0;
				while (num < val.Fields.Count)
				{
					if (((MemberReference)val.Fields[num]).Name == "value__")
					{
						num++;
					}
					else
					{
						val.Fields.RemoveAt(num);
					}
				}
			}
			Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator5.MoveNext())
				{
					FieldDefinition current6 = enumerator5.Current;
					PatchField(val, current6);
				}
			}
			finally
			{
				((IDisposable)enumerator5).Dispose();
			}
			PatchNested(type);
		}

		protected virtual void PatchNested(TypeDefinition type)
		{
			for (int i = 0; i < type.NestedTypes.Count; i++)
			{
				PatchType(type.NestedTypes[i]);
			}
		}

		public virtual void PatchProperty(TypeDefinition targetType, PropertyDefinition prop, HashSet<MethodDefinition> propMethods = null)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Expected O, but got Unknown
			//IL_022b: Expected O, but got Unknown
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Expected O, but got Unknown
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Expected O, but got Unknown
			//IL_02b5: Expected O, but got Unknown
			//IL_0363: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			if (!MatchingConditionals((ICustomAttributeProvider)(object)prop, Module))
			{
				return;
			}
			((MemberReference)prop).Name = Extensions.GetPatchName((MemberReference)(object)prop);
			PropertyDefinition val = Extensions.FindProperty(targetType, ((MemberReference)prop).Name);
			string text = "<" + ((MemberReference)prop).Name + ">__BackingField";
			FieldDefinition val2 = Extensions.FindField(prop.DeclaringType, text);
			FieldDefinition val3 = Extensions.FindField(targetType, text);
			Enumerator<CustomAttribute> enumerator;
			Enumerator<MethodDefinition> enumerator2;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModIgnore"))
			{
				if (val != null)
				{
					enumerator = prop.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (val2 != null)
				{
					val2.DeclaringType.Fields.Remove(val2);
				}
				if (prop.GetMethod != null)
				{
					propMethods?.Add(prop.GetMethod);
				}
				if (prop.SetMethod != null)
				{
					propMethods?.Add(prop.SetMethod);
				}
				enumerator2 = prop.OtherMethods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						propMethods?.Add(current2);
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModReplace"))
			{
				if (val != null)
				{
					targetType.Properties.Remove(val);
					if (val3 != null)
					{
						targetType.Fields.Remove(val3);
					}
					if (val.GetMethod != null)
					{
						targetType.Methods.Remove(val.GetMethod);
					}
					if (val.SetMethod != null)
					{
						targetType.Methods.Remove(val.SetMethod);
					}
					enumerator2 = val.OtherMethods.GetEnumerator();
					try
					{
						while (enumerator2.MoveNext())
						{
							MethodDefinition current3 = enumerator2.Current;
							targetType.Methods.Remove(current3);
						}
					}
					finally
					{
						((IDisposable)enumerator2).Dispose();
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			if (val == null)
			{
				PropertyDefinition val4 = new PropertyDefinition(((MemberReference)prop).Name, prop.Attributes, ((PropertyReference)prop).PropertyType);
				val = val4;
				PropertyDefinition val5 = val4;
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				Enumerator<ParameterDefinition> enumerator3 = ((PropertyReference)prop).Parameters.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						ParameterDefinition current4 = enumerator3.Current;
						((PropertyReference)val5).Parameters.Add(Extensions.Clone(current4));
					}
				}
				finally
				{
					((IDisposable)enumerator3).Dispose();
				}
				val5.DeclaringType = targetType;
				targetType.Properties.Add(val5);
				if (val2 != null)
				{
					FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType);
					val3 = val6;
					FieldDefinition val7 = val6;
					targetType.Fields.Add(val7);
				}
			}
			enumerator = prop.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current5 = enumerator.Current;
					val.CustomAttributes.Add(Extensions.Clone(current5));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodDefinition getMethod = prop.GetMethod;
			MethodDefinition getMethod2;
			if (getMethod != null && (getMethod2 = PatchMethod(targetType, getMethod)) != null)
			{
				val.GetMethod = getMethod2;
				propMethods?.Add(getMethod);
			}
			MethodDefinition setMethod = prop.SetMethod;
			if (setMethod != null && (getMethod2 = PatchMethod(targetType, setMethod)) != null)
			{
				val.SetMethod = getMethod2;
				propMethods?.Add(setMethod);
			}
			enumerator2 = prop.OtherMethods.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					MethodDefinition current6 = enumerator2.Current;
					if ((getMethod2 = PatchMethod(targetType, current6)) != null)
					{
						val.OtherMethods.Add(getMethod2);
						propMethods?.Add(current6);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
		}

		public virtual void PatchEvent(TypeDefinition targetType, EventDefinition srcEvent, HashSet<MethodDefinition> propMethods = null)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Expected O, but got Unknown
			//IL_0252: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			((MemberReference)srcEvent).Name = Extensions.GetPatchName((MemberReference)(object)srcEvent);
			EventDefinition val = Extensions.FindEvent(targetType, ((MemberReference)srcEvent).Name);
			string text = "<" + ((MemberReference)srcEvent).Name + ">__BackingField";
			FieldDefinition val2 = Extensions.FindField(srcEvent.DeclaringType, text);
			FieldDefinition val3 = Extensions.FindField(targetType, text);
			Enumerator<CustomAttribute> enumerator;
			Enumerator<MethodDefinition> enumerator2;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModIgnore"))
			{
				if (val != null)
				{
					enumerator = srcEvent.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (val2 != null)
				{
					val2.DeclaringType.Fields.Remove(val2);
				}
				if (srcEvent.AddMethod != null)
				{
					propMethods?.Add(srcEvent.AddMethod);
				}
				if (srcEvent.RemoveMethod != null)
				{
					propMethods?.Add(srcEvent.RemoveMethod);
				}
				if (srcEvent.InvokeMethod != null)
				{
					propMethods?.Add(srcEvent.InvokeMethod);
				}
				enumerator2 = srcEvent.OtherMethods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						propMethods?.Add(current2);
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModReplace"))
			{
				if (val != null)
				{
					targetType.Events.Remove(val);
					if (val3 != null)
					{
						targetType.Fields.Remove(val3);
					}
					if (val.AddMethod != null)
					{
						targetType.Methods.Remove(val.AddMethod);
					}
					if (val.RemoveMethod != null)
					{
						targetType.Methods.Remove(val.RemoveMethod);
					}
					if (val.InvokeMethod != null)
					{
						targetType.Methods.Remove(val.InvokeMethod);
					}
					if (val.OtherMethods != null)
					{
						enumerator2 = val.OtherMethods.GetEnumerator();
						try
						{
							while (enumerator2.MoveNext())
							{
								MethodDefinition current3 = enumerator2.Current;
								targetType.Methods.Remove(current3);
							}
						}
						finally
						{
							((IDisposable)enumerator2).Dispose();
						}
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			if (val == null)
			{
				EventDefinition val4 = new EventDefinition(((MemberReference)srcEvent).Name, srcEvent.Attributes, ((EventReference)srcEvent).EventType);
				val = val4;
				EventDefinition val5 = val4;
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				val5.DeclaringType = targetType;
				targetType.Events.Add(val5);
				if (val2 != null)
				{
					FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType);
					targetType.Fields.Add(val6);
				}
			}
			enumerator = srcEvent.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current4 = enumerator.Current;
					val.CustomAttributes.Add(Extensions.Clone(current4));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodDefinition addMethod = srcEvent.AddMethod;
			MethodDefinition addMethod2;
			if (addMethod != null && (addMethod2 = PatchMethod(targetType, addMethod)) != null)
			{
				val.AddMethod = addMethod2;
				propMethods?.Add(addMethod);
			}
			MethodDefinition removeMethod = srcEvent.RemoveMethod;
			if (removeMethod != null && (addMethod2 = PatchMethod(targetType, removeMethod)) != null)
			{
				val.RemoveMethod = addMethod2;
				propMethods?.Add(removeMethod);
			}
			MethodDefinition invokeMethod = srcEvent.InvokeMethod;
			if (invokeMethod != null && (addMethod2 = PatchMethod(targetType, invokeMethod)) != null)
			{
				val.InvokeMethod = addMethod2;
				propMethods?.Add(invokeMethod);
			}
			enumerator2 = srcEvent.OtherMethods.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					MethodDefinition current5 = enumerator2.Current;
					if ((addMethod2 = PatchMethod(targetType, current5)) != null)
					{
						val.OtherMethods.Add(addMethod2);
						propMethods?.Add(current5);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
		}

		public virtual void PatchField(TypeDefinition targetType, FieldDefinition field)
		{
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Expected O, but got Unknown
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)field.DeclaringType);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModNoNew") || SkipList.Contains(patchFullName + "::" + ((MemberReference)field).Name) || !MatchingConditionals((ICustomAttributeProvider)(object)field, Module))
			{
				return;
			}
			((MemberReference)field).Name = Extensions.GetPatchName((MemberReference)(object)field);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModReplace"))
			{
				FieldDefinition val = Extensions.FindField(targetType, ((MemberReference)field).Name);
				if (val != null)
				{
					targetType.Fields.Remove(val);
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			FieldDefinition val2 = Extensions.FindField(targetType, ((MemberReference)field).Name);
			Enumerator<CustomAttribute> enumerator;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModIgnore") && val2 != null)
			{
				enumerator = field.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
						{
							val2.CustomAttributes.Add(Extensions.Clone(current));
						}
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			}
			if (val2 == null)
			{
				val2 = new FieldDefinition(((MemberReference)field).Name, field.Attributes, ((FieldReference)field).FieldType);
				val2.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				val2.InitialValue = field.InitialValue;
				if (field.HasConstant)
				{
					val2.Constant = field.Constant;
				}
				targetType.Fields.Add(val2);
			}
			enumerator = field.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current2 = enumerator.Current;
					val2.CustomAttributes.Add(Extensions.Clone(current2));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual MethodDefinition PatchMethod(TypeDefinition targetType, MethodDefinition method)
		{
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_049f: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bb: Expected O, but got Unknown
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0504: Unknown result type (might be due to invalid IL or missing references)
			//IL_0511: Unknown result type (might be due to invalid IL or missing references)
			//IL_0564: Unknown result type (might be due to invalid IL or missing references)
			//IL_0569: Unknown result type (might be due to invalid IL or missing references)
			//IL_0453: Unknown result type (might be due to invalid IL or missing references)
			//IL_0458: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Expected O, but got Unknown
			//IL_05a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_069a: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a1: Expected O, but got Unknown
			//IL_06be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0630: Unknown result type (might be due to invalid IL or missing references)
			//IL_0635: Unknown result type (might be due to invalid IL or missing references)
			//IL_0676: Unknown result type (might be due to invalid IL or missing references)
			//IL_0680: Expected O, but got Unknown
			if (((MemberReference)method).Name.StartsWith("orig_") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginal"))
			{
				return null;
			}
			if (!AllowedSpecialName(method, targetType) || !MatchingConditionals((ICustomAttributeProvider)(object)method, Module))
			{
				return null;
			}
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)targetType);
			if (SkipList.Contains(Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false)))
			{
				return null;
			}
			((MemberReference)method).Name = Extensions.GetPatchName((MemberReference)(object)method);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor"))
			{
				if (!method.IsSpecialName && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginalName"))
				{
					CustomAttribute val = new CustomAttribute(GetMonoModOriginalNameCtor());
					val.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)("orig_" + ((MemberReference)method).Name)));
					method.CustomAttributes.Add(val);
				}
				((MemberReference)method).Name = (method.IsStatic ? ".cctor" : ".ctor");
				method.IsSpecialName = true;
				method.IsRuntimeSpecialName = true;
			}
			MethodDefinition val2 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false), true);
			MethodDefinition obj = method;
			string text = patchFullName;
			MethodDefinition val3 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)obj, method.GetOriginalName(), text, true, false), true);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModIgnore"))
			{
				if (val2 != null)
				{
					Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val2.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				return null;
			}
			if (val2 == null && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModNoNew"))
			{
				return null;
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModRemove"))
			{
				if (val2 != null)
				{
					targetType.Methods.Remove(val2);
				}
				return null;
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModReplace"))
			{
				if (val2 != null)
				{
					val2.CustomAttributes.Clear();
					val2.Attributes = method.Attributes;
					val2.IsPInvokeImpl = method.IsPInvokeImpl;
					val2.ImplAttributes = method.ImplAttributes;
				}
			}
			else if (val2 != null && val3 == null)
			{
				val3 = Extensions.Clone(val2, (MethodDefinition)null);
				((MemberReference)val3).Name = method.GetOriginalName();
				val3.Attributes = (MethodAttributes)(val2.Attributes & 0xF7FF & 0xEFFF);
				((MemberReference)val3).MetadataToken = GetMetadataToken((TokenType)100663296);
				val3.IsVirtual = false;
				val3.Overrides.Clear();
				Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodReference current2 = enumerator2.Current;
						val3.Overrides.Add(current2);
					}
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
				val3.CustomAttributes.Add(new CustomAttribute(GetMonoModOriginalCtor()));
				MethodDefinition val4 = Extensions.FindMethod(method.DeclaringType, Extensions.GetID((MethodReference)(object)method, method.GetOriginalName(), (string)null, true, false), true);
				if (val4 != null)
				{
					Enumerator<CustomAttribute> enumerator = val4.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current3 = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName))
							{
								val3.CustomAttributes.Add(Extensions.Clone(current3));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				targetType.Methods.Add(val3);
			}
			if (val3 != null && method.IsConstructor && method.IsStatic && method.HasBody && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor"))
			{
				Collection<Instruction> instructions = method.Body.Instructions;
				ILProcessor iLProcessor = method.Body.GetILProcessor();
				iLProcessor.InsertBefore(instructions[instructions.Count - 1], iLProcessor.Create(OpCodes.Call, (MethodReference)(object)val3));
			}
			if (val2 != null)
			{
				val2.Body = Extensions.Clone(method.Body, val2);
				val2.IsManaged = method.IsManaged;
				val2.IsIL = method.IsIL;
				val2.IsNative = method.IsNative;
				val2.PInvokeInfo = method.PInvokeInfo;
				val2.IsPreserveSig = method.IsPreserveSig;
				val2.IsInternalCall = method.IsInternalCall;
				val2.IsPInvokeImpl = method.IsPInvokeImpl;
				Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current4 = enumerator.Current;
						val2.CustomAttributes.Add(Extensions.Clone(current4));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				method = val2;
			}
			else
			{
				MethodDefinition val5 = new MethodDefinition(((MemberReference)method).Name, method.Attributes, Module.TypeSystem.Void);
				((MemberReference)val5).MetadataToken = GetMetadataToken((TokenType)100663296);
				((MethodReference)val5).CallingConvention = ((MethodReference)method).CallingConvention;
				((MethodReference)val5).ExplicitThis = ((MethodReference)method).ExplicitThis;
				((MethodReference)val5).MethodReturnType = ((MethodReference)method).MethodReturnType;
				val5.Attributes = method.Attributes;
				val5.ImplAttributes = method.ImplAttributes;
				val5.SemanticsAttributes = method.SemanticsAttributes;
				val5.DeclaringType = targetType;
				((MethodReference)val5).ReturnType = ((MethodReference)method).ReturnType;
				val5.Body = Extensions.Clone(method.Body, val5);
				val5.PInvokeInfo = method.PInvokeInfo;
				val5.IsPInvokeImpl = method.IsPInvokeImpl;
				Enumerator<GenericParameter> enumerator3 = ((MethodReference)method).GenericParameters.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						GenericParameter current5 = enumerator3.Current;
						((MethodReference)val5).GenericParameters.Add(Extensions.Clone(current5));
					}
				}
				finally
				{
					((IDisposable)enumerator3).Dispose();
				}
				Enumerator<ParameterDefinition> enumerator4 = ((MethodReference)method).Parameters.GetEnumerator();
				try
				{
					while (enumerator4.MoveNext())
					{
						ParameterDefinition current6 = enumerator4.Current;
						((MethodReference)val5).Parameters.Add(Extensions.Clone(current6));
					}
				}
				finally
				{
					((IDisposable)enumerator4).Dispose();
				}
				Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current7 = enumerator.Current;
						val5.CustomAttributes.Add(Extensions.Clone(current7));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodReference current8 = enumerator2.Current;
						val5.Overrides.Add(current8);
					}
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				targetType.Methods.Add(val5);
				method = val5;
			}
			if (val3 != null)
			{
				CustomAttribute val6 = new CustomAttribute(GetMonoModOriginalNameCtor());
				val6.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)((MemberReference)val3).Name));
				method.CustomAttributes.Add(val6);
			}
			return method;
		}

		public virtual void PatchRefs()
		{
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			if (!UpgradeMSCORLIB.HasValue)
			{
				Version fckUnity = new Version(2, 0, 5, 0);
				UpgradeMSCORLIB = ((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference x) => x.Version == fckUnity);
			}
			if (UpgradeMSCORLIB.Value)
			{
				List<AssemblyNameReference> list = new List<AssemblyNameReference>();
				for (int i = 0; i < Module.AssemblyReferences.Count; i++)
				{
					AssemblyNameReference val = Module.AssemblyReferences[i];
					if (val.Name == "mscorlib")
					{
						list.Add(val);
					}
				}
				if (list.Count > 1)
				{
					AssemblyNameReference val2 = list.OrderByDescending((AssemblyNameReference x) => x.Version).First();
					if (DependencyCache.TryGetValue(val2.FullName, out var value))
					{
						for (int j = 0; j < Module.AssemblyReferences.Count; j++)
						{
							AssemblyNameReference val3 = Module.AssemblyReferences[j];
							if (val3.Name == "mscorlib" && val2.Version > val3.Version)
							{
								LogVerbose("[PatchRefs] Removing and relinking duplicate mscorlib: " + val3.Version);
								RelinkModuleMap[val3.FullName] = value;
								Module.AssemblyReferences.RemoveAt(j);
								j--;
							}
						}
					}
				}
			}
			Enumerator<TypeDefinition> enumerator = Module.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PatchRefsInType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchRefs(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PatchRefsInType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchRefsInType(TypeDefinition type)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Expected O, but got Unknown
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Expected O, but got Unknown
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Expected O, but got Unknown
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Expected O, but got Unknown
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Expected O, but got Unknown
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0308: Expected O, but got Unknown
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Expected O, but got Unknown
			LogVerbose($"[VERBOSE] [PatchRefsInType] Patching refs in {type}");
			if (type.BaseType != null)
			{
				type.BaseType = Extensions.Relink(type.BaseType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			for (int i = 0; i < ((TypeReference)type).GenericParameters.Count; i++)
			{
				((TypeReference)type).GenericParameters[i] = Extensions.Relink(((TypeReference)type).GenericParameters[i], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			for (int j = 0; j < type.Interfaces.Count; j++)
			{
				InterfaceImplementation obj = type.Interfaces[j];
				InterfaceImplementation val = new InterfaceImplementation(Extensions.Relink(obj.InterfaceType, new Relinker(Relinker), (IGenericParameterProvider)(object)type));
				Enumerator<CustomAttribute> enumerator = obj.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						val.CustomAttributes.Add(Extensions.Relink(current, new Relinker(Relinker), (IGenericParameterProvider)(object)type));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				type.Interfaces[j] = val;
			}
			for (int k = 0; k < type.CustomAttributes.Count; k++)
			{
				type.CustomAttributes[k] = Extensions.Relink(type.CustomAttributes[k], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					PropertyDefinition current2 = enumerator2.Current;
					((PropertyReference)current2).PropertyType = Extensions.Relink(((PropertyReference)current2).PropertyType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int l = 0; l < current2.CustomAttributes.Count; l++)
					{
						current2.CustomAttributes[l] = Extensions.Relink(current2.CustomAttributes[l], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					EventDefinition current3 = enumerator3.Current;
					((EventReference)current3).EventType = Extensions.Relink(((EventReference)current3).EventType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int m = 0; m < current3.CustomAttributes.Count; m++)
					{
						current3.CustomAttributes[m] = Extensions.Relink(current3.CustomAttributes[m], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodDefinition current4 = enumerator4.Current;
					PatchRefsInMethod(current4);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator5.MoveNext())
				{
					FieldDefinition current5 = enumerator5.Current;
					((FieldReference)current5).FieldType = Extensions.Relink(((FieldReference)current5).FieldType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int n = 0; n < current5.CustomAttributes.Count; n++)
					{
						current5.CustomAttributes[n] = Extensions.Relink(current5.CustomAttributes[n], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator5).Dispose();
			}
			for (int num = 0; num < type.NestedTypes.Count; num++)
			{
				PatchRefsInType(type.NestedTypes[num]);
			}
		}

		public virtual void PatchRefsInMethod(MethodDefinition method)
		{
			//IL_0030: Unknown result t

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

Decompiled 6 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();
			}
		}
	}
}