Decompiled source of UpgradeAntlerPickaxe v1.1.3

plugins/UpgradeAntlerPickaxe.dll

Decompiled 3 months 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.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using Jotunn;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("UpgradeAntlerPickaxe")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UpgradeAntlerPickaxe")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")]
[assembly: AssemblyFileVersion("0.0.1.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.1.0")]
namespace UpgradeAntlerPickaxe;

internal class RecipeHelper
{
	private static readonly Regex nukeWhiteSpaceRegex = new Regex("\\s+");

	private static readonly Regex recipeEntryRegex = new Regex("^([a-zA-Z]+:[0-9]+)$");

	public static RequirementConfig[] GetAsRequirementConfigArray(string configRecipe, string upgradeRecipe, int multiplier)
	{
		return GetAsRequirementConfigList(configRecipe, upgradeRecipe, multiplier).ToArray();
	}

	public static Requirement[] GetAsPieceRequirementArray(string configRecipe, string upgradeRecipe, int multiplier)
	{
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Expected O, but got Unknown
		try
		{
			List<RequirementConfig> asRequirementConfigList = GetAsRequirementConfigList(configRecipe, upgradeRecipe, multiplier);
			List<Requirement> list = new List<Requirement>();
			foreach (RequirementConfig item in asRequirementConfigList)
			{
				GameObject prefab = PrefabManager.Instance.GetPrefab(item.Item);
				if ((Object)(object)prefab == (Object)null)
				{
					throw new Exception("Could not find item, please check config!");
				}
				Requirement val = new Requirement();
				val.m_resItem = prefab.GetComponent<ItemDrop>();
				val.m_amount = item.Amount;
				val.m_amountPerLevel = item.AmountPerLevel;
				val.m_recover = item.Recover;
				list.Add(val);
			}
			return list.ToArray();
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Could not convert recipe to Piece.Requirement array: " + ex));
			return null;
		}
	}

	public static List<RequirementConfig> GetAsRequirementConfigList(string configRecipe, string upgradeRecipe, int multiplier)
	{
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Expected O, but got Unknown
		try
		{
			configRecipe = nukeWhiteSpaceRegex.Replace(configRecipe, "");
			upgradeRecipe = nukeWhiteSpaceRegex.Replace(upgradeRecipe, "");
			if (!IsConfigRecipeValid(configRecipe, upgradeRecipe))
			{
				throw new Exception("Config is not valid, please check the values!");
			}
			List<RequirementConfig> list = new List<RequirementConfig>();
			string[] array = configRecipe.Trim().Split(new char[1] { ',' });
			string[] array2 = array;
			foreach (string text in array2)
			{
				RequirementConfig val = new RequirementConfig();
				string[] array3 = text.Split(new char[1] { ':' });
				val.Item = array3[0];
				val.Amount = int.Parse(array3[1]);
				val.Recover = true;
				if (!Utility.IsNullOrWhiteSpace(upgradeRecipe))
				{
					string[] array4 = upgradeRecipe.Trim().Split(new char[1] { ',' });
					string[] array5 = array4;
					foreach (string text2 in array5)
					{
						string[] array6 = text2.Split(new char[1] { ':' });
						if (val.Item == array6[0])
						{
							val.AmountPerLevel = int.Parse(array6[1]) * multiplier;
							break;
						}
					}
				}
				list.Add(val);
			}
			return list;
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Could not convert recipe to RequirementConfig list: " + ex));
			return null;
		}
	}

