Decompiled source of AimAnyTime v1.1.1

BepInEx/plugins/AimAnyTime.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
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 Pigeon.Movement;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Sparroh")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1")]
[assembly: AssemblyProduct("AimAnyTime")]
[assembly: AssemblyTitle("AimAnyTime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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;
		}
	}
}
public static class AimConstraints
{
	private static readonly FieldInfo lockSprintingField = AccessTools.Field(typeof(Gun), "lockSprinting");

	private static readonly Dictionary<int, bool> originalLockSprinting = new Dictionary<int, bool>();

	public static void RefreshAll()
	{
		ApplyLockSprintingToAllGuns();
		ApplySlidingOverrideToLocalPlayer();
	}

	public static void ApplySlidingOverrideToLocalPlayer()
	{
		try
		{
			Player localPlayer = Player.LocalPlayer;
			if (!((Object)(object)localPlayer == (Object)null))
			{
				localPlayer.OverrideCanAimWhileSliding = (ActionFireMode)(ConfigManager.EnableCanAimWhileSliding.Value ? 1 : 0);
			}
		}
		catch (Exception ex)
		{
			AimAnyTimePlugin.Logger.LogError((object)("Error applying sliding aim override: " + ex.Message));
		}
	}

	public static void ApplyLockSprintingToAllGuns()
	{
		try
		{
			Gun[] array = Object.FindObjectsOfType<Gun>();
			for (int i = 0; i < array.Length; i++)
			{
				if ((Object)(object)array[i] != (Object)null)
				{
					ApplyLockSprinting(array[i]);
				}
			}
		}
		catch (Exception ex)
		{
			AimAnyTimePlugin.Logger.LogError((object)("Error re-applying lockSprinting: " + ex.Message));
		}
	}

	public static void ApplyLockSprinting(Gun gun)
	{
		if ((Object)(object)gun == (Object)null || lockSprintingField == null)
		{
			return;
		}
		try
		{
			int instanceID = ((Object)gun).GetInstanceID();
			bool flag = (bool)lockSprintingField.GetValue(gun);
			if (!originalLockSprinting.TryGetValue(instanceID, out var value))
			{
				value = flag;
				originalLockSprinting[instanceID] = value;
			}
			bool flag2 = !ConfigManager.EnableCanAimWhileSprinting.Value && value;
			if (flag == flag2)
			{
				return;
			}
			lockSprintingField.SetValue(gun, flag2);
			if (!gun.Active)
			{
				return;
			}
			Player player = gun.Player;
			if ((Object)(object)player != (Object)null)
			{
				if (flag && !flag2)
				{
					player.SprintLocks = Math.Max(0, player.SprintLocks - 1);
				}
				else if (!flag && flag2)
				{
					int sprintLocks = player.SprintLocks;
					player.SprintLocks = sprintLocks + 1;
				}
			}
		}
		catch (Exception ex)
		{
			AimAnyTimePlugin.Logger.LogError((object)("Error applying lockSprinting: " + ex.Message));
		}
	}
}
[HarmonyPatch]
public static class CanAimPatches
{
	private static readonly FieldInfo isAimInputHeldField = AccessTools.Field(typeof(Gun), "isAimInputHeld");

	private static readonly FieldInfo lastPressedAimTimeField = AccessTools.Field(typeof(Gun), "lastPressedAimTime");

	private static readonly FieldInfo lastPressedFireTimeField = AccessTools.Field(typeof(Gun), "lastPressedFireTime");

	private static readonly FieldInfo gunDataField = AccessTools.Field(typeof(Gun), "gunData");

