Decompiled source of ShieldMeBruhReforged v1.0.1

plugins/ShieldMeBruhReforged.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
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 ShieldMeBruhReforged.Features;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("ShieldMeBruhReforged")]
[assembly: AssemblyDescription("Auto-equip a selected shield in Valheim 1.0.12.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ShieldMeBruhReforged")]
[assembly: AssemblyProduct("ShieldMeBruhReforged")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("997CB563-FCC7-44B7-8F71-069747D27CC5")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.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;
		}
	}
}
namespace ShieldMeBruhReforged
{
	[BepInPlugin("augusdogus.mods.shieldmebruhreforged", "Shield Me Bruh Reforged", "1.0.1")]
	public class ShieldMeBruhReforged : BaseUnityPlugin
	{
		public const string PluginId = "augusdogus.mods.shieldmebruhreforged";

		public const string PluginVersion = "1.0.1";

		private Harmony _harmony;

		public static ManualLogSource Log { get; private set; }

		public static AutoShield AutoShield { get; private set; }

		private void Awake()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			AutoShield = new AutoShield(((BaseUnityPlugin)this).Config);
			AutoShield.LoadAssets();
			_harmony = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			AutoShield?.Dispose();
			AutoShield = null;
		}
	}
}
namespace ShieldMeBruhReforged.Patches
{
	public static class Humanoid_Patches
	{
		[HarmonyPatch(typeof(Humanoid), "EquipItem")]
		private static class HumanoidEquipItemPatch
		{
			private static void Postfix(Humanoid __instance, ItemData item, bool __result, ItemData ___m_leftItem, bool __runOriginal)
			{
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Invalid comparison between Unknown and I4
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (val != null && !((Object)(object)val != (Object)(object)Player.m_localPlayer) && __runOriginal && __result && ShieldMeBruhReforged.AutoShield.EnableAutoShield.Value && item != null && (int)item.m_shared.m_itemType == 3 && ___m_leftItem == null)
				{
					ItemData selectedShield = ShieldMeBruhReforged.AutoShield.GetSelectedShield(val);
					if (selectedShield != null)
					{
						((Humanoid)val).EquipItem(selectedShield, true);
					}
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "UnequipItem")]
		private static class HumanoidUnequipItemPatch
		{
			private static void Postfix(Humanoid __instance, ItemData item, ItemData ___m_leftItem, bool __runOriginal)
			{
				//IL_0048: Unknown result type (might be due to invalid IL or missing references)
				//IL_004e: Invalid comparison between Unknown and I4
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (val != null && !((Object)(object)val != (Object)(object)Player.m_localPlayer) && __runOriginal && ShieldMeBruhReforged.AutoShield.EnableAutoShield.Value && ShieldMeBruhReforged.AutoShield.EnableAutoUnequip.Value && item != null && ___m_leftItem != null && (int)item.m_shared.m_itemType == 3 && ___m_leftItem == ShieldMeBruhReforged.AutoShield.GetSelectedShield(val))
				{
					((Humanoid)val).UnequipItem(___m_leftItem, true);
				}
			}
		}
	}
	public static class InventoryGrid_Patches
	{
		[HarmonyPatch(typeof(InventoryGrid), "UpdateGui")]
		private static class InventoryGridUpdateGuiPatch
		{
			[HarmonyPriority(800)]
			private static void Prefix(InventoryGrid __instance, ref bool __state)
			{
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null && __instance.m_inventory == ((Humanoid)localPlayer).GetInventory())
				{
					__state = __instance.m_width != __instance.m_inventory.GetWidth() || __instance.m_height != __instance.m_inventory.GetHeight();
				}
			}

			private static void Postfix(InventoryGrid __instance, bool __state, bool __runOriginal)
			{
				if (!__runOriginal)
				{
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer == null || __instance.m_inventory != ((Humanoid)localPlayer).GetInventory())
				{
					return;
				}
				if (__state)
				{
					foreach (InventoryElement element in __instance.m_elements)
					{
						UIInputHandler componentInChildren = ((Component)element).gameObject.GetComponentInChildren<UIInputHandler>();
						componentInChildren.m_onMiddleDown = (Action<UIInputHandler>)Delegate.Combine(componentInChildren.m_onMiddleDown, new Action<UIInputHandler>(ShieldMeBruhReforged.AutoShield.OnMiddleClick));
					}
				}
				ShieldMeBruhReforged.AutoShield.RefreshSelection(__instance);
			}
		}
	}
	public static class InventoryGui_Patches
	{
		[HarmonyPatch(typeof(InventoryGui), "Show")]
		private static class ShowInventoryPatch
		{
			private static void Postfix(InventoryGui __instance, bool __runOriginal)
			{
				if (__runOriginal)
				{
					ShieldMeBruhReforged.AutoShield.SetActiveInstance(__instance.m_playerGrid);
				}
			}
		}
	}
	public static class Player_Patches
	{
		[HarmonyPatch(typeof(Player), "SetLocalPlayer")]
		private static class SetLocalPlayerPatch
		{
			private static void Postfix(Player __instance)
			{
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					ShieldMeBruhReforged.AutoShield.ResetPlayerContext();
				}
			}
		}
	}
}
namespace ShieldMeBruhReforged.Features
{
	public class AutoShield : IDisposable
	{
		private InventoryGrid _activeInstance;

