Decompiled source of Auto Offhand v1.0.0

plugins/AutoOffhand.dll

Decompiled 15 hours ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
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("BenjSammy")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("AutoOffhand")]
[assembly: AssemblyTitle("AutoOffhand")]
[assembly: AssemblyVersion("1.0.0.0")]
[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;
		}
	}
}
namespace BenjSammy.AutoOffhand
{
	[BepInPlugin("benjsammy.autooffhand", "Auto Offhand by BenjSammy", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class AutoOffhand : BaseUnityPlugin
	{
		public enum Offhand
		{
			Aucun,
			Torche,
			Bouclier,
			TorcheNuitBouclierJour,
			OrdreHotbar,
			TorcheHorsCombatBouclierCombat
		}

		private const string Id = "benjsammy.autooffhand";

		private static AutoOffhand instance;

		private ConfigEntry<Offhand> mode;

		private ConfigEntry<float> quietSeconds;

		private readonly CombatState combat = new CombatState();

		private bool french;

		private bool modeMenuOpen;

		private float nextEquipmentCheck;

		private Func<int> row;

		private Harmony harmony;

		private MethodInfo hotbarRow;

		private object legacySettings;

		private FieldInfo legacyFailureFlag;

		private bool legacyFailureState;

		private bool equipping;

		private bool? previousDay;

		private Player observedPlayer;

		private float equipAfter;

		private bool offhandFailed;

		private static readonly MethodInfo InAttack = AccessTools.Method(typeof(Character), "InAttack", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo Blocking = AccessTools.Method(typeof(Character), "IsBlocking", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo Dodging = AccessTools.Method(typeof(Player), "InDodge", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo HitAttacker = AccessTools.Method(typeof(HitData), "GetAttacker", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo RightHand = AccessTools.Method(typeof(Humanoid), "GetRightItem", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo LeftHand = AccessTools.Method(typeof(Humanoid), "GetLeftItem", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo InventoryFor = AccessTools.Method(typeof(Humanoid), "GetInventory", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo Equip = AccessTools.Method(typeof(Humanoid), "EquipItem", new Type[2]
		{
			typeof(ItemData),
			typeof(bool)
		}, (Type[])null);

		private static readonly MethodInfo Unequip = AccessTools.Method(typeof(Humanoid), "UnequipItem", new Type[2]
		{
			typeof(ItemData),
			typeof(bool)
		}, (Type[])null);

		private void Awake()
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Expected O, but got Unknown
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Expected O, but got Unknown
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Expected O, but got Unknown
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Expected O, but got Unknown
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ac: Expected O, but got Unknown
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Expected O, but got Unknown
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_0353: Expected O, but got Unknown
			french = UsesFrench();
			Type type = AccessTools.TypeByName("HotbarSwitch.BepInExPlugin");
			hotbarRow = ((type == null) ? null : AccessTools.Method(type, "HotbarY", Type.EmptyTypes, (Type[])null));
			row = GetHotbarRow;
			DisableLegacyOffhand();
			mode = ((BaseUnityPlugin)this).Config.Bind<Offhand>("Offhand", "Automatic equipment", Offhand.TorcheHorsCombatBouclierCombat, new ConfigDescription(french ? "Choisis la main secondaire automatique pour les armes à une main. Recherche dans la barre rapide, puis dans l’inventaire." : "Choose automatic offhand equipment for one-handed weapons. Searches the hotbar, then your inventory.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					DispName = (french ? "Équipement automatique" : "Automatic offhand"),
					Category = (french ? "Main secondaire" : "Offhand"),
					CustomDrawer = DrawMode
				}
			}));
			quietSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Offhand", "Combat quiet seconds", 5f, new ConfigDescription(french ? "Délai sans menace avant de remettre la torche, en secondes, pour le mode combat." : "Seconds without a combat threat before switching back to the torch in combat mode.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 30f), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					DispName = (french ? "Retour à la torche après (s)" : "Return to torch after (s)"),
					Category = (french ? "Main secondaire" : "Offhand")
				}
			}));
			mode.SettingChanged += delegate
			{
				previousDay = null;
				nextEquipmentCheck = 0f;
				if ((Object)(object)observedPlayer != (Object)null && Time.unscaledTime >= equipAfter)
				{
					TryOffhand((Humanoid)(object)observedPlayer, null);
				}
			};
			instance = this;
			harmony = new Harmony("benjsammy.autooffhand");
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Humanoid), "EquipItem", new Type[2]
			{
				typeof(ItemData),
				typeof(bool)
			}, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AutoOffhand), "AfterEquip", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Player), "RPC_OnTargeted", new Type[3]
			{
				typeof(long),
				typeof(bool),
				typeof(bool)
			}, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AutoOffhand), "AfterTargeted", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Player), "OnTargeted", new Type[2]
			{
				typeof(bool),
				typeof(bool)
			}, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AutoOffhand), "AfterLocallyTargeted", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Humanoid), "StartAttack", new Type[2]
			{
				typeof(Character),
				typeof(bool)
			}, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AutoOffhand), "AfterAttack", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Player), "OnDamaged", new Type[1] { typeof(HitData) }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AutoOffhand), "AfterDamaged", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private void DrawMode(ConfigEntryBase entry)
		{
			ConfigEntry<Offhand> val = (ConfigEntry<Offhand>)(object)entry;
			string[] array = ((!french) ? new string[6] { "None", "Torch", "Shield", "Torch at night, shield by day", "Hotbar order", "Torch out of combat, shield in combat" } : new string[6] { "Aucun", "Torche", "Bouclier", "Torche la nuit, bouclier le jour", "Ordre de la barre rapide", "Torche hors combat, bouclier en combat" });
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			if (GUILayout.Button(array[(int)val.Value] + " ▼", Array.Empty<GUILayoutOption>()))
			{
				modeMenuOpen = !modeMenuOpen;
			}
			if (modeMenuOpen)
			{
				for (int i = 0; i < array.Length; i++)
				{
					if (GUILayout.Button(array[i], Array.Empty<GUILayoutOption>()))
					{
						val.Value = (Offhand)i;
						modeMenuOpen = false;
					}
				}
			}
			GUILayout.EndVertical();
		}

		private static bool UsesFrench()
		{
			string text = PlayerPrefs.GetString("language", "English");
			Type type = AccessTools.TypeByName("Localization");
			if (type != null)
			{
				try
				{
					MethodInfo methodInfo = AccessTools.Method(type, "GetSelectedLanguage", Type.EmptyTypes, (Type[])null);
					object obj = (((object)methodInfo == null || methodInfo.IsStatic) ? null : AccessTools.PropertyGetter(type, "instance")?.Invoke(null, null));
					if (methodInfo != null && (methodInfo.IsStatic || obj != null))
					{
						text = (methodInfo.Invoke(obj, null) as string) ?? text;
					}
				}
				catch (Exception)
				{
				}
			}
			if (!string.Equals(text, "French", StringComparison.OrdinalIgnoreCase) && !string.Equals(text, "Français", StringComparison.OrdinalIgnoreCase) && !string.Equals(text, "fr", StringComparison.OrdinalIgnoreCase))
			{
				return text.StartsWith("fr-", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		private int GetHotbarRow()
		{
			try
			{
				if (hotbarRow?.Invoke(null, null) is int num && num >= 0)
				{
					return num;
				}
			}
			catch (Exception)
			{
				hotbarRow = null;
			}
			return 0;
		}

		private void DisableLegacyOffhand()
		{
			if (Chainloader.PluginInfos.TryGetValue("benjsammy.hotbarscroll.settings", out var value) && !((Object)(object)value.Instance == (Object)null) && !(((object)value.Instance).GetType().GetMethod("TryOffhand", BindingFlags.Instance | BindingFlags.NonPublic) == null))
			{
				FieldInfo field = ((object)value.Instance).GetType().GetField("offhandFailed", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (!(field?.FieldType != typeof(bool)))
				{
					legacySettings = value.Instance;
					legacyFailureFlag = field;
					legacyFailureState = (bool)field.GetValue(legacySettings);
					field.SetValue(legacySettings, true);
				}
			}
		}

		private void OnDestroy()
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			if (legacySettings != null)
			{
				legacyFailureFlag.SetValue(legacySettings, legacyFailureState);
			}
			instance = null;
		}

		private static void AfterEquip(Humanoid __instance, ItemData item, bool __result)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Invalid comparison between Unknown and I4
			AutoOffhand autoOffhand = instance;
			if (__result && !((Object)(object)autoOffhand == (Object)null) && !autoOffhand.equipping && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && !((Object)(object)__instance != (Object)(object)autoOffhand.observedPlayer) && !(Time.unscaledTime < autoOffhand.equipAfter) && item != null && (int)(item.m_shared?.m_itemType).GetValueOrDefault() == 3)
			{
				autoOffhand.TryOffhand(__instance, item);
			}
		}

		private void Update()
		{
			Player localPlayer = Player.m_localPlayer;
			if (observedPlayer != localPlayer)
			{
				observedPlayer = localPlayer;
				equipAfter = Time.unscaledTime + 1f;
				previousDay = null;
				combat.Reset();
				nextEquipmentCheck = 0f;
			}
			else
			{
				if ((Object)(object)localPlayer == (Object)null || offhandFailed || Time.unscaledTime < equipAfter || Time.unscaledTime < nextEquipmentCheck)
				{
					return;
				}
				nextEquipmentCheck = Time.unscaledTime + 0.2f;
				if (mode.Value == Offhand.TorcheHorsCombatBouclierCombat)
				{
					TryOffhand((Humanoid)(object)localPlayer, null);
					previousDay = null;
					return;
				}
				if (mode.Value != Offhand.TorcheNuitBouclierJour || (Object)(object)EnvMan.instance == (Object)null)
				{
					previousDay = null;
					return;
				}
				bool flag = EnvMan.IsDay();
				bool num = previousDay.HasValue && previousDay.Value != flag;
				previousDay = flag;
				if (num)
				{
					TryOffhand((Humanoid)(object)localPlayer, null);
				}
			}
		}

		private static void AfterTargeted(Player __instance, bool __2)
		{
			if (__2 && (Object)(object)__instance == (Object)(object)Player.m_localPlayer)
			{
				instance?.RememberCombat();
			}
		}

		private static void AfterLocallyTargeted(Player __instance, bool __1)
		{
			if (__1 && (Object)(object)__instance == (Object)(object)Player.m_localPlayer)
			{
				instance?.RememberCombat();
			}
		}

		private static void AfterAttack(Humanoid __instance, bool __result)
		{
			if (__result && (Object)(object)__instance == (Object)(object)Player.m_localPlayer)
			{
				instance?.RememberCombat();
			}
		}

		private static void AfterDamaged(Player __instance, HitData __0)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && __0 != null)
			{
				object? obj = HitAttacker.Invoke(__0, null);
				Character val = (Character)((obj is Character) ? obj : null);
				if (val != null && (Object)(object)val != (Object)(object)__instance)
				{
					instance?.RememberCombat();
				}
			}
		}

		private void RememberCombat()
		{
			if (mode.Value == Offhand.TorcheHorsCombatBouclierCombat)
			{
				combat.Observe(Time.unscaledTime);
				nextEquipmentCheck = 0f;
			}
		}

		private static bool EquipmentBusy(Player player)
		{
			if (!(bool)InAttack.Invoke(player, null) && !(bool)Blocking.Invoke(player, null))
			{
				return (bool)Dodging.Invoke(player, null);
			}
			return true;
		}

		private void TryOffhand(Humanoid player, ItemData equipped)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0066: 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_0079: Invalid comparison between Unknown and I4
			if (offhandFailed || mode.Value == Offhand.Aucun)
			{
				return;
			}
			try
			{
				if (mode.Value == Offhand.TorcheHorsCombatBouclierCombat)
				{
					Player val = (Player)(object)((player is Player) ? player : null);
					if (val != null && EquipmentBusy(val))
					{
						return;
					}
				}
				ItemData val2 = (ItemData)RightHand.Invoke(player, null);
				if (val2 != null && (int)(val2.m_shared?.m_itemType).GetValueOrDefault() == 3 && (equipped == null || val2 == equipped))
				{
					EquipOffhand(player, val2);
				}
			}
			catch (Exception ex)
			{
				offhandFailed = true;
				((BaseUnityPlugin)this).Logger.LogError((object)((french ? "Équipement automatique désactivé pour cette session : " : "Automatic offhand disabled for this session: ") + ex.GetBaseException()));
			}
		}

		private void EquipOffhand(Humanoid player, ItemData weapon)
		{
			//IL_003c: 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_00a9: Expected O, but got Unknown
			//IL_00c8: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Invalid comparison between Unknown and O
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Invalid comparison between Unknown and O
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Invalid comparison between Unknown and O
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Invalid comparison between Unknown and O
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Invalid comparison between Unknown and O
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			if (mode.Value == Offhand.Aucun || (Object)(object)weapon.m_shared.m_buildPieces != (Object)null || weapon.IsTwoHanded())
			{
				return;
			}
			ItemType preferred = (ItemType)((mode.Value == Offhand.Torche) ? 15 : 5);
			if (mode.Value == Offhand.TorcheNuitBouclierJour)
			{
				if ((Object)(object)EnvMan.instance == (Object)null)
				{
					return;
				}
				preferred = (ItemType)(EnvMan.IsDay() ? 5 : 15);
			}
			if (mode.Value == Offhand.TorcheHorsCombatBouclierCombat)
			{
				preferred = (ItemType)(combat.IsActive(Time.unscaledTime, quietSeconds.Value) ? 5 : 15);
			}
			Inventory val = (Inventory)InventoryFor.Invoke(player, null);
			if (val == null)
			{
				return;
			}
			int num = row();
			ItemData val2 = FindOffhandInRow(val, num, Math.Min(8, val.GetWidth()), preferred);
			for (int i = 0; i < val.GetHeight(); i++)
			{
				if (val2 != null)
				{
					break;
				}
				int start = ((i == num) ? 8 : 0);
				val2 = FindOffhandInRow(val, i, val.GetWidth(), preferred, start);
			}
			ItemData val3 = (ItemData)LeftHand.Invoke(player, null);
			if (val2 == null || val3 == val2)
			{
				return;
			}
			equipping = true;
			try
			{
				if (val3 != null)
				{
					Unequip.Invoke(player, new object[2] { val3, false });
				}
				if (!(bool)Equip.Invoke(player, new object[2] { val2, false }) || (object)(ItemData)RightHand.Invoke(player, null) != weapon || (object)(ItemData)LeftHand.Invoke(player, null) != val2)
				{
					if ((object)(ItemData)RightHand.Invoke(player, null) == val2 || (object)(ItemData)LeftHand.Invoke(player, null) == val2)
					{
						Unequip.Invoke(player, new object[2] { val2, false });
					}
					if ((object)(ItemData)RightHand.Invoke(player, null) != weapon)
					{
						Equip.Invoke(player, new object[2] { weapon, false });
					}
					if (val3 != null && (int)(ItemData)LeftHand.Invoke(player, null) == 0)
					{
						Equip.Invoke(player, new object[2] { val3, false });
					}
				}
			}
			finally
			{
				equipping = false;
			}
		}

		private ItemData FindOffhandInRow(Inventory inventory, int y, int end, ItemType preferred, int start = 0)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: 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_0061: Invalid comparison between Unknown and I4
			//IL_0058: 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_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Invalid comparison between Unknown and I4
			for (int i = start; i < end; i++)
			{
				ItemData itemAt = inventory.GetItemAt(i, y);
				if (itemAt?.m_shared == null || !itemAt.IsEquipable() || (itemAt.m_shared.m_useDurability && itemAt.m_durability <= 0f))
				{
					continue;
				}
				ItemType itemType = itemAt.m_shared.m_itemType;
				bool num;
				if (mode.Value != Offhand.OrdreHotbar)
				{
					num = itemType == preferred;
				}
				else
				{
					if ((int)itemType == 5)
					{
						goto IL_006d;
					}
					num = (int)itemType == 15;
				}
				if (!num)
				{
					continue;
				}
				goto IL_006d;
				IL_006d:
				return itemAt;
			}
			return null;
		}
	}
	internal sealed class CombatState
	{
		private float lastThreat = float.NegativeInfinity;

		public void Observe(float now)
		{
			lastThreat = now;
		}

		public bool IsActive(float now, float quietSeconds)
		{
			if (now >= lastThreat)
			{
				return now - lastThreat < quietSeconds;
			}
			return false;
		}

		public void Reset()
		{
			lastThreat = float.NegativeInfinity;
		}
	}
	internal sealed class ConfigurationManagerAttributes
	{
		public string DispName;

		public string Category;

		public Action<ConfigEntryBase> CustomDrawer;
	}
}