Decompiled source of Ammo Count by aedenthorn Fixed v0.5.1

AmmoCount.dll

Decompiled a week 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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+9ca93ba62fa747e19cfe725051594a663b02546c")]
[assembly: AssemblyVersion("1.0.0.0")]
public class AedenthornUtils
{
	public static bool IgnoreKeyPresses(bool extra = false)
	{
		if (!extra)
		{
			if (!((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !Minimap.IsOpen() && !Console.IsVisible() && !TextInput.IsVisible() && !ZNet.instance.InPasswordDialog())
			{
				Chat instance = Chat.instance;
				if (instance == null)
				{
					return false;
				}
				return instance.HasFocus();
			}
			return true;
		}
		if (!((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !Minimap.IsOpen() && !Console.IsVisible() && !TextInput.IsVisible() && !ZNet.instance.InPasswordDialog())
		{
			Chat instance2 = Chat.instance;
			if ((instance2 == null || !instance2.HasFocus()) && !StoreGui.IsVisible() && !InventoryGui.IsVisible() && !Menu.IsVisible())
			{
				TextViewer instance3 = TextViewer.instance;
				if (instance3 == null)
				{
					return false;
				}
				return instance3.IsVisible();
			}
		}
		return true;
	}

	public static bool CheckKeyDown(string value)
	{
		try
		{
			return Input.GetKeyDown(value.ToLower());
		}
		catch
		{
			return false;
		}
	}

	public static bool CheckKeyHeld(string value, bool req = true)
	{
		try
		{
			return Input.GetKey(value.ToLower());
		}
		catch
		{
			return !req;
		}
	}
}
namespace AmmoCount;

[BepInPlugin("aedenthorn.AmmoCount", "Ammo Count", "0.5.1")]
public class BepInExPlugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(HotkeyBar), "Update")]
	public static class HotkeyBar_Update_Patch
	{
		public static void Postfix(HotkeyBar __instance, List<ItemData> ___m_items)
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Expected O, but got Unknown
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Expected O, but got Unknown
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: 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_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: 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_026d: 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_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_029e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			if (!modEnabled.Value || !Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				return;
			}
			if (elementsAmmo == null)
			{
				elementsAmmo = ResolveElementsField(((object)__instance).GetType());
				if (elementsAmmo == null)
				{
					Dbgl("AmmoCount: could not resolve HotkeyBar elements field (runtime)", (LogLevel)32);
					return;
				}
			}
			IEnumerable<object> enumerable = elementsAmmo.GetValue(__instance) as IEnumerable<object>;
			if (reset)
			{
				currentFont = GetFont(ammoStringFontName.Value, ammoStringSize.Value);
			}
			using (IEnumerator<object> enumerator = enumerable.GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					if (enumerator.Current != null)
					{
						Transform val = ((GameObject)AccessTools.Field(enumerator.Current.GetType(), "m_go").GetValue(enumerator.Current)).transform.Find("AmmoCount");
						if ((Object)(object)val != (Object)null && (reset || !(bool)AccessTools.Field(enumerator.Current.GetType(), "m_used").GetValue(enumerator.Current)))
						{
							Object.Destroy((Object)(object)((Component)val).gameObject);
						}
					}
				}
			}
			reset = false;
			for (int i = 0; i < ___m_items.Count(); i++)
			{
				int x = ___m_items[i].m_gridPos.x;
				if (x < 0 || x >= enumerable.Count() || enumerable.ElementAt(x) == null)
				{
					continue;
				}
				GameObject val2 = (GameObject)AccessTools.Field(enumerable.ElementAt(x).GetType(), "m_go").GetValue(enumerable.ElementAt(x));
				Transform val3 = val2.transform.Find("AmmoCount");
				if (val3 == null)
				{
					GameObject val4 = new GameObject("AmmoCount");
					val4.transform.SetParent(val2.transform);
					val4.AddComponent<RectTransform>().anchoredPosition = Vector2.zero;
					val3 = val4.transform;
					GameObject val5 = new GameObject("Text");
					val5.transform.SetParent(val4.transform);
					TextMeshProUGUI val6 = val5.AddComponent<TextMeshProUGUI>();
					val5.GetComponent<RectTransform>().anchoredPosition = ammoStringPosition.Value;
					val5.GetComponent<RectTransform>().sizeDelta = new Vector2(90f, 90f);
					((TMP_Text)val6).font = currentFont;
					((TMP_Text)val6).fontSize = ammoStringSize.Value;
					((TMP_Text)val6).fontStyle = ammoStringFontStyle.Value;
					((TMP_Text)val6).alignment = ammoStringAlignment.Value;
					((Graphic)val6).color = ammoStringColor.Value;
					if (showIcon.Value)
					{
						GameObject val7 = new GameObject("Icon");
						val7.transform.SetParent(val4.transform);
						val7.AddComponent<Image>();
						val7.GetComponent<RectTransform>().anchoredPosition = iconPosition.Value;
						val7.GetComponent<RectTransform>().sizeDelta = iconSize.Value;
					}
				}
				CheckAmmo(___m_items[i], ((Component)val3).gameObject);
			}
		}