	public static bool IsConfigRecipeValid(string configRecipe, string upgradeRecipe)
	{
		try
		{
			bool result = true;
			string[] array = configRecipe.Split(new char[1] { ',' });
			string[] array2 = array;
			foreach (string text in array2)
			{
				if (!recipeEntryRegex.IsMatch(text))
				{
					result = false;
					Logger.LogError((object)("Cannot resolve " + text + " from the crafting recipe"));
				}
			}
			if (Utility.IsNullOrWhiteSpace(upgradeRecipe))
			{
				return result;
			}
			string[] array3 = upgradeRecipe.Split(new char[1] { ',' });
			string[] array4 = array3;
			foreach (string text2 in array4)
			{
				if (!recipeEntryRegex.IsMatch(text2))
				{
					result = false;
					Logger.LogError((object)("Cannot resolve " + text2 + " from the upgrade recipe"));
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Could not validate recipe due to an error: " + ex));
			return false;
		}
	}
}
internal enum RecipeUpdateType
{
	Recipe,
	CraftingStation,
	MinRequiredLevel
}
[BepInPlugin("DeathWizsh.UpgradeAntlerPickaxe", "Upgrade Antler Pickaxe", "1.1.3")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
internal class UpgradeAntlerPickaxe : BaseUnityPlugin
{
	public const string PluginGUID = "DeathWizsh.UpgradeAntlerPickaxe";

	public const string PluginName = "Upgrade Antler Pickaxe";

	public const string PluginVersion = "1.1.3";

	private static string configFileName = "DeathWizsh.UpgradeAntlerPickaxe.cfg";

	private static string configFileFullPath;

	private string[] configCraftingStationOptions = new string[9] { "None", "Disabled", "Workbench", "Forge", "Stonecutter", "Cauldron", "ArtisanTable", "BlackForge", "GaldrTable" };

	private ConfigEntry<bool> configEnable;

	private ConfigEntry<bool> configCreateClone;

	private ConfigEntry<string> configName;

	private ConfigEntry<string> configDescription;

	private ConfigEntry<string> configCraftingStation;

	private ConfigEntry<int> configMinStationLevel;

	private ConfigEntry<string> configRecipe;

	private ConfigEntry<string> configRecipeUpgrade;

	private ConfigEntry<int> configRecipeMultiplier;

	private void Awake()
	{
		try
		{
			InitConfig();
			if (configEnable.Value)
			{
				PrefabManager.OnVanillaPrefabsAvailable += PatchStats;
				if (!configCreateClone.Value)
				{
					AddCustomRecipe();
					ItemManager.OnItemsRegistered += RemoveOriginalRecipe;
				}
			}
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Something went wrong with the initialisation of UpgradeAntlerPickaxe: " + ex));
		}
	}

	private void OnDestroy()
	{
		((BaseUnityPlugin)this).Config.Save();
	}

	private void PatchStats()
	{
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Expected O, but got Unknown
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Expected O, but got Unknown
		try
		{
			if (!configCreateClone.Value)
			{
				GameObject prefab = PrefabManager.Instance.GetPrefab("PickaxeAntler");
				ItemDrop component = prefab.GetComponent<ItemDrop>();
				UpdateItemStats(component);
			}
			else if (ItemManager.Instance.GetItem("PickaxeAntler_DW") == null)
			{
				ItemConfig val = new ItemConfig();
				val.CraftingStation = configCraftingStation.Value;
				val.Requirements = RecipeHelper.GetAsRequirementConfigArray(configRecipe.Value, configRecipeUpgrade.Value, configRecipeMultiplier.Value);
				CustomItem val2 = new CustomItem("PickaxeAntler_DW", "PickaxeAntler", val);
				UpdateItemStats(val2.ItemDrop);
				ItemManager.Instance.AddItem(val2);
			}
			else
			{
				CustomItem item = ItemManager.Instance.GetItem("PickaxeAntler_DW");
				UpdateItemStats(item.ItemDrop);
			}
			PrefabManager.OnVanillaPrefabsAvailable -= PatchStats;
			Logger.LogInfo((object)"Successfully patched stats on the antler pickaxe, enjoy!");
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Unable to patch stats onto the antler pickaxe: " + ex.Message));
		}
	}

	private void UnpatchStats()
	{
		try
		{
			if (!configCreateClone.Value)
			{
				GameObject prefab = PrefabManager.Instance.GetPrefab("PickaxeAntler");
				ItemDrop component = prefab.GetComponent<ItemDrop>();
				UpdateItemStats(component, unpatch: true);
			}
			else
			{
				CustomItem item = ItemManager.Instance.GetItem("PickaxeAntler_DW");
				UpdateItemStats(item.ItemDrop, unpatch: true);
			}
			Logger.LogInfo((object)"Successfully unpatched stats of the antler pickaxe, Why u do this?!");
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Unable to unpatch stats from the antler pickaxe: " + ex.Message));
		}
	}

	private void UpdateItemStats(ItemDrop item, bool unpatch = false)
	{
		if (unpatch)
		{
			item.m_itemData.m_shared.m_maxQuality = 1;
			return;
		}
		item.m_itemData.m_shared.m_name = configName.Value;
		item.m_itemData.m_shared.m_description = configDescription.Value;
		item.m_itemData.m_shared.m_maxQuality = 4;
		item.m_itemData.m_shared.m_damagesPerLevel.m_pickaxe = 5f;
		item.m_itemData.m_shared.m_damagesPerLevel.m_pierce = 5f;
		item.m_itemData.m_shared.m_blockPowerPerLevel = 0f;
		item.m_itemData.m_shared.m_deflectionForcePerLevel = 5f;
		item.m_itemData.m_shared.m_durabilityPerLevel = 50f;
	}

	private void AddCustomRecipe()
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Expected O, but got Unknown
		try
		{
			RecipeConfig val = new RecipeConfig();
			val.Item = "PickaxeAntler";
			val.CraftingStation = configCraftingStation.Value;
			val.MinStationLevel = configMinStationLevel.Value;
			val.Requirements = RecipeHelper.GetAsRequirementConfigArray(configRecipe.Value, configRecipeUpgrade.Value, configRecipeMultiplier.Value);
			ItemManager.Instance.AddRecipe(new CustomRecipe(val));
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Could not add the recipe for the antler pickaxe: " + ex));
		}
	}

	private void RemoveOriginalRecipe()
	{
		try
		{
			GameObject prefab = PrefabManager.Instance.GetPrefab("PickaxeAntler");
			ItemDrop component = prefab.GetComponent<ItemDrop>();
			Recipe recipe = ObjectDB.instance.GetRecipe(component.m_itemData);
			if ((Object)(object)recipe != (Object)null)
			{
				ObjectDB.instance.m_recipes.Remove(recipe);
				ItemManager.OnItemsRegistered -= RemoveOriginalRecipe;
				return;
			}
			throw new Exception("Could not find recipe to remove!");
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Unable to remove recipe of the antler pickaxe: " + ex.Message));
		}
	}

	private void PatchRecipe(RecipeUpdateType updateType = RecipeUpdateType.Recipe)
	{
		try
		{
			string text = "Recipe_" + (configCreateClone.Value ? "PickaxeAntler_DW" : "PickaxeAntler");
			CustomRecipe recipe = ItemManager.Instance.GetRecipe(text);
			if (recipe == null)
			{
				throw new Exception("Could not find recipe!");
			}
			if (!configEnable.Value)
			{
				return;
			}
			switch (updateType)
			{
			case RecipeUpdateType.Recipe:
			{
				Requirement[] asPieceRequirementArray = RecipeHelper.GetAsPieceRequirementArray(configRecipe.Value, configRecipeUpgrade.Value, configRecipeMultiplier.Value);
				if (asPieceRequirementArray == null)
				{
					throw new Exception("Requirements is null");
				}
				recipe.Recipe.m_resources = asPieceRequirementArray;
				break;
			}
			case RecipeUpdateType.CraftingStation:
				if (configCraftingStation.Value == "None")
				{
					recipe.Recipe.m_craftingStation = null;
					recipe.Recipe.m_enabled = true;
				}
				else if (configCraftingStation.Value == "Disabled")
				{
					recipe.Recipe.m_craftingStation = null;
					recipe.Recipe.m_enabled = false;
				}
				else
				{
					string internalName = CraftingStations.GetInternalName(configCraftingStation.Value);
					recipe.Recipe.m_enabled = true;
					recipe.Recipe.m_craftingStation = PrefabManager.Instance.GetPrefab(internalName).GetComponent<CraftingStation>();
				}
				break;
			case RecipeUpdateType.MinRequiredLevel:
				recipe.Recipe.m_minStationLevel = configMinStationLevel.Value;
				break;
			}
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Could not update recipe: " + ex));
		}
	}

	private void InitConfig()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Expected O, but got Unknown
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Expected O, but got Unknown
		//IL_004c: Expected O, but got Unknown
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Expected O, but got Unknown
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Expected O, but got Unknown
		//IL_00a6: Expected O, but got Unknown
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Expected O, but got Unknown
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Expected O, but got Unknown
		//IL_00ec: Expected O, but got Unknown
		//IL_011a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Expected O, but got Unknown
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_014a: Expected O, but got Unknown
		//IL_014a: Expected O, but got Unknown
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_019a: Unknown result type (might be due to invalid IL or missing references)
		//IL_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a8: Expected O, but got Unknown
		//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b2: Expected O, but got Unknown
		//IL_01b2: Expected O, but got Unknown
		//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0202: Expected O, but got Unknown
		//IL_0202: Unknown result type (might be due to invalid IL or missing references)
		//IL_020c: Expected O, but got Unknown
		//IL_020c: Expected O, but got Unknown
		//IL_023a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0252: Unknown result type (might be due to invalid IL or missing references)
		//IL_0257: Unknown result type (might be due to invalid IL or missing references)
		//IL_0260: Expected O, but got Unknown
		//IL_0260: Unknown result type (might be due to invalid IL or missing references)
		//IL_026a: Expected O, but got Unknown
		//IL_026a: Expected O, but got Unknown
		//IL_0298: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02be: Expected O, but got Unknown
		//IL_02be: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c8: Expected O, but got Unknown
		//IL_02c8: Expected O, but got Unknown
		//IL_0303: Unknown result type (might be due to invalid IL or missing references)
		//IL_0317: Unknown result type (might be due to invalid IL or missing references)
		//IL_031c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0325: Expected O, but got Unknown
		//IL_0325: Unknown result type (might be due to invalid IL or missing references)
		//IL_032f: Expected O, but got Unknown
		//IL_032f: Expected O, but got Unknown
		try
		{
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			configEnable = ((BaseUnityPlugin)this).Config.Bind<bool>(new ConfigDefinition("General", "Enable"), true, new ConfigDescription("Wether or not to enable this mod. When changed while the game is running it will disable the ability to upgrade\nthe pickaxe but will not modify already upgraded ones. They will be reverted back to normal on next game start\nEXCEPT if they were cloned, then they will be deleted!", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			configEnable.SettingChanged += delegate
			{
				if (!configEnable.Value)
				{
					UnpatchStats();
					string text = (configCreateClone.Value ? " and will be deleted when players relog!" : "!");
					Logger.LogWarning((object)("UpgradeAntlerPickaxe is now disabled! The Antler Pickaxe can no longer be upgraded" + text));
				}
				else
				{
					PatchStats();
				}
			};
			configCreateClone = ((BaseUnityPlugin)this).Config.Bind<bool>(new ConfigDefinition("General", "Create clone"), false, new ConfigDescription("Wether to patch the original Antler Pickaxe or to create a clone instead (requires restart)", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			configName = ((BaseUnityPlugin)this).Config.Bind<string>(new ConfigDefinition("General", "Name"), "Antler Pickaxe", new ConfigDescription("The name given to the item", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			configName.SettingChanged += delegate
			{
				PatchStats();
			};
			configDescription = ((BaseUnityPlugin)this).Config.Bind<string>(new ConfigDefinition("General", "Description"), "This tool is hard enough to crack even the most stubborn rocks.", new ConfigDescription("The description given to the item", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			configDescription.SettingChanged += delegate
			{
				PatchStats();
			};
			configCraftingStation = ((BaseUnityPlugin)this).Config.Bind<string>(new ConfigDefinition("General", "Crafting station"), "Workbench", new ConfigDescription("The crafting station the item can be created in", (AcceptableValueBase)(object)new AcceptableValueList<string>(configCraftingStationOptions), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			configCraftingStation.SettingChanged += delegate
			{
				PatchRecipe(RecipeUpdateType.CraftingStation);
			};
			configMinStationLevel = ((BaseUnityPlugin)this).Config.Bind<int>(new ConfigDefinition("General", "Required station level"), 1, new ConfigDescription("The required station level to craft the item", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			configMinStationLevel.SettingChanged += delegate
			{
				PatchRecipe(RecipeUpdateType.MinRequiredLevel);
			};
			configRecipe = ((BaseUnityPlugin)this).Config.Bind<string>(new ConfigDefinition("General", "Crafting costs"), "Wood:10,HardAntler:1", new ConfigDescription("The items required to craft the item", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			configRecipe.SettingChanged += delegate
			{
				PatchRecipe();
			};
			configRecipeUpgrade = ((BaseUnityPlugin)this).Config.Bind<string>(new ConfigDefinition("General", "Upgrade costs"), "Wood:4,HardAntler:1", new ConfigDescription("The costs to upgrade the item", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			configRecipeUpgrade.SettingChanged += delegate
			{
				PatchRecipe();
			};
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = true;
			configRecipeMultiplier = ((BaseUnityPlugin)this).Config.Bind<int>(new ConfigDefinition("General", "Upgrade multiplier"), 1, new ConfigDescription("The multiplier applied to the upgrade costs", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			configRecipeMultiplier.SettingChanged += delegate
			{
				PatchRecipe();
			};
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, configFileName);
			fileSystemWatcher.Changed += OnConfigFileChange;
			fileSystemWatcher.Created += OnConfigFileChange;
			fileSystemWatcher.Renamed += OnConfigFileChange;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Something went wrong with initialising the config or config events: " + ex));
		}
	}

	private void OnConfigFileChange(object sender, FileSystemEventArgs e)
	{
		if (!File.Exists(configFileFullPath))
		{
			return;
		}
		try
		{
			((BaseUnityPlugin)this).Config.Reload();
		}
		catch (Exception ex)
		{
			Logger.LogError((object)("Something went wrong while reloading the config, please check if the file exists and the entries are valid! " + ex));
		}
	}

	static UpgradeAntlerPickaxe()
	{
		string configPath = Paths.ConfigPath;
		char directorySeparatorChar = Path.DirectorySeparatorChar;
		configFileFullPath = configPath + directorySeparatorChar + configFileName;
	}
}