Decompiled source of MAFixes v1.0.6

BepInEx/plugins/MAFixes/MAFixes.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: AssemblyTitle("MAFixes")]
[assembly: AssemblyDescription("Optional R.E.P.O. compatibility fixes")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyFileVersion("1.0.6.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8")]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("1.0.6.0")]
namespace MAFixes;

public static class DeadEntryPruner
{
	public static int RemoveInvalid(IList entries, Predicate<object> invalid)
	{
		if (entries == null)
		{
			return 0;
		}
		int num = 0;
		for (int num2 = entries.Count - 1; num2 >= 0; num2--)
		{
			object obj = entries[num2];
			if (obj == null || invalid(obj))
			{
				entries.RemoveAt(num2);
				num++;
			}
		}
		return num;
	}
}
internal static class InventoryHudPatch
{
	private static readonly FieldInfo Children = AccessTools.Field(typeof(SemiUI), "allChildren");

	private static readonly FieldInfo Exclusions = AccessTools.Field(typeof(SemiUI), "doNotDisable");

	internal static void Install(Harmony harmony)
	{
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Expected O, but got Unknown
		MethodInfo methodInfo = AccessTools.Method(typeof(SemiUI), "AllChildrenSetActive", new Type[1] { typeof(bool) }, (Type[])null);
		if (methodInfo == null || Children == null || Exclusions == null || Children.FieldType != typeof(List<GameObject>) || Exclusions.FieldType != typeof(List<GameObject>))
		{
			Plugin.Log.LogWarning((object)"Inventory HUD: unsupported game API; module skipped.");
			return;
		}
		try
		{
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(InventoryHudPatch), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)"Inventory HUD: stale child-reference repair installed.");
		}
		catch (Exception ex)
		{
			harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)0, "ma.repo.mafixes");
			Plugin.Log.LogWarning((object)("Inventory HUD repair could not be installed: " + ex));
		}
	}

	private static void Prefix(SemiUI __instance)
	{
		if (!(__instance is InventoryUI))
		{
			return;
		}
		Transform transform = ((Component)__instance).transform;
		List<GameObject> list = Children.GetValue(__instance) as List<GameObject>;
		bool flag = list == null || list.Count != transform.childCount;
		if (!flag)
		{
			for (int i = 0; i < list.Count; i++)
			{
				if ((Object)(object)list[i] == (Object)null || (Object)(object)list[i].transform.parent != (Object)(object)transform)
				{
					flag = true;
					break;
				}
			}
		}
		if (flag)
		{
			if (list == null)
			{
				list = new List<GameObject>();
			}
			else
			{
				list.Clear();
			}
			for (int j = 0; j < transform.childCount; j++)
			{
				Transform child = transform.GetChild(j);
				if ((Object)(object)child != (Object)null)
				{
					list.Add(((Component)child).gameObject);
				}
			}
			Children.SetValue(__instance, list);
			if (Plugin.DebugLogging.Value)
			{
				Plugin.Log.LogInfo((object)"Inventory HUD: refreshed immediate child references.");
			}
		}
		if (!(Exclusions.GetValue(__instance) is List<GameObject> list2))
		{
			Exclusions.SetValue(__instance, new List<GameObject>());
			return;
		}
		for (int num = list2.Count - 1; num >= 0; num--)
		{
			if ((Object)(object)list2[num] == (Object)null)
			{
				list2.RemoveAt(num);
			}
		}
	}
}
internal static class MoreUpgradesCosmeticsPatch
{
	private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

	private static FieldInfo ledObject;

	private static FieldInfo ledMaterial;

	private static Type infoType;

	private static readonly Predicate<object> InvalidEntry = IsInvalid;