		public static void CheckAmmo(ItemData itemData, GameObject go)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			if (string.IsNullOrEmpty(itemData.m_shared.m_ammoType) || (int)itemData.m_shared.m_itemType == 9)
			{
				go.SetActive(false);
				return;
			}
			ItemData val = FindAmmo(itemData);
			if (val == null)
			{
				go.SetActive(false);
				return;
			}
			go.SetActive(true);
			if (!string.IsNullOrEmpty(ammoStringFormat.Value))
			{
				((TMP_Text)((Component)go.transform.Find("Text")).GetComponent<TextMeshProUGUI>()).text = ammoStringFormat.Value.Replace("{amount}", val.m_stack.ToString()).Replace("{name}", Localization.instance.Localize(val.m_shared.m_name));
			}
			if (showIcon.Value)
			{
				((Component)go.transform.Find("Icon")).GetComponent<Image>().sprite = val.GetIcon();
			}
		}

		public static ItemData FindAmmo(ItemData weapon)
		{
			if (string.IsNullOrEmpty(weapon.m_shared.m_ammoType))
			{
				return null;
			}
			ItemData val = ((Humanoid)Player.m_localPlayer).GetAmmoItem();
			if (val != null && (!((Humanoid)Player.m_localPlayer).GetInventory().ContainsItem(val) || val.m_shared.m_ammoType != weapon.m_shared.m_ammoType))
			{
				val = null;
			}
			if (val == null)
			{
				val = ((Humanoid)Player.m_localPlayer).GetInventory().GetAmmoItem(weapon.m_shared.m_ammoType, (string)null);
			}
			return val;
		}
	}

	[HarmonyPatch(typeof(Terminal), "InputText")]
	public static class InputText_Patch
	{
		public static bool Prefix(Terminal __instance)
		{
			if (!modEnabled.Value)
			{
				return true;
			}
			string text = ((TMP_InputField)__instance.m_input).text;
			if (text.ToLower().Equals(typeof(BepInExPlugin).Namespace.ToLower() + " reset"))
			{
				((BaseUnityPlugin)context).Config.Reload();
				((BaseUnityPlugin)context).Config.Save();
				currentFont = GetFont(ammoStringFontName.Value, ammoStringSize.Value);
				reset = true;
				Traverse.Create((object)__instance).Method("AddString", new object[1] { text }).GetValue();
				Traverse.Create((object)__instance).Method("AddString", new object[1] { ((BaseUnityPlugin)context).Info.Metadata.Name + " config reloaded" }).GetValue();
				return false;
			}
			return true;
		}
	}

	public static BepInExPlugin context;

	public Harmony harmony;

	public static ConfigEntry<bool> modEnabled;

	public static ConfigEntry<bool> isDebug;

	public static ConfigEntry<int> nexusID;

	public static ConfigEntry<bool> showIcon;

	public static ConfigEntry<Vector2> iconPosition;

	public static ConfigEntry<Vector2> iconSize;

	public static ConfigEntry<string> ammoStringFormat;

	public static ConfigEntry<int> ammoStringSize;

	public static ConfigEntry<string> ammoStringFontName;

	public static ConfigEntry<FontStyles> ammoStringFontStyle;

	public static ConfigEntry<TextAlignmentOptions> ammoStringAlignment;

	public static ConfigEntry<Color> ammoStringColor;

	public static ConfigEntry<Vector2> ammoStringPosition;

	public static FieldInfo elementsAmmo;

	public static TMP_FontAsset currentFont;

	public static bool reset = true;

	public static void Dbgl(object obj, LogLevel level = (LogLevel)32)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		if (isDebug.Value)
		{
			((BaseUnityPlugin)context).Logger.Log(level, obj);
		}
	}

	public void Awake()
	{
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0339: Unknown result type (might be due to invalid IL or missing references)
		//IL_0343: Expected O, but got Unknown
		context = this;
		modEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable this mod");
		isDebug = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "IsDebug", true, "Show debug messages");
		nexusID = ((BaseUnityPlugin)this).Config.Bind<int>("General", "NexusID", 2273, "Nexus mod ID for updates");
		showIcon = ((BaseUnityPlugin)this).Config.Bind<bool>("Options", "ShowIcon", true, "Show Ammo Icon");
		iconPosition = ((BaseUnityPlugin)this).Config.Bind<Vector2>("Options", "IconPosition", new Vector2(0f, 32f), "Icon position");
		iconSize = ((BaseUnityPlugin)this).Config.Bind<Vector2>("Options", "IconSize", new Vector2(20f, 20f), "Icon Size");
		ammoStringFormat = ((BaseUnityPlugin)this).Config.Bind<string>("Options", "AmmoTextFormat", "{amount}", "Ammo string. Use {amount} and/or {name}");
		ammoStringSize = ((BaseUnityPlugin)this).Config.Bind<int>("Options", "AmmoTextSize", 16, "Ammo count size.");
		ammoStringFontName = ((BaseUnityPlugin)this).Config.Bind<string>("Options", "AmmoStringFontName", "Valheim-AveriaSansLibre", "Ammo count font");
		ammoStringFontStyle = ((BaseUnityPlugin)this).Config.Bind<FontStyles>("Options", "AmmoTextFontStyle", (FontStyles)1, "Ammo count font style");
		ammoStringAlignment = ((BaseUnityPlugin)this).Config.Bind<TextAlignmentOptions>("Options", "AmmoTextAlignment", (TextAlignmentOptions)260, "Ammo count alignment");
		ammoStringColor = ((BaseUnityPlugin)this).Config.Bind<Color>("Options", "AmmoTextColor", new Color(1f, 1f, 1f, 1f), "Ammo count color");
		ammoStringPosition = ((BaseUnityPlugin)this).Config.Bind<Vector2>("Options", "AmmoTextPosition", new Vector2(-6f, -4f), "Ammo count position offset");
		elementsAmmo = AccessTools.Field(typeof(HotkeyBar), "m_elements");
		if (elementsAmmo == null)
		{
			elementsAmmo = ResolveElementsField(typeof(HotkeyBar));
			if (elementsAmmo == null)
			{
				Dbgl("AmmoCount: could not resolve HotkeyBar elements field", (LogLevel)32);
			}
		}
		ammoStringFontName.SettingChanged += SettingChanged;
		showIcon.SettingChanged += SettingChanged;
		iconPosition.SettingChanged += SettingChanged;
		iconSize.SettingChanged += SettingChanged;
		ammoStringFormat.SettingChanged += SettingChanged;
		ammoStringSize.SettingChanged += SettingChanged;
		ammoStringFontStyle.SettingChanged += SettingChanged;
		ammoStringAlignment.SettingChanged += SettingChanged;
		ammoStringColor.SettingChanged += SettingChanged;
		ammoStringPosition.SettingChanged += SettingChanged;
		harmony = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
		harmony.PatchAll();
	}

	public static FieldInfo ResolveElementsField(Type hotkeyBarType)
	{
		try
		{
			string[] array = new string[5] { "m_elements", "m_elementsList", "m_elementsArray", "m_elementsAmmo", "m_elements2" };
			foreach (string text in array)
			{
				FieldInfo fieldInfo = AccessTools.Field(hotkeyBarType, text);
				if (fieldInfo != null)
				{
					return fieldInfo;
				}
			}
			FieldInfo[] fields = hotkeyBarType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (FieldInfo fieldInfo2 in fields)
			{
				Type fieldType = fieldInfo2.FieldType;
				Type type = null;
				if (fieldType.IsArray)
				{
					type = fieldType.GetElementType();
				}
				else if (fieldType.IsGenericType)
				{
					type = fieldType.GetGenericArguments().FirstOrDefault();
				}
				if (!(type == null) && type.GetField("m_go", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null)
				{
					Dbgl("AmmoCount: resolved elements field '" + fieldInfo2.Name + "' with element type '" + type.Name + "'", (LogLevel)16);
					return fieldInfo2;
				}
			}
		}
		catch (Exception arg)
		{
			Dbgl($"ResolveElementsField error: {arg}", (LogLevel)2);
		}
		return null;
	}

	public void SettingChanged(object sender, EventArgs e)
	{
		reset = true;
	}

	public void OnDestroy()
	{
		Dbgl("Destroying plugin", (LogLevel)32);
		Harmony obj = harmony;
		if (obj != null)
		{
			obj.UnpatchAll((string)null);
		}
	}

	public static TMP_FontAsset GetFont(string fontName, int fontSize)
	{
		try
		{
			TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
			foreach (TMP_FontAsset val in array)
			{
				Dbgl("got font " + ((Object)val).name, (LogLevel)32);
				if (((Object)val).name == fontName)
				{
					Dbgl("Matches", (LogLevel)32);
					return val;
				}
			}
		}
		catch
		{
		}
		return currentFont;
	}
}