Decompiled source of ItemCompare v0.2.0

ItemCompare.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("garcipat")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Compare an item's stats with the equipped one in its tooltip.")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0+097839e1ce5228e03934dff7327dca0e7f7e4278")]
[assembly: AssemblyProduct("Item Compare")]
[assembly: AssemblyTitle("ItemCompare")]
[assembly: AssemblyVersion("0.2.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 ValheimItemCompare
{
	internal static class ItemAccess
	{
		private static readonly FieldInfo Equipped = AccessTools.Field(typeof(ItemData), "m_equipped") ?? AccessTools.Field(typeof(ItemData), "m_equiped");

		private static readonly MethodInfo GetWeightMethod = AccessTools.Method(typeof(ItemData), "GetWeight", (Type[])null, (Type[])null);

		private static readonly FieldInfo HiddenLeft = AccessTools.Field(typeof(Humanoid), "m_hiddenLeftItem");

		private static readonly FieldInfo HiddenRight = AccessTools.Field(typeof(Humanoid), "m_hiddenRightItem");

		private static readonly FieldInfo ItemWorldLevel = AccessTools.Field(typeof(ItemData), "m_worldLevel");

		private static readonly FieldInfo GameWorldLevel = AccessTools.Field(typeof(Game), "m_worldLevel");

		internal static bool IsEquipped(ItemData item)
		{
			if (Equipped != null)
			{
				return (bool)Equipped.GetValue(item);
			}
			return false;
		}

		internal static float Weight(ItemData item)
		{
			if (GetWeightMethod == null)
			{
				return item.m_shared.m_weight;
			}
			object[] parameters = ((GetWeightMethod.GetParameters().Length == 0) ? null : new object[1] { -1 });
			return (float)GetWeightMethod.Invoke(item, parameters);
		}

		internal static bool IsHidden(Player player, ItemData item)
		{
			if (!(HiddenLeft != null) || HiddenLeft.GetValue(player) != item)
			{
				if (HiddenRight != null)
				{
					return HiddenRight.GetValue(player) == item;
				}
				return false;
			}
			return true;
		}

		internal static void SetCraftWorldLevel(ItemData item)
		{
			if (ItemWorldLevel != null && GameWorldLevel != null)
			{
				ItemWorldLevel.SetValue(item, GameWorldLevel.GetValue(null));
			}
		}
	}
	public enum CompareMode
	{
		Always,
		OnKeyPress
	}
	[BepInPlugin("dev.pgarcia.valheim.itemcompare", "Item Compare", "0.2.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "dev.pgarcia.valheim.itemcompare";

		public const string PluginName = "Item Compare";

		public const string PluginVersion = "0.2.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<CompareMode> Mode;

		internal static ConfigEntry<KeyboardShortcut> CompareKey;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0045: 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_0069: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Mode = ((BaseUnityPlugin)this).Config.Bind<CompareMode>("General", "Mode", CompareMode.Always, "Always: every equipment tooltip shows how it compares with what you wear. OnKeyPress: only while the compare key is held.");
			CompareKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("General", "CompareKey", new KeyboardShortcut((KeyCode)304, Array.Empty<KeyCode>()), "Key to hold while hovering an item to see the comparison. Only used when Mode is OnKeyPress.");
			_harmony = new Harmony("dev.pgarcia.valheim.itemcompare");
			_harmony.PatchAll();
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal static class StatDiff
	{
		private struct Stat
		{
			public string Label;

			public float Value;

			public string Format;

			public string Suffix;

			public bool HigherIsBetter;
		}

		private const string Better = "#6FE36F";

		private const string Worse = "#FF5A5A";

		private const int TwoHandedWeaponLeft = 22;

		private const int Trinket = 24;

		internal static ItemData FindWorn(ItemData item, Player player)
		{
			string text = GroupOf(item);
			if (text == null || ItemAccess.IsEquipped(item) || ItemAccess.IsHidden(player, item))
			{
				return null;
			}
			return FindEquipped(player, text);
		}

		internal static string Inline(string text, ItemData item, ItemData worn, string title)
		{
			string text2 = GroupOf(item);
			if (text2 == null || GroupOf(worn) != text2)
			{
				return text;
			}
			StringBuilder stringBuilder = new StringBuilder(text);
			StringBuilder stringBuilder2 = new StringBuilder();
			bool flag = false;
			Dictionary<string, Stat> dictionary = Stats(worn, text2);
			foreach (Stat value2 in Stats(item, text2).Values)
			{
				Stat value;
				Stat old = (dictionary.TryGetValue(value2.Label, out value) ? value : Zero(value2));
				dictionary.Remove(value2.Label);
				flag |= InsertDelta(stringBuilder, stringBuilder2, old, value2);
			}
			foreach (Stat value3 in dictionary.Values)
			{
				flag |= InsertDelta(stringBuilder, stringBuilder2, value3, Zero(value3));
			}
			if (!flag)
			{
				return text;
			}
			return stringBuilder.Append("\n<color=#AAAAAA>vs. ").Append(Localization.instance.Localize(title)).Append("</color>")
				.Append((object?)stringBuilder2)
				.ToString();
		}

		private static bool InsertDelta(StringBuilder text, StringBuilder extra, Stat old, Stat now)
		{
			if (Format(old) == Format(now))
			{
				return false;
			}
			bool flag = (now.HigherIsBetter ? (now.Value > old.Value) : (now.Value < old.Value));
			string text2 = "+" + now.Format + ";-" + now.Format;
			string value = " (<color=" + (flag ? "#6FE36F" : "#FF5A5A") + ">" + (now.Value - old.Value).ToString(text2, CultureInfo.InvariantCulture) + now.Suffix + "</color>)";
			string text3 = Localization.instance.Localize(now.Label);
			string text4 = text.ToString();
			int num = FindLine(text4, now.Label + ":");
			if (num < 0)
			{
				num = FindLine(text4, text3 + ":");
			}
			if (num < 0)
			{
				extra.Append("\n").Append(text3).Append(": ")
					.Append(Format(now))
					.Append(value);
				return true;
			}
			int num2 = text4.IndexOf('\n', num);
			if (num2 < 0)
			{
				num2 = text4.Length;
			}
			int num3 = text4.IndexOf("</color>", num, num2 - num, StringComparison.Ordinal);
			text.Insert((num3 < 0) ? num2 : (num3 + "</color>".Length), value);
			return true;
		}

		private static int FindLine(string text, string prefix)
		{
			for (int num = text.IndexOf(prefix, StringComparison.Ordinal); num >= 0; num = text.IndexOf(prefix, num + 1, StringComparison.Ordinal))
			{
				if (num == 0 || text[num - 1] == '\n')
				{
					return num;
				}
			}
			return -1;
		}

		private static string Format(Stat stat)
		{
			return stat.Value.ToString(stat.Format, CultureInfo.InvariantCulture) + stat.Suffix;
		}

		private static Stat Zero(Stat stat)
		{
			stat.Value = 0f;
			return stat;
		}

		private static string GroupOf(ItemData item)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected I4, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected I4, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected I4, but got Unknown
			switch ((int)item.m_shared.m_itemType)
			{
			case 3:
			case 4:
			case 14:
			case 22:
				return "weapon";
			case 5:
			case 15:
			case 19:
				return "hand" + (int)item.m_shared.m_itemType;
			case 6:
			case 7:
			case 11:
			case 17:
			case 18:
			case 24:
				return "armor" + (int)item.m_shared.m_itemType;
			default:
				return null;
			}
		}

		private static ItemData FindEquipped(Player player, string group)
		{
			foreach (ItemData allItem in ((Humanoid)player).GetInventory().GetAllItems())
			{
				if ((ItemAccess.IsEquipped(allItem) || ItemAccess.IsHidden(player, allItem)) && GroupOf(allItem) == group)
				{
					return allItem;
				}
			}
			return null;
		}

		private static Dictionary<string, Stat> Stats(ItemData item, string group)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: 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_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, Stat> stats = new Dictionary<string, Stat>();
			SharedData shared = item.m_shared;
			if (group == "weapon")
			{
				DamageTypes damage = item.GetDamage();
				Add("$inventory_damage", damage.m_damage, "0", higherIsBetter: true);
				Add("$inventory_blunt", damage.m_blunt, "0", higherIsBetter: true);
				Add("$inventory_slash", damage.m_slash, "0", higherIsBetter: true);
				Add("$inventory_pierce", damage.m_pierce, "0", higherIsBetter: true);
				Add("$inventory_fire", damage.m_fire, "0", higherIsBetter: true);
				Add("$inventory_frost", damage.m_frost, "0", higherIsBetter: true);
				Add("$inventory_lightning", damage.m_lightning, "0", higherIsBetter: true);
				Add("$inventory_poison", damage.m_poison, "0", higherIsBetter: true);
				Add("$inventory_spirit", damage.m_spirit, "0", higherIsBetter: true);
				Add("$item_knockback", shared.m_attackForce, "0.#", higherIsBetter: true);
				Add("$item_staminause", shared.m_attack.m_attackStamina, "0.#", higherIsBetter: false);
			}
			if (group == "weapon" || group.StartsWith("hand"))
			{
				Add("$item_blockarmor", item.GetBaseBlockPower(), "0.#", higherIsBetter: true);
				Add("$item_blockforce", item.GetDeflectionForce(), "0.#", higherIsBetter: true);
				Add("$item_parrybonus", (shared.m_timedBlockBonus > 1f) ? shared.m_timedBlockBonus : 0f, "0.##", higherIsBetter: true, "x");
			}
			if (group.StartsWith("armor"))
			{
				Add("$item_armor", item.GetArmor(), "0.#", higherIsBetter: true);
			}
			Add("$item_weight", ItemAccess.Weight(item), "0.0", higherIsBetter: false);
			if (shared.m_useDurability)
			{
				Add("$item_durability", item.GetMaxDurability(), "0", higherIsBetter: true);
			}
			Add("$item_movement_modifier", shared.m_movementModifier * 100f, "0.#", higherIsBetter: true, "%");
			return stats;
			void Add(string label, float value, string format, bool higherIsBetter, string suffix = "")
			{
				stats[label] = new Stat
				{
					Label = label,
					Value = value,
					Format = format,
					Suffix = suffix,
					HigherIsBetter = higherIsBetter
				};
			}
		}
	}
	internal static class BuildInfo
	{
		public const string Version = "0.2.0";
	}
}
namespace ValheimItemCompare.Patches
{
	[HarmonyPatch(typeof(InventoryGui), "UpdateRecipe")]
	internal static class RecipeComparePatch
	{
		private static readonly FieldInfo DescriptionField = AccessTools.Field(typeof(InventoryGui), "m_recipeDecription");

		private static void Postfix(InventoryGui __instance)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer == (Object)null || DescriptionField == null)
				{
					return;
				}
				if (Plugin.Mode.Value == CompareMode.OnKeyPress)
				{
					KeyboardShortcut value = Plugin.CompareKey.Value;
					if (!((KeyboardShortcut)(ref value)).IsPressed())
					{
						return;
					}
				}
				Traverse val = Traverse.Create((object)__instance).Field("m_selectedRecipe");
				Recipe val2 = val.Property("Recipe", (object[])null).GetValue<Recipe>() ?? val.Property("Key", (object[])null).GetValue<Recipe>();
				if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.m_item == (Object)null))
				{
					ItemData val3 = val.Property("ItemData", (object[])null).GetValue<ItemData>() ?? val.Property("Value", (object[])null).GetValue<ItemData>();
					ItemData val4;
					ItemData val5;
					string title;
					if (val3 != null)
					{
						val4 = val3.Clone();
						val4.m_quality = val3.m_quality + 1;
						val5 = val3;
						title = val3.m_shared.m_name + " (" + val3.m_quality + ")";
					}
					else
					{
						val4 = val2.m_item.m_itemData.Clone();
						val4.m_quality = 1;
						ItemAccess.SetCraftWorldLevel(val4);
						val5 = StatDiff.FindWorn(val4, localPlayer);
						title = val5?.m_shared.m_name;
					}
					object value2 = DescriptionField.GetValue(__instance);
					PropertyInfo propertyInfo = ((value2 == null) ? null : AccessTools.Property(value2.GetType(), "text"));
					if (val5 != null && propertyInfo != null)
					{
						propertyInfo.SetValue(value2, StatDiff.Inline((string)propertyInfo.GetValue(value2), val4, val5, title));
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogWarning((object)$"Recipe comparison failed: {arg}");
			}
		}
	}
	[HarmonyPatch]
	internal static class TooltipComparePatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			MethodInfo[] methods = typeof(ItemData).GetMethods(BindingFlags.Instance | BindingFlags.Public);
			foreach (MethodInfo methodInfo in methods)
			{
				if (methodInfo.Name == "GetTooltip")
				{
					yield return methodInfo;
				}
			}
		}

		private static void Postfix(ItemData __instance, ref string __result)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer == (Object)null || __instance?.m_shared == null)
				{
					return;
				}
				if (Plugin.Mode.Value == CompareMode.OnKeyPress)
				{
					KeyboardShortcut value = Plugin.CompareKey.Value;
					if (!((KeyboardShortcut)(ref value)).IsPressed())
					{
						return;
					}
				}
				ItemData val = StatDiff.FindWorn(__instance, localPlayer);
				if (val != null)
				{
					__result = StatDiff.Inline(__result, __instance, val, val.m_shared.m_name);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogWarning((object)$"Tooltip comparison failed: {arg}");
			}
		}
	}
}