Decompiled source of AmmoReticle v1.0.0

AmmoReticle.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("AmmoReticle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Azumatt")]
[assembly: AssemblyProduct("AmmoReticle")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[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 AmmoReticle
{
	[HarmonyPatch(typeof(Hud), "Awake")]
	internal static class AddHudComponents
	{
		private static void Postfix(Hud __instance)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			Transform parent = ((Component)__instance.m_crosshair).transform.parent;
			GameObject val = new GameObject("AmmoIcon", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val.transform.SetParent(parent, false);
			AmmoReticlePlugin.AmmoIcon = val.GetComponent<Image>();
			((Graphic)AmmoReticlePlugin.AmmoIcon).rectTransform.anchoredPosition = ((Graphic)__instance.m_crosshairBow).rectTransform.anchoredPosition + new Vector2(40f, -20f);
			((Transform)((Graphic)AmmoReticlePlugin.AmmoIcon).rectTransform).localRotation = Quaternion.Euler(0f, 0f, 45f);
			((Transform)((Graphic)AmmoReticlePlugin.AmmoIcon).rectTransform).localScale = new Vector3(0.4f, 0.4f, 1f);
			((Component)AmmoReticlePlugin.AmmoIcon).gameObject.SetActive(false);
			GameObject val2 = new GameObject("AmmoCount", new Type[2]
			{
				typeof(RectTransform),
				typeof(TextMeshProUGUI)
			});
			val2.transform.SetParent(parent, false);
			AmmoReticlePlugin.AmmoCount = val2.GetComponent<TextMeshProUGUI>();
			((TMP_Text)AmmoReticlePlugin.AmmoCount).fontSize = 18f;
			((TMP_Text)AmmoReticlePlugin.AmmoCount).alignment = (TextAlignmentOptions)513;
			((TMP_Text)AmmoReticlePlugin.AmmoCount).rectTransform.anchoredPosition = ((Graphic)AmmoReticlePlugin.AmmoIcon).rectTransform.anchoredPosition + new Vector2(120f, -10f);
			((Component)AmmoReticlePlugin.AmmoCount).gameObject.SetActive(false);
		}
	}
	[HarmonyPatch(typeof(Hud), "UpdateCrosshair")]
	internal static class UpdateAmmoUI
	{
		private static void Postfix(Hud __instance, Player player, float bowDrawPercentage)
		{
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Invalid comparison between Unknown and I4
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Invalid comparison between Unknown and I4
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Invalid comparison between Unknown and I4
			if (((TMP_Text)__instance.m_hoverName).text.Length > 0)
			{
				((Component)AmmoReticlePlugin.AmmoIcon).gameObject.SetActive(false);
				((Component)AmmoReticlePlugin.AmmoCount).gameObject.SetActive(false);
				return;
			}
			ItemData val = ((Humanoid)player).LeftItem ?? ((Humanoid)player).RightItem;
			if (val != null)
			{
				float attackEitr = val.m_shared.m_attack.m_attackEitr;
				if (attackEitr > 0f && AmmoReticlePlugin.ShowAmmoUsesForEitr.Value.IsOn())
				{
					int num = Mathf.FloorToInt(player.GetEitr() / attackEitr);
					int num2 = Mathf.FloorToInt(((Character)player).GetMaxEitr() / attackEitr);
					SetAmmoUI(val.GetIcon(), $"{num}/{num2}");
					return;
				}
				if ((int)val.m_shared.m_itemType == 4)
				{
					Inventory inventory = ((Humanoid)player).GetInventory();
					ItemData ammoItem = ((Humanoid)player).GetAmmoItem();
					if (ammoItem != null && !(ammoItem.m_shared.m_ammoType != val.m_shared.m_ammoType))
					{
						int stack = ammoItem.m_stack;
						int num3 = inventory.CountItemsByType((ItemType)9, -1, true, false);
						SetAmmoUI(ammoItem.GetIcon() ?? ammoItem.m_shared.m_icons[0], $"{stack}/{num3}");
					}
					return;
				}
				if (val.IsWeapon() && (int)val.m_shared.m_itemType != 4 && (int)val.m_shared.m_itemType != 15 && AmmoReticlePlugin.ShowAmmoUsesForStamina.Value.IsOn())
				{
					float attackStamina = val.m_shared.m_attack.m_attackStamina;
					if (attackStamina > 0f)
					{
						int num4 = Mathf.FloorToInt(player.GetStamina() / attackStamina);
						int num5 = Mathf.FloorToInt(((Character)player).GetMaxStamina() / attackStamina);
						SetAmmoUI(val.GetIcon(), $"{num4}/{num5}");
						return;
					}
				}
			}
			((Component)AmmoReticlePlugin.AmmoIcon).gameObject.SetActive(false);
			((Component)AmmoReticlePlugin.AmmoCount).gameObject.SetActive(false);
		}

		private static void SetAmmoUI(Sprite icon, string countText)
		{
			if (AmmoReticlePlugin.ShowAmmoIcon.Value.IsOn())
			{
				AmmoReticlePlugin.AmmoIcon.sprite = icon;
				((Component)AmmoReticlePlugin.AmmoIcon).gameObject.SetActive(true);
			}
			else
			{
				((Component)AmmoReticlePlugin.AmmoIcon).gameObject.SetActive(false);
			}
			if (AmmoReticlePlugin.ShowAmmoCount.Value.IsOn())
			{
				((TMP_Text)AmmoReticlePlugin.AmmoCount).text = countText;
				((Component)AmmoReticlePlugin.AmmoCount).gameObject.SetActive(true);
			}
			else
			{
				((Component)AmmoReticlePlugin.AmmoCount).gameObject.SetActive(false);
			}
		}
	}
	[BepInPlugin("Azumatt.AmmoReticle", "AmmoReticle", "1.0.0")]
	public class AmmoReticlePlugin : BaseUnityPlugin
	{
		public enum Toggle
		{
			On = 1,
			Off = 0
		}

		internal const string ModName = "AmmoReticle";

		internal const string ModVersion = "1.0.0";

		internal const string Author = "Azumatt";

		private const string ModGUID = "Azumatt.AmmoReticle";

		private static string ConfigFileName = "Azumatt.AmmoReticle.cfg";

		private static string ConfigFileFullPath;

		internal static string ConnectionError;

		private readonly Harmony _harmony = new Harmony("Azumatt.AmmoReticle");

		public static readonly ManualLogSource AmmoReticleLogger;

		private FileSystemWatcher _watcher;

		private readonly object _reloadLock = new object();

		private DateTime _lastConfigReloadTime;

		private const long RELOAD_DELAY = 10000000L;

		internal static Image AmmoIcon;

		internal static TextMeshProUGUI AmmoCount;

		internal static TextMeshProUGUI AmmoTotal;

		internal static ConfigEntry<Toggle> ShowAmmoIcon;

		internal static ConfigEntry<Toggle> ShowAmmoCount;

		internal static ConfigEntry<Toggle> ShowAmmoUsesForEitr;

		internal static ConfigEntry<Toggle> ShowAmmoUsesForStamina;

		public void Awake()
		{
			bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			ShowAmmoIcon = config("1 - UI", "Show Ammo Icon", Toggle.On, "Enable/Disable showing the ammo icon near the crosshair.");
			ShowAmmoCount = config("1 - UI", "Show Ammo Count", Toggle.On, "Enable/Disable showing the ammo count.");
			ShowAmmoUsesForEitr = config("2 - Logic", "Show Eitr Usage Info", Toggle.On, "Display how many times you can cast with current/max Eitr.");
			ShowAmmoUsesForStamina = config("2 - Logic", "Show Stamina Usage Info", Toggle.On, "Display how many times you can attack with current/max stamina.");
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.PatchAll(executingAssembly);
			SetupWatcher();
			((BaseUnityPlugin)this).Config.Save();
			if (saveOnConfigSet)
			{
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		private void OnDestroy()
		{
			SaveWithRespectToConfigSet();
			_watcher?.Dispose();
		}

		private void SetupWatcher()
		{
			_watcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			_watcher.Changed += ReadConfigValues;
			_watcher.Created += ReadConfigValues;
			_watcher.Renamed += ReadConfigValues;
			_watcher.IncludeSubdirectories = true;
			_watcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			_watcher.EnableRaisingEvents = true;
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			DateTime now = DateTime.Now;
			if (now.Ticks - _lastConfigReloadTime.Ticks < 10000000)
			{
				return;
			}
			lock (_reloadLock)
			{
				if (!File.Exists(ConfigFileFullPath))
				{
					AmmoReticleLogger.LogWarning((object)"Config file does not exist. Skipping reload.");
					return;
				}
				try
				{
					AmmoReticleLogger.LogDebug((object)"Reloading configuration...");
					SaveWithRespectToConfigSet(reload: true);
					AmmoReticleLogger.LogInfo((object)"Configuration reload complete.");
				}
				catch (Exception ex)
				{
					AmmoReticleLogger.LogError((object)("Error reloading configuration: " + ex.Message));
				}
			}
			_lastConfigReloadTime = now;
		}

		private void SaveWithRespectToConfigSet(bool reload = false)
		{
			bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			if (reload)
			{
				((BaseUnityPlugin)this).Config.Reload();
			}
			((BaseUnityPlugin)this).Config.Save();
			if (saveOnConfigSet)
			{
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description)
		{
			return ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
		}

		private ConfigEntry<T> config<T>(string group, string name, T value, string description)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}

		static AmmoReticlePlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			ConnectionError = "";
			AmmoReticleLogger = Logger.CreateLogSource("AmmoReticle");
			AmmoIcon = null;
			AmmoCount = null;
			AmmoTotal = null;
			ShowAmmoIcon = null;
			ShowAmmoCount = null;
			ShowAmmoUsesForEitr = null;
			ShowAmmoUsesForStamina = null;
		}
	}
	public static class ToggleExtentions
	{
		public static bool IsOn(this AmmoReticlePlugin.Toggle value)
		{
			return value == AmmoReticlePlugin.Toggle.On;
		}

		public static bool IsOff(this AmmoReticlePlugin.Toggle value)
		{
			return value == AmmoReticlePlugin.Toggle.Off;
		}
	}
}