		private Sprite _shield;

		private InventoryElement _currentElement;

		public ConfigEntry<bool> EnableAutoShield;

		public ConfigEntry<bool> EnableAutoUnequip;

		public AutoShield(ConfigFile config)
		{
			EnableAutoShield = config.Bind<bool>("Local Config", "Enable Auto Shield", true, "When enabled, selected shield will automatically equip when a one handed weapon is equipped.");
			EnableAutoUnequip = config.Bind<bool>("Local Config", "Enable Auto Unequip", true, "When enabled, when one handed weapon is unequipped, the marked equipped shield, will also unequip.");
			EnableAutoShield.SettingChanged += OnEnabledChanged;
		}

		private void OnEnabledChanged(object sender, EventArgs args)
		{
			if ((Object)(object)_activeInstance != (Object)null)
			{
				RefreshSelection(_activeInstance);
			}
		}

		public void Dispose()
		{
			EnableAutoShield.SettingChanged -= OnEnabledChanged;
		}

		public void LoadAssets()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			string text = "ShieldMeBruhReforged.Resources";
			_shield = LoadSprite(text + ".shield.png", new Rect(0f, 0f, 1024f, 1024f));
		}

		public void SetActiveInstance(InventoryGrid instance)
		{
			_activeInstance = instance;
		}