	[HarmonyPatch(typeof(Gun), "CanAim")]
	[HarmonyPrefix]
	private static bool CanAimPrefix(Gun __instance, ref bool __result)
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Invalid comparison between Unknown and I4
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			Player player = __instance.Player;
			if ((Object)(object)player == (Object)null || isAimInputHeldField == null || gunDataField == null)
			{
				return true;
			}
			bool num = (bool)isAimInputHeldField.GetValue(__instance);
			FireConstraints fireConstraints = ((GunData)gunDataField.GetValue(__instance)).fireConstraints;
			ActionFireMode val = ((player.OverrideCanAimWhileSliding > fireConstraints.canAimWhileSliding) ? player.OverrideCanAimWhileSliding : fireConstraints.canAimWhileSliding);
			if (ConfigManager.EnableCanAimWhileSliding.Value)
			{
				val = (ActionFireMode)1;
			}
			bool flag = (int)val > 0 || !player.Sliding;
			bool flag2 = !__instance.Reloading || fireConstraints.canAimWhileReloading || ConfigManager.EnableCanAimWhileReloading.Value;
			bool flag3 = num && flag && flag2 && !player.IsFireLocked;
			if (flag3)
			{
				if (player.IsSprinting && !ConfigManager.EnableCanAimWhileSprinting.Value)
				{
					float num2 = ((lastPressedAimTimeField != null) ? ((float)lastPressedAimTimeField.GetValue(__instance)) : 0f);
					if (player.StartSprintTime >= num2)
					{
						flag3 = false;
					}
					else
					{
						player.StopSprint();
					}
				}
			}
			else if (__instance.IsAiming && !__instance.WantsToFire && !ConfigManager.EnableCanAimWhileSprinting.Value)
			{
				float num3 = ((lastPressedFireTimeField != null) ? ((float)lastPressedFireTimeField.GetValue(__instance)) : 0f);
				if (Time.time - Mathf.Max(__instance.LastFireTime, num3) > 0.5f)
				{
					player.ResumeSprint();
				}
			}
			__result = flag3;
			return false;
		}
		catch (Exception ex)
		{
			AimAnyTimePlugin.Logger.LogError((object)("Error in CanAim patch: " + ex.Message));
			return true;
		}
	}
}
public static class ConfigManager
{
	private const float DebounceSeconds = 0.25f;

	private static ConfigFile config;

	private static ManualLogSource logger;

	private static FileSystemWatcher configWatcher;

	private static volatile bool pendingConstraintRefresh;

	private static volatile bool reloadPending;

	private static float lastReloadTime;

	public static ConfigEntry<bool> EnableCanAimWhileSliding { get; private set; }

	public static ConfigEntry<bool> EnableCanAimWhileReloading { get; private set; }

	public static ConfigEntry<bool> EnableCanAimWhileSprinting { get; private set; }

	public static ConfigEntry<bool> ShowReloadAnimWhileAiming { get; private set; }

	public static void Initialize(ConfigFile configFile, ManualLogSource log)
	{
		config = configFile;
		logger = log;
		EnableCanAimWhileSliding = config.Bind<bool>("General", "Can Aim While Sliding", true, "Allows aiming weapons while sliding.");
		EnableCanAimWhileReloading = config.Bind<bool>("General", "Can Aim While Reloading", true, "Keeps ADS active while reloading (FOV/aim state). Pair with Show Reload Anim While Aiming for visible reload feedback.");
		EnableCanAimWhileSprinting = config.Bind<bool>("General", "Can Aim While Sprinting", true, "Allows aiming weapons while sprinting without cancelling sprint.");
		ShowReloadAnimWhileAiming = config.Bind<bool>("General", "Show Reload Anim While Aiming", true, "While ADS-reloading, temporarily hide the aim pose so the reload animation is visible. ADS state (FOV) stays active.");
		EnableCanAimWhileSliding.SettingChanged += OnSettingChanged;
		EnableCanAimWhileReloading.SettingChanged += OnSettingChanged;
		EnableCanAimWhileSprinting.SettingChanged += OnSettingChanged;
		ShowReloadAnimWhileAiming.SettingChanged += OnSettingChanged;
		try
		{
			SetupFileWatcher();
		}
		catch (Exception ex)
		{
			logger.LogError((object)("Error setting up config file watcher: " + ex.Message));
		}
	}

