Decompiled source of ShardTierClassicItems v1.1.0

plugins/ShardTierClassicItems.dll

Decompiled 2 weeks ago
using System;
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.Security;
using System.Security.Permissions;
using AncientScepter;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ClassicItemsReturns;
using HG.Reflection;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MiscFixes.Modules;
using Mono.Cecil;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using On.RoR2;
using R2API;
using RoR2;
using RoR2.ContentManagement;
using SS2;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: OptIn]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ShardTierClassicItems")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+0f27381212dac21fca31169b3aa1a513ed617567")]
[assembly: AssemblyProduct("ShardTierClassicItems")]
[assembly: AssemblyTitle("ShardTierClassicItems")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 ShardTierClassicItems
{
	public static class ConfigOptions
	{
		internal static ConfigEntry<bool> LogExtraInfo;

		internal static List<ConfigEntry<string>> TradesConfigEntriesList = new List<ConfigEntry<string>>();

		internal static List<ConfigEntry<bool>> TierChangeConfigEntriesList = new List<ConfigEntry<bool>>();

		internal static void BindConfigOptions(ConfigFile config)
		{
			LogExtraInfo = Extensions.BindOption<bool>(config, "Other", "Enable logging extra info", "If you wanna see stuff like all valid trades, the mod changing item tiers and adding items to trades, enable this.", false, (ConfigFlags)0);
			string text = "Set what shard trades this item should be added to.\nValid options:\n";
			foreach (string validTradeName in Main.ValidTradeNames)
			{
				text = ((!(validTradeName == "None")) ? (text + validTradeName + ", ") : (text + validTradeName));
			}
			text += "\nSeparate each one with a COMMA ( , ) and NO SPACES, except for `All` or `None` which must be alone.";
			text += "\n\nNOTE: Setting to `All` means it may add itself to other modded trades!";
			ItemDef[] itemDefs = ContentManager.itemDefs;
			foreach (ItemDef val in itemDefs)
			{
				if (Main.IsItemDefNormalClassicItem(val.nameToken))
				{
					string @string = Language.GetString(val.nameToken, "en");
					TradesConfigEntriesList.Add(Extensions.BindOption<string>(config, "Add to shard trades", @string, text, "All", (ConfigFlags)0));
					TierChangeConfigEntriesList.Add(Extensions.BindOption<bool>(config, "Change to shard tier", @string, "Should this item be changed to shard tier?", true, (ConfigFlags)0));
				}
			}
		}
	}
	internal static class Extensions
	{
		public static T GetRandom<T>(this IEnumerable<T> self, Xoroshiro128Plus rng)
		{
			return self.ElementAt(rng.RangeInt(0, self.Count()));
		}
	}
	internal static class Log
	{
		private static ManualLogSource _logSource;

		internal static void Init(ManualLogSource logSource)
		{
			_logSource = logSource;
		}

		internal static void Debug(object data)
		{
		}

		internal static void Error(object data)
		{
			_logSource.LogError(data);
		}

		internal static void Fatal(object data)
		{
			_logSource.LogFatal(data);
		}

		internal static void Info(object data)
		{
			if (ConfigOptions.LogExtraInfo != null && ConfigOptions.LogExtraInfo.Value)
			{
				_logSource.LogInfo(data);
			}
		}

		internal static void Message(object data)
		{
			_logSource.LogMessage(data);
		}

		internal static void Warning(object data)
		{
			_logSource.LogWarning(data);
		}
	}
	internal static class Main
	{
		internal static Color CurioColor;

		internal static TradeController tradeController = null;

		internal static List<string> ValidTradeNames = new List<string>();

		internal static List<ItemIndex> CurioItemIndexesList = new List<ItemIndex>();

		internal static void SetupTradeController()
		{
			tradeController = SS2Assets.LoadAsset<GameObject>("TradeTeleporter", (SS2Bundle)15).GetComponent<TradeController>();
			Log.Info("ALl valid trades:");
			TradeDef[] trades = tradeController.trades;
			foreach (TradeDef val in trades)
			{
				Log.Info(((Object)val).name + " (requires " + ((Object)val.desiredItem).name + ")");
				ValidTradeNames.Add(((Object)val).name);
			}
			ValidTradeNames.Add("All");
			ValidTradeNames.Add("None");
		}

		internal static void EditClassicItems()
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			ItemDef[] itemDefs = ContentManager.itemDefs;
			foreach (ItemDef val in itemDefs)
			{
				if (!IsItemDefNormalClassicItem(val.nameToken))
				{
					continue;
				}
				ConfigEntry<string> tradesConfigEntryForItemDef = GetTradesConfigEntryForItemDef(val);
				if (ShouldItemBeAddedToTrades(tradesConfigEntryForItemDef))
				{
					AddItemDefToConfiguredTrades(val, tradesConfigEntryForItemDef);
				}
				ConfigEntry<bool> tierChangeConfigEntryForItemDef = GetTierChangeConfigEntryForItemDef(val);
				if (tierChangeConfigEntryForItemDef.Value)
				{
					MakeItemDefCurioTier(val, tierChangeConfigEntryForItemDef);
					if (IsItemAncientScepter(val.nameToken))
					{
						new Harmony("LordVGames.ShardTierClassicItems").CreateClassProcessor(typeof(ModSupport.AncientScepterMod.HarmonyPatches)).Patch();
						ModSupport.AncientScepterMod.OverrideScepterDescriptionTokenIfApplicable();
					}
				}
			}
		}

		private static void AddItemDefToConfiguredTrades(ItemDef itemDef, ConfigEntry<string> itemConfigEntry)
		{
			string[] array = itemConfigEntry.Value.Split(',');
			TradeDef[] trades;
			if (array[0].ToLower() == "all")
			{
				Log.Info("Adding \"" + ((ConfigEntryBase)itemConfigEntry).Definition.Key + "\" to ALL trades!");
				trades = tradeController.trades;
				foreach (TradeDef val in trades)
				{
					val.options = CollectionExtensions.AddToArray<TradeOption>(val.options, CreateTradeOptionFromItemDef(itemDef));
					Log.Debug($"tradeDef.options.Length is {val.options.Length}");
				}
				return;
			}
			trades = tradeController.trades;
			foreach (TradeDef val2 in trades)
			{
				if (array.Contains(((Object)val2).name))
				{
					Log.Info("Adding \"" + ((ConfigEntryBase)itemConfigEntry).Definition.Key + "\" to trade \"" + ((Object)val2).name + "\"");
					val2.options = CollectionExtensions.AddToArray<TradeOption>(val2.options, CreateTradeOptionFromItemDef(itemDef));
				}
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		private static void MakeItemDefCurioTier(ItemDef itemDef, ConfigEntry<bool> itemTierChangeConfigEntry)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			Log.Info("Changing \"" + ((ConfigEntryBase)itemTierChangeConfigEntry).Definition.Key + "\" item tier to shard tier!");
			Log.Debug(((Object)itemDef).name);
			itemDef._itemTierDef = ItemTierDefs.Curio;
			itemDef.tier = ItemTierDefs.Curio.tier;
			ModSupport.SoftDependencies.SetItemDefSpriteToCurioSprite(itemDef);
		}

		internal static void FillCurioItemIndexesList()
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			ItemDef[] itemDefs = ContentManager.itemDefs;
			foreach (ItemDef val in itemDefs)
			{
				if (!((Object)(object)val._itemTierDef != (Object)(object)ItemTierDefs.Curio) && !((Object)val).name.Contains("SHARD") && !IsItemAncientScepter(((Object)val).name))
				{
					CurioItemIndexesList.Add(val.itemIndex);
				}
			}
		}

		internal static TradeOption CreateTradeOptionFromItemDef(ItemDef itemDef)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			return new TradeOption
			{
				pickupName = itemDef.nameToken,
				pickupDef = (Object)(object)itemDef,
				pickupIndex = PickupCatalog.FindPickupIndex(itemDef.itemIndex)
			};
		}

		internal static bool ShouldItemBeAddedToTrades(ConfigEntry<string> itemConfigEntry)
		{
			if (itemConfigEntry.Value == "None")
			{
				Log.Info("\"" + ((ConfigEntryBase)itemConfigEntry).Definition.Key + "\" will not be added to any trades due to being set to \"None\".");
				return false;
			}
			if (Utility.IsNullOrWhiteSpace(itemConfigEntry.Value))
			{
				Log.Info("\"" + ((ConfigEntryBase)itemConfigEntry).Definition.Key + "\" will not be added to any trades due to being set to blank.");
				return false;
			}
			return true;
		}

		internal static ConfigEntry<string> GetTradesConfigEntryForItemDef(ItemDef itemDef)
		{
			foreach (ConfigEntry<string> tradesConfigEntries in ConfigOptions.TradesConfigEntriesList)
			{
				if (((ConfigEntryBase)tradesConfigEntries).Definition.Key == Language.GetString(itemDef.nameToken, "en"))
				{
					return tradesConfigEntries;
				}
			}
			return null;
		}

		internal static ConfigEntry<bool> GetTierChangeConfigEntryForItemDef(ItemDef itemDef)
		{
			foreach (ConfigEntry<bool> tierChangeConfigEntries in ConfigOptions.TierChangeConfigEntriesList)
			{
				if (((ConfigEntryBase)tierChangeConfigEntries).Definition.Key == Language.GetString(itemDef.nameToken, "en"))
				{
					return tierChangeConfigEntries;
				}
			}
			return null;
		}

		internal static bool IsItemDefNormalClassicItem(string nameToken)
		{
			if (nameToken.StartsWith("CLASSICITEMSRETURNS") || IsItemAncientScepter(nameToken))
			{
				return !nameToken.Contains("DRONEITEM");
			}
			return false;
		}

		internal static bool IsItemAncientScepter(string nameToken)
		{
			return nameToken == "ITEM_ANCIENT_SCEPTER_NAME";
		}
	}
	internal static class ModSupport
	{
		internal static class ClassicItemsReturnsMod
		{
			private static bool? _modexists;

			internal static bool ModIsRunning
			{
				get
				{
					bool valueOrDefault = _modexists.GetValueOrDefault();
					if (!_modexists.HasValue)
					{
						valueOrDefault = Chainloader.PluginInfos.ContainsKey("com.RiskySleeps.ClassicItemsReturns");
						_modexists = valueOrDefault;
					}
					return _modexists.Value;
				}
			}

			internal static bool Use3DModels
			{
				get
				{
					if (ModIsRunning)
					{
						return ClassicItemsReturnsPlugin.use3dModels;
					}
					return false;
				}
			}

			internal static bool UseClassicSprites
			{
				get
				{
					if (ModIsRunning)
					{
						return ClassicItemsReturnsPlugin.useClassicSprites;
					}
					return false;
				}
			}
		}

		internal static class AncientScepterMod
		{
			[HarmonyPatch]
			internal static class HarmonyPatches
			{
				[HarmonyPatch(typeof(AncientScepterItem), "Reroll")]
				[HarmonyILManipulator]
				internal static void PatchRerollItemResult(ILContext il)
				{
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Expected O, but got Unknown
					//IL_008a: Unknown result type (might be due to invalid IL or missing references)
					ILCursor val = new ILCursor(il);
					if (!val.TryGotoNext((MoveType)2, new Func<Instruction, bool>[1]
					{
						(Instruction x) => ILPatternMatchingExt.MatchStloc(x, 6)
					}))
					{
						Log.Error("COULD NOT IL HOOK " + ((MemberReference)il.Method).Name);
						Log.Warning($"il is {il}");
						return;
					}
					val.EmitDelegate<Func<ItemIndex>>((Func<ItemIndex>)(() => Main.CurioItemIndexesList.GetRandom(Run.instance.treasureRng)));
					val.Emit(OpCodes.Stloc, 6);
				}
			}

			private static bool? _modexists;

			internal static bool ModIsRunning
			{
				get
				{
					bool valueOrDefault = _modexists.GetValueOrDefault();
					if (!_modexists.HasValue)
					{
						valueOrDefault = Chainloader.PluginInfos.ContainsKey("com.DestroyedClone.AncientScepter");
						_modexists = valueOrDefault;
					}
					return _modexists.Value;
				}
			}

			[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
			internal static void OverrideScepterDescriptionTokenIfApplicable()
			{
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Invalid comparison between Unknown and I4
				string text = "Upgrade one of your <style=cIsUtility>skills</style>. <style=cStack>(Unique per character)</style> <style=cStack>" + (((int)AncientScepterItem.rerollMode != 0) ? "Extra/Unusable" : "Unusable (but NOT extra)") + " pickups will reroll into " + (((int)AncientScepterItem.rerollMode == 2) ? "red scrap" : "other shard-tier items.") + "</style>";
				LanguageAPI.AddOverlay("ITEM_ANCIENT_SCEPTER_DESCRIPTION", text);
			}
		}

		internal static class SoftDependencies
		{
			[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
			internal static void SetItemDefSpriteToCurioSprite(ItemDef itemDef)
			{
				string text = ((Object)itemDef).name + ".png";
				Sprite val = null;
				bool flag = false;
				bool flag2 = false;
				if (Main.IsItemAncientScepter(((Object)itemDef).name) || ClassicItemsReturnsMod.Use3DModels)
				{
					val = MyAssets.R2IconsBundle.LoadAsset<Sprite>(text);
					if ((Object)(object)val == (Object)null)
					{
						if (Main.IsItemAncientScepter(((Object)itemDef).name))
						{
							Log.Warning("Shard-tier 3D item sprite for \"" + ((Object)itemDef).name + "\" could not be found!");
							Log.Error("All possible sprite options not found. The item's sprite will not be changed.");
							return;
						}
						Log.Warning("Shard-tier 3D item sprite for \"" + ((Object)itemDef).name + "\" could not be found!");
						Log.Warning("Falling back to the Returns sprite.");
						flag2 = true;
					}
					else
					{
						flag = true;
					}
				}
				if (flag2)
				{
					val = MyAssets.RRIconsBundle.LoadAsset<Sprite>(text);
					if ((Object)(object)val == (Object)null)
					{
						Log.Warning("Shard-tier returns item sprite for \"" + ((Object)itemDef).name + "\" could not be found!");
						Log.Warning("Falling back to the Classic sprite.");
					}
					else
					{
						flag = true;
					}
				}
				if ((!flag && ClassicItemsReturnsMod.UseClassicSprites) || (!flag && flag2))
				{
					val = MyAssets.R1IconsBundle.LoadAsset<Sprite>(text);
					if ((Object)(object)val == (Object)null)
					{
						if (flag2)
						{
							Log.Warning("Shard-tier classic item sprite for item \"" + ((Object)itemDef).name + "\" could not be found!");
							Log.Error("All possible sprite options not found. The item's sprite will not be changed.");
							return;
						}
						Log.Warning("Shard-tier classic item sprite for \"" + ((Object)itemDef).name + "\" could not be found!");
						Log.Warning("Falling back to the Returns sprite.");
					}
					else
					{
						flag = true;
					}
				}
				if (!flag)
				{
					val = MyAssets.RRIconsBundle.LoadAsset<Sprite>(text);
					if ((Object)(object)val == (Object)null)
					{
						Log.Warning("Shard-tier returns item sprite for \"" + ((Object)itemDef).name + "\" could not be found!");
						Log.Error("All possible sprite options not found. The item's sprite will not be changed.");
						val = itemDef.pickupIconSprite;
						return;
					}
				}
				itemDef.pickupIconSprite = val;
			}
		}
	}
	public static class MyAssets
	{
		public static AssetBundle R2IconsBundle;

		public const string R2IconsBundleName = "recolored_ror2_icons";

		public static AssetBundle R1IconsBundle;

		public const string R1IconsBundleName = "recolored_ror1_icons";

		public static AssetBundle RRIconsBundle;

		public const string RRIconsBundleName = "recolored_rorr_icons";

		public static string R2IconsBundlePath => Path.Combine(Path.GetDirectoryName(Plugin.PluginInfo.Location), "recolored_ror2_icons");

		public static string R1IconsBundlePath => Path.Combine(Path.GetDirectoryName(Plugin.PluginInfo.Location), "recolored_ror1_icons");

		public static string RRIconsBundlePath => Path.Combine(Path.GetDirectoryName(Plugin.PluginInfo.Location), "recolored_rorr_icons");

		public static void Init()
		{
			R2IconsBundle = AssetBundle.LoadFromFile(R2IconsBundlePath);
			R1IconsBundle = AssetBundle.LoadFromFile(R1IconsBundlePath);
			RRIconsBundle = AssetBundle.LoadFromFile(RRIconsBundlePath);
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("LordVGames.ShardTierClassicItems", "ShardTierClassicItems", "1.1.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGUID = "LordVGames.ShardTierClassicItems";

		public const string PluginAuthor = "LordVGames";

		public const string PluginName = "ShardTierClassicItems";

		public const string PluginVersion = "1.1.0";

		public static PluginInfo PluginInfo { get; private set; }

		public void Awake()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			PluginInfo = ((BaseUnityPlugin)this).Info;
			Log.Init(((BaseUnityPlugin)this).Logger);
			MyAssets.Init();
			ItemCatalog.SetItemDefs += (hook_SetItemDefs)delegate(orig_SetItemDefs orig, ItemDef[] itemDefs)
			{
				orig.Invoke(itemDefs);
				Guh(((BaseUnityPlugin)this).Config);
			};
		}

		private static void Guh(ConfigFile config)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: 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)
			Main.CurioColor = Color32.op_Implicit(ColorCatalog.GetColor(ItemTierDefs.Curio.colorIndex));
			Main.SetupTradeController();
			ConfigOptions.BindConfigOptions(config);
			Extensions.WipeConfig(config);
			Main.EditClassicItems();
			Main.FillCurioItemIndexesList();
		}
	}
}