		public static Texture2D LoadImage(byte[] bytes)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			//IL_001c: Expected O, but got Unknown
			Texture2D val = new Texture2D(2, 2);
			if (!ImageConversion.LoadImage(val, bytes))
			{
				throw new Exception("Failed to load image data into texture from byte array");
			}
			return val;
		}

		public Sprite LoadSprite(string path, Rect size, Vector2? pivot = null, int units = 100)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			if (!pivot.HasValue)
			{
				pivot = new Vector2(0.5f, 0.5f);
			}
			Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path);
			Texture2D obj = LoadImage(ReadToEnd(manifestResourceStream));
			if ((Object)(object)obj == (Object)null)
			{
				ShieldMeBruhReforged.Log.LogError((object)("Missing Embedded Resource: " + path));
			}
			return Sprite.Create(obj, size, pivot.Value, (float)units, 0u, (SpriteMeshType)1);
		}

		private byte[] ReadToEnd(Stream stream)
		{
			long position = stream.Position;
			stream.Position = 0L;
			try
			{
				byte[] array = new byte[4096];
				int num = 0;
				int num2;
				while ((num2 = stream.Read(array, num, array.Length - num)) > 0)
				{
					num += num2;
					if (num == array.Length)
					{
						int num3 = stream.ReadByte();
						if (num3 != -1)
						{
							byte[] array2 = new byte[array.Length * 2];
							Buffer.BlockCopy(array, 0, array2, 0, array.Length);
							Buffer.SetByte(array2, num, (byte)num3);
							array = array2;
							num++;
						}
					}
				}
				byte[] array3 = array;
				if (array.Length != num)
				{
					array3 = new byte[num];
					Buffer.BlockCopy(array, 0, array3, 0, num);
				}
				return array3;
			}
			finally
			{
				stream.Position = position;
			}
		}

		private Image CreateShieldedImage(Image baseImg, Image noTeleport)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			Image obj = Object.Instantiate<Image>(baseImg, ((Component)baseImg).transform.parent);
			((Object)((Component)obj).transform).name = "shield";
			obj.sprite = _shield;
			((Object)obj).name = "shield";
			((Graphic)obj).color = ((Graphic)noTeleport).color;
			obj.type = noTeleport.type;
			return obj;
		}

		public ItemData GetSelectedShield(Player player)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Invalid comparison between Unknown and I4
			foreach (ItemData allItem in ((Humanoid)player).GetInventory().GetAllItems())
			{
				if ((int)allItem.m_shared.m_itemType == 5 && ShieldSelection.IsSelected(player.m_customData, allItem.m_customData, "augusdogus.mods.shieldmebruhreforged"))
				{
					return allItem;
				}
			}
			return null;
		}

		public void OnMiddleClick(UIInputHandler middleClick)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Invalid comparison between Unknown and I4
			if (!EnableAutoShield.Value)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if (localPlayer == null || (Object)(object)_activeInstance == (Object)null || (Object)(object)middleClick == (Object)null)
			{
				return;
			}
			Inventory inventory = ((Humanoid)localPlayer).GetInventory();
			if (_activeInstance.m_inventory != inventory)
			{
				return;
			}
			Vector2i buttonPos = _activeInstance.GetButtonPos(((Component)middleClick).gameObject);
			ItemData itemAt = inventory.GetItemAt(buttonPos.x, buttonPos.y);
			if (itemAt != null && (int)itemAt.m_shared.m_itemType == 5)
			{
				ItemData selectedShield = GetSelectedShield(localPlayer);
				if (selectedShield == itemAt)
				{
					ShieldSelection.Clear(localPlayer.m_customData, "augusdogus.mods.shieldmebruhreforged");
				}
				else
				{
					ShieldSelection.Select(localPlayer.m_customData, itemAt.m_customData, "augusdogus.mods.shieldmebruhreforged");
				}
				RefreshSelection(_activeInstance);
				if (selectedShield != null && selectedShield != itemAt && selectedShield.m_equipped)
				{
					((Humanoid)localPlayer).EquipItem(itemAt, true);
				}
			}
		}

		public void RefreshSelection(InventoryGrid grid)
		{
			Player localPlayer = Player.m_localPlayer;
			if (localPlayer != null && grid.m_inventory == ((Humanoid)localPlayer).GetInventory())
			{
				_activeInstance = grid;
				ItemData selectedShield = GetSelectedShield(localPlayer);
				InventoryElement val = null;
				if (selectedShield != null && selectedShield.m_gridPos.x >= 0 && selectedShield.m_gridPos.x < grid.m_width && selectedShield.m_gridPos.y >= 0 && selectedShield.m_gridPos.y < grid.m_height)
				{
					val = grid.GetElement(selectedShield.m_gridPos.x, selectedShield.m_gridPos.y, grid.m_width);
				}
				if ((Object)(object)_currentElement != (Object)null && (Object)(object)_currentElement != (Object)(object)val)
				{
					((Behaviour)GetShield(_currentElement)).enabled = false;
				}
				_currentElement = val;
				if ((Object)(object)_currentElement != (Object)null)
				{
					((Behaviour)GetShield(_currentElement)).enabled = EnableAutoShield.Value;
				}
			}
		}

		public void ResetPlayerContext()
		{
			if ((Object)(object)_currentElement != (Object)null)
			{
				((Behaviour)GetShield(_currentElement)).enabled = false;
			}
			_currentElement = null;
			_activeInstance = null;
		}

		private Image GetShield(InventoryElement element)
		{
			Image val = null;
			if ((Object)(object)((Component)element).gameObject == (Object)null)
			{
				ShieldMeBruhReforged.Log.LogError((object)"Element.gameObject is null");
				return null;
			}
			if (((Component)element).gameObject.transform.childCount > 0)
			{
				for (int i = 0; i < ((Component)element).gameObject.transform.childCount; i++)
				{
					Image component = ((Component)((Component)element).gameObject.transform.GetChild(i)).GetComponent<Image>();
					if ((Object)(object)component != (Object)null && ((Object)((Component)component).transform).name == "shield")
					{
						val = component;
					}
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				ShieldMeBruhReforged.Log.LogDebug((object)("Image Null: " + ((Object)((Component)element).gameObject.transform).name));
				val = CreateShieldedImage(element.m_icon, element.m_noteleport);
			}
			return val;
		}
	}
	internal static class ShieldSelection
	{
		public static Guid? Read(IDictionary<string, string> data, string key)
		{
			if (!data.TryGetValue(key, out var value) || !Guid.TryParseExact(value, "N", out var result) || !(result != Guid.Empty))
			{
				return null;
			}
			return result;
		}

		public static bool IsSelected(IDictionary<string, string> character, IDictionary<string, string> item, string key)
		{
			Guid? guid = Read(character, key);
			if (guid.HasValue)
			{
				Guid valueOrDefault = guid.GetValueOrDefault();
				return Read(item, key) == valueOrDefault;
			}
			return false;
		}

		public static void Select(IDictionary<string, string> character, IDictionary<string, string> item, string key)
		{
			item[key] = (Read(item, key) ?? Guid.NewGuid()).ToString("N");
			character[key] = item[key];
		}

		public static void Clear(IDictionary<string, string> character, string key)
		{
			character.Remove(key);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}