	public static void Tick()
	{
		if (!reloadPending || Time.unscaledTime - lastReloadTime < 0.25f)
		{
			return;
		}
		reloadPending = false;
		lastReloadTime = Time.unscaledTime;
		try
		{
			config.Reload();
			pendingConstraintRefresh = true;
			logger.LogInfo((object)"Config reloaded from disk.");
		}
		catch (Exception ex)
		{
			logger.LogError((object)("Error reloading config: " + ex.Message));
		}
	}

	public static bool ConsumePendingRefresh()
	{
		if (!pendingConstraintRefresh)
		{
			return false;
		}
		pendingConstraintRefresh = false;
		return true;
	}

	public static void Dispose()
	{
		if (EnableCanAimWhileSliding != null)
		{
			EnableCanAimWhileSliding.SettingChanged -= OnSettingChanged;
		}
		if (EnableCanAimWhileReloading != null)
		{
			EnableCanAimWhileReloading.SettingChanged -= OnSettingChanged;
		}
		if (EnableCanAimWhileSprinting != null)
		{
			EnableCanAimWhileSprinting.SettingChanged -= OnSettingChanged;
		}
		if (ShowReloadAnimWhileAiming != null)
		{
			ShowReloadAnimWhileAiming.SettingChanged -= OnSettingChanged;
		}
		if (configWatcher != null)
		{
			configWatcher.EnableRaisingEvents = false;
			configWatcher.Changed -= OnConfigFileChanged;
			configWatcher.Created -= OnConfigFileChanged;
			configWatcher.Renamed -= OnConfigFileChanged;
			configWatcher.Dispose();
			configWatcher = null;
		}
	}

	private static void SetupFileWatcher()
	{
		configWatcher = new FileSystemWatcher(Paths.ConfigPath, "sparroh.aimanytime.cfg");
		configWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite;
		configWatcher.Changed += OnConfigFileChanged;
		configWatcher.Created += OnConfigFileChanged;
		configWatcher.Renamed += OnConfigFileChanged;
		configWatcher.EnableRaisingEvents = true;
	}

	private static void OnConfigFileChanged(object sender, FileSystemEventArgs e)
	{
		reloadPending = true;
	}

	private static void OnSettingChanged(object sender, EventArgs e)
	{
		pendingConstraintRefresh = true;
	}
}
[HarmonyPatch]
public static class GunLifecyclePatches
{
	[HarmonyPatch(typeof(Gun), "Setup", new Type[]
	{
		typeof(Player),
		typeof(PlayerAnimation),
		typeof(IGear)
	})]
	[HarmonyPostfix]
	private static void SetupPostfix(Gun __instance)
	{
		try
		{
			AimConstraints.ApplyLockSprinting(__instance);
			AimConstraints.ApplySlidingOverrideToLocalPlayer();
		}
		catch (Exception ex)
		{
			AimAnyTimePlugin.Logger.LogError((object)("Error in Gun.Setup patch: " + ex.Message));
		}
	}

	[HarmonyPatch(typeof(Gun), "Enable")]
	[HarmonyPrefix]
	private static void EnablePrefix(Gun __instance)
	{
		try
		{
			AimConstraints.ApplyLockSprinting(__instance);
			AimConstraints.ApplySlidingOverrideToLocalPlayer();
		}
		catch (Exception ex)
		{
			AimAnyTimePlugin.Logger.LogError((object)("Error in Gun.Enable prefix: " + ex.Message));
		}
	}
}
[BepInPlugin("sparroh.aimanytime", "AimAnyTime", "1.1.1")]
[MycoMod(/*Could not decode attribute arguments.*/)]
public class AimAnyTimePlugin : BaseUnityPlugin
{
	public const string PluginGUID = "sparroh.aimanytime";

	public const string PluginName = "AimAnyTime";

	public const string PluginVersion = "1.1.1";

	internal static ManualLogSource Logger;

	private Harmony harmony;

