using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Jotunn.Utils; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.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 Niflheim.ToolTiers { internal static class ModInfo { internal const string Guid = "niflheim.hammertiers"; internal const string Name = "HammerTiers"; internal const string Version = "0.3.0"; internal const string DefaultTool = "Hammer"; } [BepInPlugin("niflheim.hammertiers", "HammerTiers", "0.3.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public class ToolTiersPlugin : BaseUnityPlugin { public const string PluginGuid = "niflheim.hammertiers"; public const string PluginName = "HammerTiers"; public const string PluginVersion = "0.3.0"; public const string JotunnGuid = "com.jotunn.jotunn"; internal static ManualLogSource Log; internal static ConfigEntry ToolPrefabName; internal static ConfigEntry TierSpec; internal static ConfigEntry ReplaceVanillaUpgrades; internal static ConfigEntry BaseMaterialsPerLevel; internal static ConfigEntry PlaceDistancePerLevel; internal static ConfigEntry Verbose; private static ConfigDescription Admin(string description) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown ConfigurationManagerAttributes val = new ConfigurationManagerAttributes(); val.IsAdminOnly = true; return new ConfigDescription(description, (AcceptableValueBase)null, new object[1] { val }); } private void Awake() { //IL_00fa: Unknown result type (might be due to invalid IL or missing references) Log = ((BaseUnityPlugin)this).Logger; ToolPrefabName = ((BaseUnityPlugin)this).Config.Bind("General", "ToolPrefab", "Hammer", Admin("Tool to add levels to. Hammer, Hoe and Cultivator all work.")); TierSpec = ((BaseUnityPlugin)this).Config.Bind("General", "Tiers", "Tin:3:300,Copper:3:300,Bronze:3:300,Iron:3:300,Silver:3:500,BlackMetal:3:500,FlametalNew:3:500,Gold:3:2000", Admin("One entry per added level, in order: Prefab:Amount:Durability. Durability is the extra max durability that level grants, and they add up. Optional. Unknown prefabs are skipped, so a typo costs you a level silently. Two prefab names do not match what the game calls them. The flametal bar is FlametalNew; plain Flametal is the old unusable one. Bloodgold, the Deep North metal, is Gold, and its ore is GoldOre.")); ReplaceVanillaUpgrades = ((BaseUnityPlugin)this).Config.Bind("General", "ReplaceVanillaUpgrades", false, Admin("true = metal levels start at 2 and replace the tool's own upgrades instead of stacking after them.")); BaseMaterialsPerLevel = ((BaseUnityPlugin)this).Config.Bind("General", "BaseMaterialsPerLevel", 1, Admin("Wood and stone per metal level, times the level. 0 = metal only.")); PlaceDistancePerLevel = ((BaseUnityPlugin)this).Config.Bind("Effects", "PlaceDistancePerLevel", 1f, Admin("Extra build reach per metal level. 0 = off.")); Verbose = ((BaseUnityPlugin)this).Config.Bind("General", "Verbose", false, Admin("Extra logging.")); new Harmony("niflheim.hammertiers").PatchAll(Assembly.GetExecutingAssembly()); Log.LogInfo((object)"HammerTiers 0.3.0 loaded."); } } internal static class ToolTiers { private sealed class ReferenceComparer : IEqualityComparer { public bool Equals(Requirement a, Requirement b) { return a == b; } public int GetHashCode(Requirement o) { return RuntimeHelpers.GetHashCode(o); } } internal static ItemDrop ToolDrop; internal static Recipe ToolRecipe; internal static Requirement[][] ByQuality; internal static int VanillaMaxQuality = 1; internal static Requirement[] TierRequirements = (Requirement[])(object)new Requirement[0]; internal static int FirstMetalLevel = 2; internal static int FullMaxQuality = 1; internal static string[] TierMaterialNames = new string[0]; internal static float[] TierDurability = new float[0]; private static int _lastCap = -1; private static bool _loggedDiag; private static FieldRef _containerRef; private static bool _containerRefResolved; private static readonly HashSet TierSet = new HashSet(new ReferenceComparer()); private static SharedData _capturedShared; private static Requirement[] _baseResources; private static string _lastSummary; internal static bool TryGetMaxDurability(ItemData item, int quality, out float result) { result = 0f; if ((Object)(object)ToolDrop == (Object)null || item == null || item.m_shared == null) { return false; } if (item.m_shared.m_name != ToolDrop.m_itemData.m_shared.m_name) { return false; } if (TierDurability.Length == 0) { return false; } int num = FirstMetalLevel - 1; if (quality <= num) { return false; } float num2 = item.m_shared.m_maxDurability + (float)Mathf.Max(0, num - 1) * item.m_shared.m_durabilityPerLevel; for (int i = 0; i < TierDurability.Length && FirstMetalLevel + i <= quality; i++) { num2 += TierDurability[i]; } result = num2; return true; } internal static void LogDiagnosticsOnce() { if (_loggedDiag || !ToolTiersPlugin.Verbose.Value) { return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)ToolDrop == (Object)null) { return; } _loggedDiag = true; SharedData shared = ToolDrop.m_itemData.m_shared; ToolTiersPlugin.Log.LogInfo((object)("prefab max=" + shared.m_maxQuality + " full=" + FullMaxQuality + " firstMetal=" + FirstMetalLevel)); for (int i = 0; i < TierMaterialNames.Length; i++) { ToolTiersPlugin.Log.LogInfo((object)(" level " + (FirstMetalLevel + i) + " " + TierMaterialNames[i] + " known=" + localPlayer.IsKnownMaterial(TierMaterialNames[i]))); } Inventory inventory = ((Humanoid)localPlayer).GetInventory(); if (inventory == null) { ToolTiersPlugin.Log.LogInfo((object)" no inventory"); return; } List allItems = inventory.GetAllItems(); for (int j = 0; j < allItems.Count; j++) { ItemData val = allItems[j]; if (val != null && val.m_shared != null && !(val.m_shared.m_name != shared.m_name)) { TryGetMaxDurability(val, val.m_quality, out var result); ToolTiersPlugin.Log.LogInfo((object)(" held quality=" + val.m_quality + " max=" + val.m_shared.m_maxQuality + " durability=" + result)); } } } internal static void ApplyKnownMaterialCap() { if ((Object)(object)ToolDrop == (Object)null || TierMaterialNames.Length == 0) { return; } Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { int num = FirstMetalLevel - 1; for (int i = 0; i < TierMaterialNames.Length && localPlayer.IsKnownMaterial(TierMaterialNames[i]); i++) { num = FirstMetalLevel + i; } if (num > FullMaxQuality) { num = FullMaxQuality; } if (num < 1) { num = 1; } ToolDrop.m_itemData.m_shared.m_maxQuality = num; CapInventory(((Humanoid)localPlayer).GetInventory(), num); Container openContainer = GetOpenContainer(); if ((Object)(object)openContainer != (Object)null) { CapInventory(openContainer.GetInventory(), num); } if (num != _lastCap) { _lastCap = num; ToolTiersPlugin.Log.LogInfo((object)("Max upgrade level: " + num + " of " + FullMaxQuality)); } } } private static Container GetOpenContainer() { InventoryGui instance = InventoryGui.instance; if ((Object)(object)instance == (Object)null) { return null; } if (!_containerRefResolved) { _containerRefResolved = true; try { _containerRef = AccessTools.FieldRefAccess("m_currentContainer"); } catch (Exception ex) { ToolTiersPlugin.Log.LogWarning((object)("Could not read m_currentContainer (" + ex.GetType().Name + "), chest contents will show the uncapped max.")); _containerRef = null; } } if (_containerRef != null) { return _containerRef.Invoke(instance); } return null; } private static void CapInventory(Inventory inventory, int allowed) { if (inventory == null || (Object)(object)ToolDrop == (Object)null) { return; } string name = ToolDrop.m_itemData.m_shared.m_name; List allItems = inventory.GetAllItems(); for (int i = 0; i < allItems.Count; i++) { ItemData val = allItems[i]; if (val != null && val.m_shared != null && val.m_shared.m_name == name) { val.m_shared.m_maxQuality = allowed; } } } internal static bool TryGetFlatAmount(Requirement req, out int amount) { if (req != null && TierSet.Contains(req)) { amount = req.m_amount; return true; } amount = 0; return false; } internal static void Build(ObjectDB odb) { //IL_03b5: Unknown result type (might be due to invalid IL or missing references) //IL_03bc: Expected O, but got Unknown if ((Object)(object)odb == (Object)null || odb.m_items == null || odb.m_items.Count == 0 || odb.m_recipes == null || odb.m_recipes.Count == 0) { return; } string value = ToolTiersPlugin.ToolPrefabName.Value; GameObject itemPrefab = odb.GetItemPrefab(value); if ((Object)(object)itemPrefab == (Object)null) { ToolTiersPlugin.Log.LogWarning((object)("Tool prefab '" + value + "' not found.")); return; } ItemDrop component = itemPrefab.GetComponent(); if ((Object)(object)component == (Object)null || component.m_itemData == null || component.m_itemData.m_shared == null) { ToolTiersPlugin.Log.LogWarning((object)("Prefab '" + value + "' has no ItemDrop.")); return; } Recipe val = null; for (int i = 0; i < odb.m_recipes.Count; i++) { Recipe val2 = odb.m_recipes[i]; if ((Object)(object)val2 != (Object)null && (Object)(object)val2.m_item == (Object)(object)component) { val = val2; break; } } if ((Object)(object)val == (Object)null) { ToolTiersPlugin.Log.LogWarning((object)("No recipe for '" + value + "'.")); return; } SharedData shared = component.m_itemData.m_shared; if ((Object)(object)ToolRecipe == (Object)(object)val && _baseResources != null) { val.m_resources = _baseResources; } if (_capturedShared != shared) { _capturedShared = shared; _baseResources = val.m_resources; VanillaMaxQuality = Mathf.Max(1, shared.m_maxQuality); ToolTiersPlugin.Log.LogInfo((object)(value + " base max quality: " + VanillaMaxQuality)); ToolTiersPlugin.Log.LogInfo((object)(" durability: " + shared.m_maxDurability + " +" + shared.m_durabilityPerLevel + "/level, drain " + shared.m_useDurabilityDrain + (shared.m_useDurability ? "" : " [m_useDurability is FALSE - this tool never wears down]"))); for (int j = 0; j < _baseResources.Length; j++) { Requirement val3 = _baseResources[j]; if (val3 != null && !((Object)(object)val3.m_resItem == (Object)null)) { ToolTiersPlugin.Log.LogInfo((object)(" base: " + ((Object)val3.m_resItem).name + " x" + val3.m_amount + " (+" + val3.m_amountPerLevel + "/level)" + (val3.m_upgraderResource ? " [Forge of Potential ingredient, left alone]" : ""))); } } } List list = new List(); List list2 = ResolveTiers(odb, list, shared.m_durabilityPerLevel); if (list2.Count == 0) { ToolTiersPlugin.Log.LogWarning((object)("No tier materials found, leaving '" + value + "' alone.")); return; } int num = (ToolTiersPlugin.ReplaceVanillaUpgrades.Value ? 2 : (VanillaMaxQuality + 1)); int num2 = num - 1 + list2.Count; int value2 = ToolTiersPlugin.BaseMaterialsPerLevel.Value; List list3 = new List(list2); Requirement[][] array = new Requirement[num2 + 1][]; for (int k = 1; k < num && k <= num2; k++) { array[k] = _baseResources; } for (int l = 0; l < list2.Count; l++) { int num3 = num + l; List list4 = new List(); list4.Add(list2[l]); if (value2 > 0) { for (int m = 0; m < _baseResources.Length; m++) { Requirement val4 = _baseResources[m]; if (val4 != null && !((Object)(object)val4.m_resItem == (Object)null) && !val4.m_upgraderResource) { Requirement val5 = new Requirement(); val5.m_resItem = val4.m_resItem; val5.m_amount = value2 * num3; val5.m_amountPerLevel = 0; list4.Add(val5); list3.Add(val5); } } } array[num3] = list4.ToArray(); } TierRequirements = list3.ToArray(); TierSet.Clear(); for (int n = 0; n < TierRequirements.Length; n++) { TierSet.Add(TierRequirements[n]); } string text = ""; for (int num4 = 0; num4 < list2.Count; num4++) { int num5 = num + num4; float result; string text2 = (TryGetMaxDurability(component.m_itemData, num5, out result) ? (" (durability " + result + ")") : ""); text = text + "Level " + num5 + " requires " + Describe(array[num5], num5) + text2 + "\n"; } if (text != _lastSummary) { _lastSummary = text; string[] array2 = text.Split(new char[1] { '\n' }); foreach (string text3 in array2) { if (text3.Length > 0) { ToolTiersPlugin.Log.LogInfo((object)text3); } } } string[] array3 = new string[list2.Count]; for (int num7 = 0; num7 < list2.Count; num7++) { array3[num7] = list2[num7].m_resItem.m_itemData.m_shared.m_name; } ToolDrop = component; ToolRecipe = val; ByQuality = array; FirstMetalLevel = num; FullMaxQuality = num2; TierMaterialNames = array3; TierDurability = list.ToArray(); _lastCap = -1; shared.m_maxQuality = num2; val.m_resources = _baseResources; if (text != "") { ToolTiersPlugin.Log.LogInfo((object)(value + " max quality " + VanillaMaxQuality + " -> " + num2 + " (" + list2.Count + " metal levels from " + num + ").")); } } private static string Describe(Requirement[] set, int level) { string text = ""; for (int i = 0; i < set.Length; i++) { if (set[i] == null || (Object)(object)set[i].m_resItem == (Object)null) { continue; } int amount = set[i].GetAmount(level); if (amount > 0) { if (text.Length > 0) { text += ", "; } text = text + amount + "x " + ((Object)set[i].m_resItem).name; } } return text; } private static List ResolveTiers(ObjectDB odb, List durability, float vanillaPerLevel) { //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Expected O, but got Unknown List list = new List(); string[] array = ToolTiersPlugin.TierSpec.Value.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length != 0) { string[] array2 = text.Split(new char[1] { ':' }); string text2 = array2[0].Trim(); int result = 1; float result2 = vanillaPerLevel; if (array2.Length > 1 && array2[1].Trim().Length > 0 && (!int.TryParse(array2[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out result) || result < 1)) { ToolTiersPlugin.Log.LogWarning((object)("Bad amount in '" + text + "', using 1.")); result = 1; } if (array2.Length > 2 && array2[2].Trim().Length > 0 && (!float.TryParse(array2[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out result2) || result2 < 0f)) { ToolTiersPlugin.Log.LogWarning((object)("Bad durability in '" + text + "', using " + vanillaPerLevel + ".")); result2 = vanillaPerLevel; } GameObject itemPrefab = odb.GetItemPrefab(text2); ItemDrop val = (((Object)(object)itemPrefab == (Object)null) ? null : itemPrefab.GetComponent()); if ((Object)(object)val == (Object)null) { ToolTiersPlugin.Log.LogWarning((object)("'" + text2 + "' not found, skipping that level.")); continue; } Requirement val2 = new Requirement(); val2.m_resItem = val; val2.m_amount = result; val2.m_amountPerLevel = 0; list.Add(val2); durability.Add(result2); } } return list; } internal static void RestoreVanillaResources() { if ((Object)(object)ToolRecipe != (Object)null && _baseResources != null) { ToolRecipe.m_resources = _baseResources; } } private static bool AtUpgraderStation() { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return false; } CraftingStation currentCraftingStation = localPlayer.GetCurrentCraftingStation(); if ((Object)(object)currentCraftingStation != (Object)null) { return currentCraftingStation.m_upgrader; } return false; } internal static void Apply(int targetQuality) { if ((Object)(object)ToolRecipe == (Object)null || ByQuality == null) { return; } if (AtUpgraderStation()) { RestoreVanillaResources(); return; } int num = targetQuality; if (num < 1) { num = 1; } if (num > ByQuality.Length - 1) { num = ByQuality.Length - 1; } Requirement[] array = ByQuality[num]; if (array != null) { ToolRecipe.m_resources = array; if (ToolTiersPlugin.Verbose.Value) { ToolTiersPlugin.Log.LogInfo((object)("Swapped to level " + num + ".")); } } } } [HarmonyPatch(typeof(ObjectDB), "Awake")] internal static class Patch_ObjectDB_Awake { private static void Postfix(ObjectDB __instance) { ToolTiers.Build(__instance); } } [HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")] internal static class Patch_ObjectDB_CopyOtherDB { private static void Postfix(ObjectDB __instance) { ToolTiers.Build(__instance); } } [HarmonyPatch(typeof(Requirement), "GetAmount", new Type[] { typeof(int) })] internal static class Patch_Requirement_GetAmount { private static bool Prefix(Requirement __instance, ref int __result) { if (!ToolTiers.TryGetFlatAmount(__instance, out var amount)) { return true; } __result = amount; return false; } } [HarmonyPatch(typeof(InventoryGui), "SetupRequirementList")] internal static class Patch_InventoryGui_SetupRequirementList { private static void Prefix(int quality) { ToolTiers.Apply(quality); } } [HarmonyPatch(typeof(Player), "HaveRequirements", new Type[] { typeof(Recipe), typeof(bool), typeof(int), typeof(int) })] internal static class Patch_Player_HaveRequirements { private static void Prefix(Recipe recipe, int qualityLevel) { if ((Object)(object)recipe == (Object)(object)ToolTiers.ToolRecipe) { ToolTiers.Apply(qualityLevel); } } } [HarmonyPatch(typeof(InventoryGui), "DoCrafting")] internal static class Patch_InventoryGui_DoCrafting { private static void Prefix(Recipe ___m_craftRecipe, ItemData ___m_craftUpgradeItem) { if (!((Object)(object)___m_craftRecipe != (Object)(object)ToolTiers.ToolRecipe)) { ToolTiers.Apply((___m_craftUpgradeItem == null) ? 1 : (___m_craftUpgradeItem.m_quality + 1)); } } private static void Postfix(Recipe ___m_craftRecipe) { if ((Object)(object)___m_craftRecipe == (Object)(object)ToolTiers.ToolRecipe) { ToolTiers.RestoreVanillaResources(); } } } [HarmonyPatch(typeof(InventoryGui), "UpdateRecipe")] internal static class Patch_InventoryGui_UpdateRecipe { private static void Prefix() { ToolTiers.ApplyKnownMaterialCap(); } } [HarmonyPatch(typeof(InventoryGui), "UpdateRecipeList")] internal static class Patch_InventoryGui_UpdateRecipeList { private static void Prefix() { ToolTiers.ApplyKnownMaterialCap(); ToolTiers.LogDiagnosticsOnce(); } } [HarmonyPatch(typeof(Recipe), "GetRequiredStationLevel")] internal static class Patch_Recipe_GetRequiredStationLevel { private static void Postfix(Recipe __instance, int quality, ref int __result) { if (!((Object)(object)__instance != (Object)(object)ToolTiers.ToolRecipe) && quality > ToolTiers.VanillaMaxQuality) { __result = Mathf.Max(1, __instance.m_minStationLevel); } } } [HarmonyPatch(typeof(ItemData), "GetMaxDurability", new Type[] { typeof(int) })] internal static class Patch_ItemData_GetMaxDurability { private static void Postfix(ItemData __instance, int quality, ref float __result) { if (ToolTiers.TryGetMaxDurability(__instance, quality, out var result)) { __result = result; } } } [HarmonyPatch(typeof(Player), "Awake")] internal static class Patch_Player_Awake { private static void Postfix(Player __instance) { Patch_Player_UpdatePlacement.CaptureBaseline(__instance.m_maxPlaceDistance); } } [HarmonyPatch(typeof(Player), "UpdatePlacement")] internal static class Patch_Player_UpdatePlacement { private static float _vanillaDistance = -1f; private static bool _raised; internal static void CaptureBaseline(float distance) { _vanillaDistance = distance; _raised = false; } private static void Prefix(Player __instance, ItemData ___m_rightItem) { if (_vanillaDistance < 0f) { _vanillaDistance = __instance.m_maxPlaceDistance; } float value = ToolTiersPlugin.PlaceDistancePerLevel.Value; int num = 0; if (value != 0f && (Object)(object)ToolTiers.ToolDrop != (Object)null) { if (___m_rightItem != null && ___m_rightItem.m_shared != null && ___m_rightItem.m_shared.m_name == ToolTiers.ToolDrop.m_itemData.m_shared.m_name) { num = ___m_rightItem.m_quality - (ToolTiers.FirstMetalLevel - 1); if (num < 0) { num = 0; } } } if (num > 0) { __instance.m_maxPlaceDistance = _vanillaDistance + (float)num * value; _raised = true; } else if (_raised) { __instance.m_maxPlaceDistance = _vanillaDistance; _raised = false; } } } }