Decompiled source of PoVPlus Gear v0.3.0

PoVPlus.Gear.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using HarmonyLib;
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("PoVPlus.Gear")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.3.0.0")]
[assembly: AssemblyInformationalVersion("0.3.0+c508b57fea1e28454dc9b591a952e24b6a86574e")]
[assembly: AssemblyProduct("PoVPlus.Gear")]
[assembly: AssemblyTitle("PoVPlus.Gear")]
[assembly: AssemblyVersion("0.3.0.0")]
namespace PoVPlus.Gear;

[BepInPlugin("avesatanas.povplus.gear", "PoVPlus.Gear", "0.3.0")]
public sealed class Plugin : BaseUnityPlugin
{
	private sealed class Gear
	{
		public string Name;

		public ItemData Item;

		public SharedData Shared;

		public string Class;

		public int Tier;

		public double Stat;

		public Dictionary<string, double> Mats;

		public string Property;

		public string Range;

		public object Def;

		public int Min;

		public int Max;

		public IList Row;

		public Gear Copy()
		{
			return (Gear)MemberwiseClone();
		}
	}

	private struct Choice
	{
		public string Property;

		public string Range;

		public string Via;

		public string Source;
	}

	private sealed class Ruling
	{
		public string Property;

		public string Range;

		public int Tier = -1;
	}

	public const string PluginGuid = "avesatanas.povplus.gear";

	public const string PluginName = "PoVPlus.Gear";

	public const string PluginVersion = "0.3.0";

	private const string MatchFile = "PoVPlus.Gear-matches.txt";

	private const ItemType Helmet = (ItemType)6;

	private const ItemType Chest = (ItemType)7;

	private const ItemType Legs = (ItemType)11;

	private const ItemType Cape = (ItemType)17;

	private const ItemType Shield = (ItemType)5;

	private static readonly string[] Ladder = new string[8] { "5-8", "6-10", "8-12", "9-15", "11-18", "12-20", "15-24", "17-28" };

	private const double WMat = 2.0;

	private const double WTier = 0.5;

	private const double WStat = 1.5;

	private const double WSet = 1.0;

	private const double WTool = 4.0;

	private const double WLine = 3.0;

	private const double WElem = 1.5;

	private const double WPhys = 0.5;

	private const double WCost = 2.0;

	private const double WAmmo = 1.0;

	private const double WAnim = 3.0;

	private const double WArmourMat = 1.0;

	private const double WArmourStat = 1.0;

	private const double Heavy = 0.9;

	private const int Nearest = 5;

	private const int FixedCount = 3;

	private const double FixedShare = 0.75;

	private const double RangeBase = 0.2;

	private const double RangeSame = 0.3;

	private static ManualLogSource _log;

	private static IDictionary _bases;

	private static MethodInfo _inherit;

	private static MethodInfo _register;

	private static MethodInfo _canHave;

	private static MethodInfo _classOf;

	private static MethodInfo _baseBiome;

	private static bool _given;

	private static ObjectDB _prefabsFor;

	private static readonly Dictionary<SharedData, GameObject> PrefabOf = new Dictionary<SharedData, GameObject>();

	private static readonly HashSet<string> GameBare = new HashSet<string>(StringComparer.Ordinal) { "PickaxeStone", "PlayerUnarmed", "SwordCheat", "SledgeCheat", "CapeTest", "SwordIronFire", "ShieldKnight" };

	private static readonly string[][] Element = new string[5][]
	{
		new string[2] { "fire", "base-fire-area" },
		new string[2] { "frost", "base-chill-buildup" },
		new string[2] { "lightning", "base-shock-buildup" },
		new string[2] { "poison", "base-poison-buildup" },
		new string[2] { "spirit", "base-curse-effect" }
	};