	internal static void Install(Harmony harmony)
	{
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f5: Expected O, but got Unknown
		//IL_01f5: Expected O, but got Unknown
		if (!Chainloader.PluginInfos.TryGetValue("bulletbot.moreupgrades", out var value))
		{
			Plugin.Log.LogInfo((object)"MoreUpgrades: not installed; optional module skipped.");
			return;
		}
		Assembly assembly = ((object)value.Instance).GetType().Assembly;
		Type type = assembly.GetType("MoreUpgrades.Plugin+<>c__DisplayClass17_0");
		if (type != null && type.GetMethod("__MA_PruneDeadCosmeticLeds", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) != null)
		{
			Plugin.Log.LogInfo((object)"MoreUpgrades: previous direct LED repair already present; duplicate hook skipped. Reinstall stock MoreUpgrades to use this module instead.");
			return;
		}
		if (value.Metadata.Version.ToString() != "1.7.3")
		{
			Plugin.Log.LogWarning((object)string.Concat("MoreUpgrades: only 1.7.3 is verified; optional module skipped for ", value.Metadata.Version, "."));
			return;
		}
		MethodInfo methodInfo = ((type == null) ? null : type.GetMethod("<Awake>b__14", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
		infoType = assembly.GetType("MoreUpgrades.Classes.CosmeticLEDInfo");
		ledObject = ((infoType == null) ? null : infoType.GetField("ledObject", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
		ledMaterial = ((infoType == null) ? null : infoType.GetField("ledMaterial", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
		if (methodInfo == null || methodInfo.ReturnType != typeof(void) || methodInfo.GetParameters().Length != 0 || ledObject == null || ledObject.FieldType != typeof(GameObject) || ledMaterial == null || ledMaterial.FieldType != typeof(Material))
		{
			Plugin.Log.LogWarning((object)"MoreUpgrades: unrecognized cosmetics tracker API; module skipped.");
			return;
		}
		try
		{
			FindListStore(PatchProcessor.GetOriginalInstructions((MethodBase)methodInfo, (ILGenerator)null).ToList());
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(MoreUpgradesCosmeticsPatch), "Prefix", (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(MoreUpgradesCosmeticsPatch), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)"MoreUpgrades: cosmetics tracker LED lifetime repair installed. Valid indicators and owned upgrades retained.");
		}
		catch (Exception ex)
		{
			harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)0, "ma.repo.mafixes");
			Plugin.Log.LogWarning((object)("MoreUpgrades repair could not be installed: " + ex));
		}
	}

	private static int FindListStore(List<CodeInstruction> code)
	{
		int num = -1;
		for (int i = 0; i + 1 < code.Count; i++)
		{
			MethodInfo methodInfo = code[i].operand as MethodInfo;
			if (methodInfo == null || methodInfo.Name != "GetVariable" || !methodInfo.IsGenericMethod)
			{
				continue;
			}
			Type type = methodInfo.GetGenericArguments()[0];
			if (type.IsGenericType && !(type.GetGenericTypeDefinition() != typeof(List<>)) && !(type.GetGenericArguments()[0] != infoType))
			{
				if (num >= 0 || code[i + 1].opcode != OpCodes.Stloc_1 || i + 2 >= code.Count || code[i + 2].labels.Count != 0 || code[i + 2].blocks.Count != 0)
				{
					throw new InvalidOperationException("Unsupported cosmetics tracker instruction layout.");
				}
				num = i + 1;
			}
		}
		if (num < 0)
		{
			throw new InvalidOperationException("Cosmetic LED list assignment not found.");
		}
		return num;
	}

	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Expected O, but got Unknown
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Expected O, but got Unknown
		List<CodeInstruction> list = instructions.ToList();
		int num = FindListStore(list);
		list.InsertRange(num + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2]
		{
			new CodeInstruction(OpCodes.Ldloc_1, (object)null),
			new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(MoreUpgradesCosmeticsPatch), "Prune", (Type[])null, (Type[])null))
		});
		return list;
	}

	private static bool Prefix()
	{
		if ((Object)(object)PlayerController.instance != (Object)null && (Object)(object)PlayerController.instance.playerAvatarScript != (Object)null)
		{
			return (Object)(object)MapToolController.instance != (Object)null;
		}
		return false;
	}

	private static bool IsInvalid(object entry)
	{
		if (!infoType.IsInstanceOfType(entry))
		{
			return false;
		}
		object? value = ledObject.GetValue(entry);
		if (!((Object)((value is Object) ? value : null) == (Object)null))
		{
			object? value2 = ledMaterial.GetValue(entry);
			return (Object)((value2 is Object) ? value2 : null) == (Object)null;
		}
		return true;
	}

	private static void Prune(IList entries)
	{
		int num = DeadEntryPruner.RemoveInvalid(entries, InvalidEntry);
		if (num != 0 && Plugin.DebugLogging.Value)
		{
			Plugin.Log.LogInfo((object)("MoreUpgrades: removed " + num + " stale cosmetic LED reference(s)."));
		}
	}
}
internal static class UpgradeLabelPatch
{
	internal static void Install(Harmony harmony)
	{
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Expected O, but got Unknown
		MethodInfo methodInfo = AccessTools.Method(typeof(StatsUI), "GetUpgradeDisplayName", new Type[1] { typeof(string) }, (Type[])null);
		if (methodInfo == null || methodInfo.ReturnType != typeof(string))
		{
			Plugin.Log.LogWarning((object)"Upgrade labels: unsupported display API; skipped.");
			return;
		}
		try
		{
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(UpgradeLabelPatch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)"Upgrade labels: IHM prefix cleanup installed; upgrade rows and numbers retained.");
		}
		catch (Exception ex)
		{
			harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)0, "ma.repo.mafixes");
			Plugin.Log.LogWarning((object)("Upgrade label cleanup could not be installed: " + ex));
		}
	}

	private static void Postfix(ref string __result)
	{
		if (Plugin.CleanIhmPrefix != null && Plugin.CleanIhmPrefix.Value)
		{
			__result = UpgradeLabelRules.CleanPrefix(__result);
		}
	}
}
internal static class SanitySignPatch
{
	internal static void Install(Harmony harmony)
	{
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Expected O, but got Unknown
		if (!Chainloader.PluginInfos.TryGetValue("kinglir.paranoia", out var value))
		{
			return;
		}
		Type type = ((object)value.Instance).GetType().Assembly.GetType("Paranoia.SanityBanner");
		MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "Tick", new Type[3]
		{
			typeof(bool),
			typeof(float),
			typeof(float)
		}, (Type[])null));
		if (methodInfo == null || !methodInfo.IsStatic || methodInfo.ReturnType != typeof(void))
		{
			Plugin.Log.LogWarning((object)"Sanity sign: unrecognized banner API; skipped.");
			return;
		}
		try
		{
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(SanitySignPatch), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)"Sanity sign: visual banner toggle installed.");
		}
		catch (Exception ex)
		{
			harmony.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)0, "ma.repo.mafixes");
			Plugin.Log.LogWarning((object)("Sanity sign toggle could not be installed: " + ex));
		}
	}

	private static bool Prefix()
	{
		if (Plugin.HideSanity != null)
		{
			return !Plugin.HideSanity.Value;
		}
		return true;
	}
}
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInPlugin("ma.repo.mafixes", "MAFixes", "1.0.6")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	public const string Guid = "ma.repo.mafixes";

	public const string Version = "1.0.6";

	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> DebugLogging;

	internal static ConfigEntry<bool> HideSanity;

	internal static ConfigEntry<bool> CleanIhmPrefix;

	private Harmony harmony;

	private void Awake()
	{
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "Inventory HUD", true, "Refresh stale inventory HUD child references after slot UI rebuilds. Does not add slots or change items.");
		ConfigEntry<bool> val2 = ((BaseUnityPlugin)this).Config.Bind<bool>("Fixes", "MoreUpgrades cosmetics tracker", true, "Repair destroyed cosmetic tracker LED references in MoreUpgrades 1.7.3. Optional: MoreUpgrades is not installed automatically.");
		DebugLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "Log repairs", false, "Log a message when stale references are actually removed or rebuilt. Does not suppress errors.");
		HideSanity = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "Hide Sanity sign", true, "Hide only Paranoia's Sanity banner. Its sanity and hallucination mechanics remain active.");
		CleanIhmPrefix = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "Clean IHM prefix", true, "Remove only the IHM_ prefix from upgrade display names. Keep all upgrade rows, levels and effects.");
		harmony = new Harmony("ma.repo.mafixes");
		if (val.Value)
		{
			ConfigEntry<bool> val3 = default(ConfigEntry<bool>);
			if (Chainloader.PluginInfos.TryGetValue("local.repo.inventoryuirepair", out var value) && (Object)(object)value.Instance != (Object)null && value.Instance.Config.TryGetEntry<bool>("General", "Repair inventory UI", ref val3) && val3.Value)
			{
				Log.LogInfo((object)"Inventory HUD: existing standalone Inventory UI Repair is active; duplicate hook skipped.");
			}
			else
			{
				InventoryHudPatch.Install(harmony);
			}
		}
		if (val2.Value)
		{
			MoreUpgradesCosmeticsPatch.Install(harmony);
		}
		UpgradeLabelPatch.Install(harmony);
		SanitySignPatch.Install(harmony);
		Log.LogInfo((object)"MAFixes 1.0.6 loaded.");
	}

	private void OnDestroy()
	{
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
	}
}
public static class UpgradeLabelRules
{
	private static readonly Regex Prefix = new Regex("^(?<lead>[ \\t\\u00a0]*(?:<[^>\\r\\n]*>[ \\t\\u00a0]*)*)I[ \\t\\u00a0]*H[ \\t\\u00a0]*M[ \\t\\u00a0]*_[ \\t\\u00a0]*", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);

	private static readonly Regex Tags = new Regex("<[^>\\r\\n]*>", RegexOptions.Compiled);

	public static string CleanPrefix(string label)
	{
		if (string.IsNullOrEmpty(label))
		{
			return label;
		}
		string text = Prefix.Replace(label, "${lead}", 1);
		if (!string.IsNullOrWhiteSpace(Tags.Replace(text, "")))
		{
			return text;
		}
		return label;
	}
}