	private void Awake()
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Expected O, but got Unknown
		Logger = ((BaseUnityPlugin)this).Logger;
		ConfigManager.Initialize(((BaseUnityPlugin)this).Config, Logger);
		harmony = new Harmony("sparroh.aimanytime");
		try
		{
			harmony.PatchAll(typeof(CanAimPatches));
			harmony.PatchAll(typeof(ReloadAimAnimationPatches));
			harmony.PatchAll(typeof(GunLifecyclePatches));
			Logger.LogInfo((object)"Harmony patches applied.");
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Error applying patches: " + ex.Message));
		}
		Logger.LogInfo((object)"AimAnyTime v1.1.1 loaded successfully.");
	}

	private void Update()
	{
		ConfigManager.Tick();
		if (ConfigManager.ConsumePendingRefresh())
		{
			AimConstraints.RefreshAll();
		}
	}

	private void OnDestroy()
	{
		ConfigManager.Dispose();
		Harmony obj = harmony;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
	}
}
[HarmonyPatch]
public static class ReloadAimAnimationPatches
{
	private static readonly FieldInfo animatorField = AccessTools.Field(typeof(Gun), "animator");

	private static readonly FieldInfo aimTransitionDurationField = AccessTools.Field(typeof(Gun), "aimTransitionDuration");

	private static readonly PropertyInfo enableAimAnimationsProperty = AccessTools.Property(typeof(Gun), "EnableAimAnimations");

	private static bool ShouldShowReloadOverAim(Gun gun)
	{
		if (ConfigManager.EnableCanAimWhileReloading != null && ConfigManager.EnableCanAimWhileReloading.Value && ConfigManager.ShowReloadAnimWhileAiming != null && ConfigManager.ShowReloadAnimWhileAiming.Value && (Object)(object)gun != (Object)null && gun.Reloading)
		{
			return gun.IsAiming;
		}
		return false;
	}

	private static void HideAimLayerForReload(Gun gun, bool instant)
	{
		if (animatorField == null)
		{
			return;
		}
		object? value = animatorField.GetValue(gun);
		PlayerAnimation val = (PlayerAnimation)((value is PlayerAnimation) ? value : null);
		if (!((Object)(object)val == (Object)null))
		{
			float num = 0f;
			if (!instant && aimTransitionDurationField != null)
			{
				num = (float)aimTransitionDurationField.GetValue(gun);
			}
			val.DisableAimLayer(num);
		}
	}

	[HarmonyPatch(typeof(Gun), "HandleAim")]
	[HarmonyPostfix]
	private static void HandleAimPostfix(Gun __instance)
	{
		try
		{
			if (!ShouldShowReloadOverAim(__instance))
			{
				return;
			}
			if (enableAimAnimationsProperty != null)
			{
				object value = enableAimAnimationsProperty.GetValue(__instance);
				if (value is bool && !(bool)value)
				{
					return;
				}
			}
			HideAimLayerForReload(__instance, instant: true);
		}
		catch (Exception ex)
		{
			AimAnyTimePlugin.Logger.LogError((object)("Error in HandleAim reload-anim patch: " + ex.Message));
		}
	}

	[HarmonyPatch(typeof(Gun), "StartReloadAnimation")]
	[HarmonyPostfix]
	private static void StartReloadAnimationPostfix(Gun __instance)
	{
		try
		{
			if (ConfigManager.EnableCanAimWhileReloading != null && ConfigManager.EnableCanAimWhileReloading.Value && ConfigManager.ShowReloadAnimWhileAiming != null && ConfigManager.ShowReloadAnimWhileAiming.Value && !((Object)(object)__instance == (Object)null) && __instance.IsAiming)
			{
				HideAimLayerForReload(__instance, instant: true);
			}
		}
		catch (Exception ex)
		{
			AimAnyTimePlugin.Logger.LogError((object)("Error in StartReloadAnimation patch: " + ex.Message));
		}
	}
}
namespace AimAnyTime
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "AimAnyTime";

		public const string PLUGIN_NAME = "AimAnyTime";

		public const string PLUGIN_VERSION = "1.1.1";
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}