	private void Start()
	{
		//IL_0246: Unknown result type (might be due to invalid IL or missing references)
		//IL_024d: Expected O, but got Unknown
		//IL_0276: Unknown result type (might be due to invalid IL or missing references)
		//IL_0283: Expected O, but got Unknown
		//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_02dc: Expected O, but got Unknown
		_log = ((BaseUnityPlugin)this).Logger;
		if (!Chainloader.PluginInfos.TryGetValue("treextr.pathofvalheiman", out var value) || (Object)(object)value.Instance == (Object)null)
		{
			Disable("treextr.pathofvalheiman is not installed.");
			return;
		}
		Version version = new Version(6, 0, 6);
		if (value.Metadata.Version < version)
		{
			Disable("Path of Valheiman " + value.Metadata.Version?.ToString() + " is older than " + version?.ToString() + ", the version this was built for.");
			return;
		}
		try
		{
			Type[] types = Types(((object)value.Instance).GetType().Assembly);
			Type type = Type(types, "Implicits", "Inherit");
			_inherit = AccessTools.Method(type, "Inherit", new Type[2]
			{
				typeof(string),
				typeof(string)
			}, (Type[])null);
			_register = AccessTools.GetDeclaredMethods(type).FirstOrDefault((MethodInfo m) => m.Name == "Register" && m.IsStatic && m.GetParameters().Length == 4 && m.GetParameters()[0].ParameterType == typeof(string) && m.GetParameters()[2].ParameterType == typeof(int) && m.GetParameters()[3].ParameterType == typeof(int));
			_bases = AccessTools.Field(type, "bases")?.GetValue(null) as IDictionary;
			_canHave = AccessTools.Method(Type(types, "Rarity", "CanHave"), "CanHave", new Type[1] { typeof(ItemData) }, (Type[])null);
			Type type2 = Type(types, "ItemAscension", "ClassOf");
			_classOf = AccessTools.Method(type2, "ClassOf", new Type[2]
			{
				typeof(SharedData),
				typeof(string)
			}, (Type[])null);
			_baseBiome = AccessTools.Method(type2, "BaseBiome", new Type[1] { typeof(string) }, (Type[])null);
			if (_inherit == null || _register == null || _bases == null || _canHave == null || _classOf == null || _baseBiome == null)
			{
				throw new MissingMemberException("a Path of Valheiman member this plugin calls");
			}
			Harmony val = new Harmony("avesatanas.povplus.gear");
			val.Patch((MethodBase)AccessTools.Method(typeof(Game), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "GiveImplicits", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Active: mod weapons, shields and armour are given Path of Valheiman implicits.");
			try
			{
				val.Patch((MethodBase)AccessTools.Method(typeof(ItemData), "Save", new Type[1] { typeof(ZPackage) }, (Type[])null), new HarmonyMethod(typeof(Plugin), "KeepPrefab", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Active: items without a prefab are repaired before they are saved.");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Skipped (repairing items without a prefab): " + ex.Message));
			}
		}
		catch (Exception ex2)
		{
			Disable("an expected hook is missing (" + ex2.Message + ").");
		}
	}

	private void Disable(string why)
	{
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Disabled, nothing patched: " + why));
		((Behaviour)this).enabled = false;
	}

	private static Type[] Types(Assembly assembly)
	{
		try
		{
			return assembly.GetTypes();
		}
		catch (ReflectionTypeLoadException ex)
		{
			return ex.Types.Where((Type t) => t != null).ToArray();
		}
	}

	private static Type Type(Type[] types, string name, string method)
	{
		Type? type = types.FirstOrDefault((Type t) => t.Name == name && !t.IsNested && AccessTools.GetDeclaredMethods(t).Any((MethodInfo m) => m.Name == method));
		if (type == null)
		{
			throw new TypeLoadException(name + "." + method);
		}
		return type;
	}

	private static void GiveImplicits()
	{
		try
		{
			ObjectDB instance = ObjectDB.instance;
			if ((Object)(object)instance == (Object)null || _given)
			{
				return;
			}
			_inherit.Invoke(null, new object[2] { "", null });
			List<Gear> list = new List<Gear>();
			List<Gear> list2 = new List<Gear>();
			foreach (GameObject item in instance.m_items)
			{
				ItemDrop val = (((Object)(object)item != (Object)null) ? item.GetComponent<ItemDrop>() : null);
				SharedData val2 = val?.m_itemData?.m_shared;
				if (val2 != null && IsGear(val2))
				{
					ItemData val3 = val.m_itemData.Clone();
					val3.m_dropPrefab = item;
					bool flag = _bases.Contains(((Object)item).name);
					if (!((Object)item).name.StartsWith("PT_") && (flag || (val2.m_icons != null && val2.m_icons.Length != 0 && (bool)_canHave.Invoke(null, new object[1] { val3 }))) && (flag || (!IsFromGame(((Object)item).name) && !IsNpcGear(((Object)item).name))))
					{
						(flag ? list : list2).Add(Describe(item, val3, flag));
					}
				}
			}
			list.Sort((Gear a, Gear b) => string.CompareOrdinal(a.Name, b.Name));
			list2.Sort((Gear a, Gear b) => string.CompareOrdinal(a.Name, b.Name));
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			foreach (Gear item2 in list)
			{
				if (!dictionary.ContainsKey(item2.Property))
				{
					dictionary[item2.Property] = item2.Def;
				}
			}
			Dictionary<string, Gear> dictionary2 = new Dictionary<string, Gear>(StringComparer.Ordinal);
			foreach (Gear item3 in list)
			{
				if (item3.Shared.m_name != null && !dictionary2.ContainsKey(item3.Shared.m_name))
				{
					dictionary2[item3.Shared.m_name] = item3;
				}
			}
			foreach (Gear item4 in list2)
			{
				if (item4.Shared.m_name != null && dictionary2.TryGetValue(item4.Shared.m_name, out var value))
				{
					item4.Tier = value.Tier;
				}
			}
			Dictionary<string, Ruling> rulings = LoadRulings(dictionary);
			int num = 0;
			StringBuilder stringBuilder = new StringBuilder("item\tproperty\trange\tclosest vanilla item\tkind\ttier\tstat\tarmour class\tfrom\n");
			foreach (Gear item5 in list2)
			{
				Choice c = Assign(item5, list, dictionary, rulings);
				if (c.Property == null || !dictionary.TryGetValue(c.Property, out var value2) || !Split(c.Range, out var min, out var max))
				{
					stringBuilder.Append(item5.Name).Append("\t(none: no vanilla item of its kind has implicits)\n");
					continue;
				}
				_register.Invoke(null, new object[4] { item5.Name, value2, min, max });
				IList list3 = (c.Property.Contains(" (+") ? list.First((Gear v) => v.Property == c.Property).Row : null);
				int num2 = 1;
				while (list3 != null && num2 < list3.Count)
				{
					Type type = list3[num2].GetType();
					_register.Invoke(null, new object[4]
					{
						item5.Name,
						type.GetField("Item1").GetValue(list3[num2]),
						type.GetField("Item2").GetValue(list3[num2]),
						type.GetField("Item3").GetValue(list3[num2])
					});
					num2++;
				}
				num++;
				stringBuilder.Append(string.Join("\t", item5.Name, c.Property, c.Range, c.Via, Kind(item5), item5.Tier.ToString(), item5.Stat.ToString("0"), IsArmour(item5.Shared) ? WeightClass(item5) : "-", c.Source)).Append('\n');
			}
			_given = true;
			string path = Path.Combine(Paths.BepInExRootPath, "PoVPlus.Gear-matches.txt");
			try
			{
				File.WriteAllText(path, stringBuilder.ToString());
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Could not write PoVPlus.Gear-matches.txt: " + ex.Message));
			}
			_log.LogInfo((object)("Implicits given to " + num + " of " + list2.Count + " mod items, learned from " + list.Count + " vanilla items. Every assignment is listed in BepInEx/PoVPlus.Gear-matches.txt."));
		}
		catch (Exception ex2)
		{
			_log.LogWarning((object)("Implicits were not given this session: " + (ex2.InnerException ?? ex2)));
		}
	}

	private static bool IsFromGame(string prefab)
	{
		return GameBare.Contains(prefab);
	}

	private static bool IsNpcGear(string prefab)
	{
		if (!prefab.StartsWith("FW_", StringComparison.Ordinal) && !prefab.StartsWith("SP_", StringComparison.Ordinal))
		{
			return prefab.StartsWith("DvergerArbalest_shoot", StringComparison.Ordinal);
		}
		return true;
	}

	private static bool IsWeapon(SharedData s)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: 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_0009: Invalid comparison between Unknown and I4
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Invalid comparison between Unknown and I4
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Invalid comparison between Unknown and I4
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Invalid comparison between Unknown and I4
		ItemType itemType = s.m_itemType;
		if ((int)itemType != 3 && (int)itemType != 14 && (int)itemType != 22)
		{
			return (int)itemType == 4;
		}
		return true;
	}

	private static bool IsArmour(SharedData s)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: 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_0009: Invalid comparison between Unknown and I4
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Invalid comparison between Unknown and I4
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Invalid comparison between Unknown and I4
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Invalid comparison between Unknown and I4
		ItemType itemType = s.m_itemType;
		if ((int)itemType != 6 && (int)itemType != 7 && (int)itemType != 11)
		{
			return (int)itemType == 17;
		}
		return true;
	}

	private static bool IsGear(SharedData s)
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Invalid comparison between Unknown and I4
		if (!IsWeapon(s) && !IsArmour(s))
		{
			return (int)s.m_itemType == 5;
		}
		return true;
	}

	private static Gear Describe(GameObject prefab, ItemData item, bool known)
	{
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Invalid comparison between Unknown and I4
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		SharedData shared = item.m_shared;
		Gear gear = new Gear();
		gear.Name = ((Object)prefab).name;
		gear.Item = item;
		gear.Shared = shared;
		gear.Class = (_classOf.Invoke(null, new object[2]
		{
			shared,
			((Object)prefab).name
		}) as string) ?? "";
		gear.Tier = Tier((Biome)_baseBiome.Invoke(null, new object[1] { ((Object)prefab).name }));
		gear.Stat = (IsArmour(shared) ? shared.m_armor : (((int)shared.m_itemType == 5) ? shared.m_blockPower : Damage(shared.m_damages)));
		gear.Mats = new Dictionary<string, double>(StringComparer.Ordinal);
		Gear gear2 = gear;
		Recipe recipe = ObjectDB.instance.GetRecipe(item);
		if (recipe?.m_resources != null)
		{
			Requirement[] resources = recipe.m_resources;
			foreach (Requirement val in resources)
			{
				if (val != null && !((Object)(object)val.m_resItem == (Object)null))
				{
					string name = ((Object)((Component)val.m_resItem).gameObject).name;
					if (!name.StartsWith("Upgrader"))
					{
						gear2.Mats[name] = val.m_amount;
					}
				}
			}
		}
		if (known && _bases[((Object)prefab).name] is IList { Count: >0 } list)
		{
			object obj = list[0];
			Type type = obj.GetType();
			gear2.Def = type.GetField("Item1").GetValue(obj);
			gear2.Min = (int)type.GetField("Item2").GetValue(obj);
			gear2.Max = (int)type.GetField("Item3").GetValue(obj);
			gear2.Range = gear2.Min + "-" + gear2.Max;
			gear2.Row = list;
			gear2.Property = (AccessTools.Field(gear2.Def.GetType(), "Id")?.GetValue(gear2.Def) ?? gear2.Def).ToString() + ((list.Count > 1) ? (" (+" + (list.Count - 1) + ")") : "");
		}
		return gear2;
	}

	private static int Tier(Biome biome)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Invalid comparison between Unknown and I4
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Invalid comparison between Unknown and I4
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Invalid comparison between Unknown and I4
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Invalid comparison between Unknown and I4
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Invalid comparison between Unknown and I4
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Invalid comparison between Unknown and I4
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Invalid comparison between Unknown and I4
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Invalid comparison between Unknown and I4
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Invalid comparison between Unknown and I4
		if ((int)biome <= 8)
		{
			if ((int)biome == 2)
			{
				return 2;
			}
			if ((int)biome == 4)
			{
				return 3;
			}
			if ((int)biome == 8)
			{
				return 1;
			}
		}
		else if ((int)biome <= 32)
		{
			if ((int)biome == 16)
			{
				return 4;
			}
			if ((int)biome == 32)
			{
				return 6;
			}
		}
		else
		{
			if ((int)biome == 64)
			{
				return 7;
			}
			if ((int)biome == 512)
			{
				return 5;
			}
		}
		return 0;
	}

	private static float Damage(DamageTypes d)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: 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_0030: Unknown result type (might be due to invalid IL or missing references)
		return d.m_blunt + d.m_slash + d.m_pierce + d.m_fire + d.m_frost + d.m_lightning + d.m_poison + d.m_spirit;
	}

	private static string Kind(Gear g)
	{
		if (g.Class.Length <= 0)
		{
			return ((object)Unsafe.As<ItemType, ItemType>(ref g.Shared.m_itemType)/*cast due to .constrained prefix*/).ToString();
		}
		return g.Class;
	}

	private static bool Split(string range, out int min, out int max)
	{
		min = (max = 0);
		int num = range?.IndexOf('-') ?? (-1);
		if (num > 0 && int.TryParse(range.Substring(0, num), out min))
		{
			return int.TryParse(range.Substring(num + 1), out max);
		}
		return false;
	}

	private static Choice Predict(Gear item, List<Gear> pool)
	{
		string via;
		string text = PickProperty(item, pool, out via);
		if (text != null)
		{
			return new Choice
			{
				Property = text,
				Range = PickRange(item, text, pool),
				Via = via
			};
		}
		return default(Choice);
	}

	private static double MatSim(Gear a, Gear b)
	{
		if (a.Mats.Count == 0 || b.Mats.Count == 0)
		{
			return 0.0;
		}
		double num = a.Mats.Values.Sum();
		double num2 = b.Mats.Values.Sum();
		double num3 = 0.0;
		if (num == 0.0)
		{
			num = 1.0;
		}
		if (num2 == 0.0)
		{
			num2 = 1.0;
		}
		foreach (KeyValuePair<string, double> mat in a.Mats)
		{
			if (b.Mats.TryGetValue(mat.Key, out var value))
			{
				num3 += Math.Min(mat.Value / num, value / num2);
			}
		}
		return num3;
	}

	private static string WeightClass(Gear g)
	{
		if (g.Shared.m_armor <= 2f)
		{
			return "clothes";
		}
		if (g.Shared.m_eitrRegenModifier > 0f)
		{
			return "mage";
		}
		if (!((double)g.Shared.m_armor >= 0.9 * (double)(6 * g.Tier + 2)))
		{
			return "medium";
		}
		return "heavy";
	}

	private static List<Gear> KindPool(Gear item, List<Gear> pool)
	{
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Invalid comparison between Unknown and I4
		SharedData s = item.Shared;
		List<Func<Gear, bool>> list = new List<Func<Gear, bool>>();
		if (item.Class.Length > 0)
		{
			list.Add((Gear d) => d.Class == item.Class);
		}
		if (IsArmour(s) || (int)s.m_itemType == 5)
		{
			list.Add((Gear d) => d.Shared.m_itemType == s.m_itemType);
		}
		else
		{
			list.Add((Gear d) => d.Shared.m_skillType == s.m_skillType && d.Shared.m_itemType == s.m_itemType);
			list.Add((Gear d) => d.Shared.m_skillType == s.m_skillType);
			list.Add((Gear d) => d.Shared.m_itemType == s.m_itemType);
			list.Add((Gear d) => IsWeapon(d.Shared));
		}
		foreach (Func<Gear, bool> item2 in list)
		{
			List<Gear> list2 = pool.Where(item2).ToList();
			if (list2.Count > 0)
			{
				return list2;
			}
		}
		return new List<Gear>();
	}

	private static double Distance(Gear a, Gear b)
	{
		//IL_010d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Invalid comparison between Unknown and I4
		//IL_0131: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		double num = 2.0 * (1.0 - MatSim(a, b)) + 0.5 * (double)Math.Abs(a.Tier - b.Tier);
		if (a.Stat > 0.0 && b.Stat > 0.0)
		{
			num += 1.5 * Math.Abs(Math.Log(a.Stat / b.Stat));
		}
		SharedData shared = a.Shared;
		SharedData shared2 = b.Shared;
		if (!string.IsNullOrEmpty(shared.m_setName) && shared.m_setName == shared2.m_setName)
		{
			num -= 1.0;
		}
		if (b.Mats.ContainsKey(a.Name) || a.Mats.ContainsKey(b.Name))
		{
			num -= 3.0;
		}
		if (shared.m_maxQuality > 1 != shared2.m_maxQuality > 1)
		{
			num += 4.0;
		}
		if ((int)shared.m_itemType == 5)
		{
			num += (double)Math.Abs(shared.m_timedBlockBonus - shared2.m_timedBlockBonus);
		}
		else
		{
			if (Elements(shared.m_damages) != Elements(shared2.m_damages))
			{
				num += 1.5;
			}
			if (Physical(shared.m_damages) != Physical(shared2.m_damages))
			{
				num += 0.5;
			}
			Attack attack = shared.m_attack;
			bool num2 = attack != null && attack.m_attackEitr > 0f;
			Attack attack2 = shared2.m_attack;
			if (num2 != (attack2 != null && attack2.m_attackEitr > 0f))
			{
				num += 2.0;
			}
			if ((shared.m_ammoType ?? "") != (shared2.m_ammoType ?? ""))
			{
				num += 1.0;
			}
			string text = shared.m_attack?.m_attackAnimation;
			if (!string.IsNullOrEmpty(text) && text == shared2.m_attack?.m_attackAnimation)
			{
				num -= 3.0;
			}
		}
		return num;
	}

	private static int Elements(DamageTypes d)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		return (int)(((d.m_fire > 0f) ? 1u : 0u) | (uint)((d.m_frost > 0f) ? 2 : 0) | (uint)((d.m_lightning > 0f) ? 4 : 0) | (uint)((d.m_poison > 0f) ? 8 : 0)) | ((d.m_spirit > 0f) ? 16 : 0);
	}

	private static int Physical(DamageTypes d)
	{
		//IL_0000: 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_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		if (d.m_blunt <= 0f && d.m_slash <= 0f && d.m_pierce <= 0f)
		{
			return 0;
		}
		if (!(d.m_blunt >= d.m_slash) || !(d.m_blunt >= d.m_pierce))
		{
			if (!(d.m_slash >= d.m_pierce))
			{
				return 3;
			}
			return 2;
		}
		return 1;
	}

	private static string Winner(Dictionary<string, double> votes)
	{
		string text = null;
		foreach (string item in votes.Keys.OrderBy<string, string>((string k) => k, StringComparer.Ordinal))
		{
			if (text == null || votes[item] > votes[text])
			{
				text = item;
			}
		}
		return text;
	}

	private static void Vote(Dictionary<string, double> votes, string key, double weight)
	{
		votes.TryGetValue(key, out var value);
		votes[key] = value + weight;
	}

	private static string PickProperty(Gear item, List<Gear> pool, out string via)
	{
		via = null;
		List<Gear> list = KindPool(item, pool);
		if (list.Count == 0)
		{
			return null;
		}
		Dictionary<string, double> votes = new Dictionary<string, double>();
		if (IsArmour(item.Shared))
		{
			string cls = WeightClass(item);
			List<Gear> list2 = list.Where((Gear d) => WeightClass(d) == cls).ToList();
			if (list2.Count == 0)
			{
				list2 = list;
			}
			Func<Gear, double> func = delegate(Gear d)
			{
				double num2 = 1.0 * (1.0 - MatSim(item, d));
				if (item.Shared.m_armor > 0f && d.Shared.m_armor > 0f)
				{
					num2 += 1.0 * Math.Abs(Math.Log((double)item.Shared.m_armor / (double)d.Shared.m_armor));
				}
				return num2;
			};
			List<Gear> list3 = list2.OrderBy(func).ThenBy<Gear, string>((Gear d) => d.Name, StringComparer.Ordinal).ToList();
			foreach (Gear item2 in list3)
			{
				Vote(votes, item2.Property, 1.0 / (0.5 + func(item2)));
			}
			via = list3[0].Name;
			return Winner(votes);
		}
		List<Gear> list4 = list.OrderBy((Gear d) => Distance(item, d)).ThenBy<Gear, string>((Gear d) => d.Name, StringComparer.Ordinal).Take(5)
			.ToList();
		double num = Distance(item, list4[0]);
		foreach (Gear item3 in list4)
		{
			Vote(votes, item3.Property, 1.0 / (0.5 + Distance(item, item3) - num));
		}
		via = list4[0].Name;
		return Winner(votes);
	}

	private static string PickRange(Gear item, string property, List<Gear> pool)
	{
		List<Gear> list = pool.Where((Gear d) => d.Property == property).ToList();
		string result = null;
		int num = 0;
		Dictionary<string, int> dictionary = new Dictionary<string, int>();
		foreach (Gear item2 in list)
		{
			dictionary.TryGetValue(item2.Range, out var value);
			value = (dictionary[item2.Range] = value + 1);
		}
		foreach (Gear item3 in list)
		{
			if (dictionary[item3.Range] > num)
			{
				result = item3.Range;
				num = dictionary[item3.Range];
			}
		}
		if (list.Count >= 3 && (double)num >= 0.75 * (double)list.Count)
		{
			return result;
		}
		if (list.Count > 0 && !list.Any((Gear d) => Array.IndexOf(Ladder, d.Range) >= 0))
		{
			return list.OrderBy((Gear d) => Math.Abs(d.Tier - item.Tier)).ThenBy<Gear, string>((Gear d) => d.Name, StringComparer.Ordinal).First()
				.Range;
		}
		Dictionary<string, double> dictionary2 = new Dictionary<string, double>();
		foreach (Gear item4 in pool)
		{
			if (item4.Tier == item.Tier && Array.IndexOf(Ladder, item4.Range) >= 0)
			{
				Vote(dictionary2, item4.Range, 0.2 + MatSim(item, item4) + ((item4.Property == property) ? 0.3 : 0.0));
			}
		}
		if (dictionary2.Count <= 0)
		{
			return Ladder[Math.Max(0, Math.Min(7, item.Tier))];
		}
		return Winner(dictionary2);
	}

	private static float ElementDamage(DamageTypes d, string e)
	{
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: 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)
		return e switch
		{
			"fire" => d.m_fire, 
			"frost" => d.m_frost, 
			"lightning" => d.m_lightning, 
			"poison" => d.m_poison, 
			_ => d.m_spirit, 
		};
	}

	private static string Rule(Gear item, List<Gear> pool, out string source)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Invalid comparison between Unknown and I4
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Invalid comparison between Unknown and I4
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Invalid comparison between Unknown and I4
		//IL_0049: 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)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		SharedData shared = item.Shared;
		source = null;
		if (IsArmour(shared) || (int)shared.m_itemType == 5)
		{
			return null;
		}
		if ((int)shared.m_skillType == 9 || (int)shared.m_skillType == 10)
		{
			string[] array = Element[0];
			string[][] element = Element;
			foreach (string[] array2 in element)
			{
				if (ElementDamage(shared.m_damages, array2[0]) > ElementDamage(shared.m_damages, array[0]))
				{
					array = array2;
				}
			}
			if (ElementDamage(shared.m_damages, array[0]) > 0f)
			{
				source = "rule: element";
				return array[1];
			}
		}
		if ((shared.m_attack?.m_attackAnimation ?? "").IndexOf("dual", StringComparison.OrdinalIgnoreCase) >= 0)
		{
			Dictionary<string, double> dictionary = new Dictionary<string, double>();
			string text = ((object)Unsafe.As<SkillType, SkillType>(ref shared.m_skillType)/*cast due to .constrained prefix*/).ToString() + "/1h";
			foreach (Gear item2 in pool)
			{
				if (item2.Class == text)
				{
					Vote(dictionary, item2.Property, 1.0);
				}
			}
			if (dictionary.Count > 0)
			{
				source = "rule: dual";
				return Winner(dictionary);
			}
		}
		return null;
	}

	private static string RuledRange(Gear item, string property, List<Gear> pool)
	{
		string text = PickRange(item, property, pool);
		if (Array.IndexOf(Ladder, text) >= 0 || pool.Any((Gear d) => d.Property == property && d.Tier == item.Tier))
		{
			return text;
		}
		return Ladder[Math.Max(0, Math.Min(7, item.Tier))];
	}

	private static Dictionary<string, Ruling> LoadRulings(Dictionary<string, object> defs)
	{
		Dictionary<string, Ruling> dictionary = new Dictionary<string, Ruling>(StringComparer.Ordinal);
		using Stream stream = typeof(Plugin).Assembly.GetManifestResourceStream("rulings.txt");
		if (stream == null)
		{
			_log.LogWarning((object)"rulings.txt is missing from the DLL; no single-item rulings this session.");
			return dictionary;
		}
		StreamReader streamReader = new StreamReader(stream);
		string text;
		while ((text = streamReader.ReadLine()) != null)
		{
			string[] array = text.Split(new char[1] { '#' })[0].Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
			if (array.Length >= 2)
			{
				Ruling ruling = new Ruling
				{
					Property = array[1]
				};
				if (array.Length > 2 && int.TryParse(array[2], out var result))
				{
					ruling.Tier = result;
				}
				else if (array.Length > 2 && array[2].Contains("-"))
				{
					ruling.Range = array[2];
				}
				if (ruling.Property != "learned" && !defs.ContainsKey(ruling.Property))
				{
					_log.LogWarning((object)("rulings.txt: " + array[0] + " names " + ruling.Property + ", which no vanilla item has; the property is left to the rules."));
				}
				dictionary[array[0]] = ruling;
			}
		}
		return dictionary;
	}

	private static Choice Assign(Gear item, List<Gear> pool, Dictionary<string, object> defs, Dictionary<string, Ruling> rulings)
	{
		if (rulings.TryGetValue(item.Name, out var value) && value.Tier >= 0)
		{
			item = item.Copy();
			item.Tier = value.Tier;
		}
		Choice result = Predict(item, pool);
		if (result.Property == null)
		{
			return result;
		}
		result.Source = "learned";
		if (value != null)
		{
			result.Source = "ruling";
			if (defs.ContainsKey(value.Property) && value.Property != result.Property)
			{
				result.Property = value.Property;
				result.Range = RuledRange(item, value.Property, pool);
			}
			if (value.Range != null)
			{
				result.Range = value.Range;
			}
			return result;
		}
		string source;
		string text = Rule(item, pool, out source);
		if (text != null && defs.ContainsKey(text))
		{
			result.Source = source;
			if (text != result.Property)
			{
				result.Property = text;
				result.Range = RuledRange(item, text, pool);
			}
		}
		return result;
	}

	private static void KeepPrefab(ItemData __instance)
	{
		if ((Object)(object)__instance.m_dropPrefab != (Object)null || __instance.m_shared == null)
		{
			return;
		}
		ObjectDB instance = ObjectDB.instance;
		if ((Object)(object)instance == (Object)null)
		{
			return;
		}
		if ((Object)(object)_prefabsFor != (Object)(object)instance)
		{
			PrefabOf.Clear();
			foreach (GameObject item in instance.m_items)
			{
				SharedData val = ((!((Object)(object)item != (Object)null)) ? null : item.GetComponent<ItemDrop>()?.m_itemData?.m_shared);
				if (val != null)
				{
					PrefabOf[val] = item;
				}
			}
			_prefabsFor = instance;
		}
		if (PrefabOf.TryGetValue(__instance.m_shared, out var value))
		{
			__instance.m_dropPrefab = value;
			_log.LogWarning((object)("An item had no prefab and would have been lost on save; restored it as " + ((Object)value).name + "."));
		}
	}
}