using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Timers; using APIManager; using AdventureBackpacks.API; using AdventureBackpacks.Assets; using AdventureBackpacks.Assets.Effects; using AdventureBackpacks.Assets.Factories; using AdventureBackpacks.Assets.Items; using AdventureBackpacks.Assets.Items.BackpackItems; using AdventureBackpacks.Compats; using AdventureBackpacks.Components; using AdventureBackpacks.Configuration; using AdventureBackpacks.Extensions; using AdventureBackpacks.Features; using AdventureBackpacks.Patches; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using BepInEx.Preloader; using BepInEx.Preloader.Patching; using HarmonyLib; using ItemManager; using JetBrains.Annotations; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using Vapok.Common.Abstractions; using Vapok.Common.Managers; using Vapok.Common.Managers.Configuration; using Vapok.Common.Managers.Creature; using Vapok.Common.Managers.LocalizationManager; using Vapok.Common.Managers.Location; using Vapok.Common.Managers.PieceManager; using Vapok.Common.Managers.Skill; using Vapok.Common.Managers.StatusEffects; using Vapok.Common.Shared; using Vapok.Common.Tools; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("AdventureBackpacks")] [assembly: AssemblyDescription("A Valheim Mod for adding progression multiple backpacks as an item/utility gear addition.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Vapok Gaming")] [assembly: AssemblyProduct("AdventureBackpacks")] [assembly: AssemblyCopyright("Copyright © 2024")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("997CB563-FCC7-44B7-8F71-069747D27CC5")] [assembly: AssemblyFileVersion("1.9.13.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.9.13.0")] [module: UnverifiableCode] [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 AdventureBackpacks { [BepInPlugin("vapok.mods.adventurebackpacks", "Adventure Backpacks", "1.9.13")] [BepInIncompatibility("JotunnBackpacks")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public class AdventureBackpacks : BaseUnityPlugin, IPluginInfo { public class Waiting { public event EventHandler StatusChanged; public void ValheimIsAwake(bool awakeFlag) { if (awakeFlag) { this.StatusChanged?.Invoke(this, EventArgs.Empty); } } } private const string _pluginId = "vapok.mods.adventurebackpacks"; private const string _displayName = "Adventure Backpacks"; private const string _version = "1.9.13"; public static bool ValheimAwake; public static bool PerformYardSale; public static bool QuickDropping; public static bool BypassMoveProtection; public static Waiting Waiter; private static AdventureBackpacks _instance; private static ConfigSyncBase _config; private static ILogIt _log; private Harmony _harmony; public string PluginId => "vapok.mods.adventurebackpacks"; public string DisplayName => "Adventure Backpacks"; public string Version => "1.9.13"; public BaseUnityPlugin Instance => (BaseUnityPlugin)(object)_instance; public static ILogIt Log => _log; public static ConfigSyncBase ActiveConfig => _config; [UsedImplicitly] private void Awake() { //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown _instance = this; Patcher.Patch(new string[1] { "AdventureBackpacks.API" }); Waiter = new Waiting(); CustomLocalization localization = LocalizationManager.Instance.GetLocalization(); LogManager.Init(PluginId, out _log); Initializer.LoadManagers(localization, enableCreatureManager: false, enableItemManager: true, enableLocationManager: true, enableMaterialReplacer: true, enablePieceManager: false, enableSkillManager: false, enableEffectManager: true); _config = new ConfigRegistry(_instance); ItemManager.PrefabManager.Initalized = true; _harmony = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID); _harmony.PatchAll(Assembly.GetExecutingAssembly()); if (Chainloader.PluginInfos.ContainsKey("com.chebgonaz.ChebsNecromancy")) { ChebsNecromancy.SetupNecromancyBackpackUsingApi(); } if (Chainloader.PluginInfos.ContainsKey("com.maxsch.valheim.contentswithin")) { ContentsWithin.Awake(_harmony, "com.maxsch.valheim.contentswithin"); } } private void Start() { Localizer.Waiter.StatusChanged += InitializeBackpacks; QuickTransfer.FeatureInitialized = true; } private void Update() { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)Player.m_localPlayer) || !Object.op_Implicit((Object)(object)ZNetScene.instance)) { return; } if (PerformYardSale) { BackpackComponent equippedBackpack = Player.m_localPlayer.GetEquippedBackpack(); if (equippedBackpack != null) { Backpacks.PerformYardSale(Player.m_localPlayer, equippedBackpack.Item); } } if (ZInput.GetButton("Forward") || ZInput.GetButton("Backward") || ZInput.GetButton("Left") || ZInput.GetButton("Right")) { KeyboardShortcut value = ConfigRegistry.HotKeyDrop.Value; if (ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey, true) && ConfigRegistry.OutwardMode.Value) { Player.m_localPlayer.QuickDropBackpack(); } } EffectsFactory.Instance.ToggleEffects(); InventoryPatches.ProcessItemsAddedQueue(); } public void InitializeBackpacks(object send, EventArgs args) { if (!ValheimAwake) { new EffectsFactory(_log, _config).RegisterEffects(); new BackpackFactory(_log, _config).CreateAssets(); IronBackpackIconFix.Apply(); SilverBackpackIconFix.Apply(); Backpacks.LoadBackpackTypes(BackpackFactory.BackpackTypes()); BoneReorder.ApplyOnEquipmentChanged(((BaseUnityPlugin)this).Info.Metadata.GUID); ConfigRegistry.Waiter.ConfigurationComplete(configDone: true); ValheimAwake = true; } } private void OnDestroy() { _instance = null; } } } namespace AdventureBackpacks.API { [PublicAPI] public class ABAPI { public struct Backpack { public string Name; public ItemData ItemData; public Inventory Inventory; public BackpackDefinition Definition; } public class BackpackDefinition { public GameObject BackPackGo; public AssetBundle AssetBundle; public string PrefabName; public string ItemName; public string ConfigSection = ""; public string CraftingTable; public int StationLevel; public int MaxRequiredStationLevel; public readonly List RecipeIngredients = new List(); public readonly List UpgradeIngredients = new List(); public readonly List DropsFrom = new List(); public readonly Dictionary> EffectsToApply = new Dictionary>(); public Dictionary BackpackSizeByQuality = new Dictionary(); public StatusEffect ItemSetStatusEffect; public float WeightMultiplier; public int CarryBonus; public float SpeedMod; public bool EnableFreezing; public BackpackBiomes BackpackBiome; public BackpackDefinition() { } public BackpackDefinition(GameObject backPackGo) { BackPackGo = backPackGo; } public BackpackDefinition(AssetBundle assetBundle, string prefabName) { AssetBundle = assetBundle; PrefabName = prefabName; } } public struct DropTarget { public string Creature; public int Min; public int? Max; public float Chance; public DropTarget(string creature, float chance, int min = 1, int? max = null) { Creature = creature; Chance = chance; Min = min; Max = max; } } public struct EffectDefinition { public readonly string Name; public readonly string LocalizedName; public readonly string EffectName; public readonly string Description; public readonly StatusEffect StatusEffect; public EffectDefinition(string name, string localizedName, string effectName, string description, StatusEffect statusEffect) { Name = name; LocalizedName = localizedName; EffectName = effectName; Description = description; StatusEffect = statusEffect; } } public struct RecipeIngredient { public string ItemPrefabName; public int Quantity; public RecipeIngredient(string itemPrefabName, int quantity) { ItemPrefabName = itemPrefabName; Quantity = quantity; } } public static bool IsLoaded() { return true; } public static bool IsBackpack(ItemData itemData) { return itemData?.IsBackpack() ?? false; } public static bool IsBackpackEquipped(Player player) { if ((Object)(object)player != (Object)null) { return player.IsBackpackEquipped(); } return false; } public static bool CanOpenBackpack(Player player) { if ((Object)(object)player != (Object)null) { return player.CanOpenBackpack(); } return false; } public static bool IsThisBackpackEquipped(Player player, ItemData itemData) { if ((Object)(object)player != (Object)null) { return player.IsThisBackpackEquipped(itemData); } return false; } public static Backpack? GetEquippedBackpack(Player player) { return ConvertBackpackItem(player.GetEquippedBackpack()); } public static Backpack? GetBackpack(ItemData itemData) { return ConvertBackpackItem(itemData); } public static HashSet GetActiveBackpackStatusEffects() { return EquipmentEffectCache.ActiveEffects; } public static HashSet GetRegisterdStatusEffects() { return EffectsFactory.GetRegisteredEffects(); } public static void OpenBackpack(Player player, InventoryGui gui) { if ((Object)(object)player != (Object)null) { player.OpenBackpack(gui); } } public static void RegisterEffect(EffectDefinition effectDefinition) { EffectsFactory.RegisterExternalEffect(effectDefinition); } public static void RegisterBackpack(BackpackDefinition definition) { BackpackFactory.RegisterExternalBackpack(definition); } private static Backpack? ConvertBackpackItem(BackpackComponent component) { BackpackDefinition backPackDefinitionFromComponent = GetBackPackDefinitionFromComponent(component); if (backPackDefinitionFromComponent == null) { return null; } return new Backpack { Name = backPackDefinitionFromComponent.ItemName, ItemData = component.Item, Definition = backPackDefinitionFromComponent, Inventory = component.GetInventory() }; } private static Backpack? ConvertBackpackItem(ItemData itemData) { if (!itemData.IsBackpack()) { return null; } return ConvertBackpackItem(itemData.Data().GetOrCreate()); } private static Dictionary GetBackpackSizing(BackpackItem backpack) { return backpack.BackpackSize.ToDictionary((KeyValuePair> entry) => entry.Key, (KeyValuePair> entry) => entry.Value.Value); } private static BackpackDefinition GetBackPackDefinitionFromComponent(BackpackComponent component) { if (component.Item.TryGetBackpackItem(out var backpack)) { return null; } return GetBackPackDefinition(backpack); } private static BackpackDefinition GetBackPackDefinition(BackpackItem backpack) { return new BackpackDefinition { ItemName = backpack.ItemName, PrefabName = backpack.PrefabName, BackpackSizeByQuality = GetBackpackSizing(backpack), WeightMultiplier = backpack.WeightMultiplier.Value, CarryBonus = backpack.CarryBonus.Value, SpeedMod = backpack.SpeedMod.Value, EnableFreezing = backpack.EnableFreezing.Value, BackpackBiome = backpack.BackpackBiome.Value }; } } [Flags] public enum BackpackBiomes : uint { None = 0u, Meadows = 1u, BlackForest = 2u, Swamp = 4u, Mountains = 8u, Plains = 0x10u, Mistlands = 0x20u, Ashlands = 0x40u, DeepNorth = 0x80u, EffectBiome1 = 0x100000u, EffectBiome2 = 0x200000u, EffectBiome3 = 0x400000u, EffectBiome4 = 0x800000u, EffectBiome5 = 0x1000000u } } namespace AdventureBackpacks.Compats { public static class ChebsNecromancy { public static void SetupNecromancyBackpackUsingApi() { //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Unknown result type (might be due to invalid IL or missing references) string text = "SetEffect_NecromancyArmor"; string text2 = "chebgonaz"; string path = "Assets"; string text3 = ""; string text4 = "friendlyskeletonwand_necromancy_skill"; StatusEffect val = null; if (!ABAPI.IsLoaded()) { return; } PluginInfo val2 = Chainloader.PluginInfos["com.chebgonaz.ChebsNecromancy"]; text3 = Path.Combine(Paths.PluginPath, Path.GetDirectoryName(val2.Location) ?? "", path, text2); if (!File.Exists(text3)) { text3 = Path.Combine(Paths.PluginPath, Path.GetDirectoryName(val2.Location) ?? "", text2); } AssetBundle val3 = ((!File.Exists(text3)) ? null : AssetBundle.LoadFromFile(text3)); if ((Object)(object)val3 == (Object)null) { AdventureBackpacks.Log.Error("Can't find Asset Bundle for Status Effect: " + text + " - Effect Not Registered"); return; } SkillType skillLevel = (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(text4)); SE_Stats val4 = val3.LoadAsset(text); if ((Object)(object)val4 != (Object)null) { val4.m_skillLevel = skillLevel; val4.m_skillLevelModifier = 10f; } val = (StatusEffect)(object)val4; ABAPI.RegisterEffect(new ABAPI.EffectDefinition("Necromancy Armor Effect", "Necromancy Armor Effect", text, "When activated the backpack provides the Necromancy Armor effect from Cheb's Necromancy", val)); AssetBundle val5 = Utilities.LoadAssetBundle("chebsbackpack"); if ((Object)(object)val5 == (Object)null) { AdventureBackpacks.Log.Warning("Asset Bundle Not Found"); return; } string prefabName = "BackpackNecromancy"; ABAPI.RegisterBackpack(new ABAPI.BackpackDefinition(val5, prefabName) { ItemName = "$item_friendlyskeletonwand_spectralshroud_backpack", CraftingTable = "piece_workbench", StationLevel = 1, MaxRequiredStationLevel = 4, RecipeIngredients = { new ABAPI.RecipeIngredient("ChebGonaz_SpectralShroud", 1), new ABAPI.RecipeIngredient("TrollHide", 5) }, UpgradeIngredients = { new ABAPI.RecipeIngredient("Chain", 1), new ABAPI.RecipeIngredient("TrollHide", 5) }, DropsFrom = { new ABAPI.DropTarget("ChebGonaz_GuardianWraith", 0.002f) }, BackpackBiome = (BackpackBiomes.BlackForest | BackpackBiomes.EffectBiome1), BackpackSizeByQuality = { { 1, new Vector2(3f, 3f) }, { 2, new Vector2(4f, 3f) }, { 3, new Vector2(5f, 3f) }, { 4, new Vector2(6f, 3f) } }, WeightMultiplier = 20f, EffectsToApply = { { BackpackBiomes.EffectBiome1, new KeyValuePair(val, 1) } }, ItemSetStatusEffect = val }); } } public static class ContentsWithin { private static PluginInfo _plugin; private static Assembly _assembly; public static Type Main; public static Type InventoryGuiPatch; public static void Awake(Harmony harmony, string guidID) { //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Expected O, but got Unknown if (Chainloader.PluginInfos.TryGetValue(guidID, out _plugin)) { _assembly = Assembly.LoadFile(_plugin.Location); Main = _assembly.GetType("ContentsWithin.ContentsWithin"); InventoryGuiPatch = Main.GetNestedType("InventoryGuiPatch"); MethodInfo methodInfo = AccessTools.Method(InventoryGuiPatch, "HasContainerAccess", (Type[])null, (Type[])null); if (InventoryGuiPatch != null) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ContentsWithin), "ContainerAccessPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } private static bool ContainerAccessPrefix(Container container, ref bool __result) { if ((Object)(object)container == (Object)null) { return true; } if (!((Object)container).name.Equals("Player(Clone)")) { return true; } __result = false; return false; } } } namespace AdventureBackpacks.Patches { public static class ArmorStandPatches { [HarmonyPatch(typeof(ArmorStand), "UpdateAttach")] private static class ArmorStandUpdateAttachPatch { private static void Prefix(ArmorStand __instance) { AdventureBackpacks.BypassMoveProtection = true; } private static void Postfix(ArmorStand __instance) { AdventureBackpacks.BypassMoveProtection = false; } } } public static class ContainerPatches { [HarmonyPatch(typeof(Container), "TakeAll")] private static class ContainerTakeAllPatch { private static void Prefix(Container __instance) { AdventureBackpacks.BypassMoveProtection = true; } private static void Postfix(Container __instance) { AdventureBackpacks.BypassMoveProtection = false; } } [HarmonyPatch(typeof(Container), "Interact")] private static class ContainerInteractPatch { private static bool Prefix(Container __instance, ref bool __result) { if (((Object)__instance).name.Equals("Player(Clone)")) { __result = false; return false; } return true; } } [HarmonyPatch(typeof(Container), "Awake")] private static class ContainerAwakePatch { private static void UpdateZDO(Container instance, ZNetView nview) { if (((Object)instance).name.Equals("Player(Clone)")) { nview.GetZDO().Set(StringExtensionMethods.GetStableHashCode("creator"), 1L); } } private static IEnumerable Transpiler(IEnumerable instructions, ILGenerator ilGenerator) { bool patchedSuccess = false; List instrs = instructions.ToList(); int counter = 0; MethodInfo invokeRepeatingMethod = AccessTools.DeclaredMethod(typeof(MonoBehaviour), "InvokeRepeating", new Type[3] { typeof(string), typeof(float), typeof(float) }, (Type[])null); FieldInfo nviewField = AccessTools.DeclaredField(typeof(Container), "m_nview"); int i = 0; while (i < instrs.Count) { if (i > 5 && instrs[i].opcode == OpCodes.Ret && instrs[i - 1].opcode == OpCodes.Call && instrs[i - 1].operand.Equals(invokeRepeatingMethod)) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); counter++; yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); counter++; yield return new CodeInstruction(OpCodes.Ldfld, (object)nviewField); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(ContainerAwakePatch), "UpdateZDO", (Type[])null, (Type[])null))); counter++; patchedSuccess = true; } yield return LogMessage(instrs[i]); counter++; int num = i + 1; i = num; } if (!patchedSuccess) { AdventureBackpacks.Log.Error("Container.Awake Transpiler Failed To Patch"); Thread.Sleep(5000); } CodeInstruction LogMessage(CodeInstruction instruction) { AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}"); return instruction; } } } } public static class DoorPatches { [HarmonyPatch(typeof(Door), "HaveKey")] private static class HaveDoorKeyPatch { private static void Postfix(Door __instance, ref bool __result) { if (!((Object)(object)__instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && Player.m_localPlayer.IsBackpackEquipped() && !__result) { BackpackComponent equippedBackpack = Player.m_localPlayer.GetEquippedBackpack(); __result = (Object)(object)__instance.m_keyItem == (Object)null || equippedBackpack.GetInventory().HaveItem(__instance.m_keyItem.m_itemData.m_shared.m_name, true); } } } } public class EnvManPatches { [HarmonyPatch(typeof(EnvMan), "IsCold")] public static class EnvManIsCold { [UsedImplicitly] [HarmonyPriority(800)] public static bool Prefix(EnvMan __instance, ref bool __result) { if ((Object)(object)Player.m_localPlayer == (Object)null) { return true; } if (EffectsFactory.EffectList[BackpackEffect.ColdResistance].IsEffectActive((Humanoid)(object)Player.m_localPlayer)) { __result = false; return false; } return true; } } [HarmonyPatch(typeof(EnvMan), "IsWet")] public static class EnvManIsWet { [UsedImplicitly] [HarmonyPriority(800)] public static bool Prefix(EnvMan __instance, ref bool __result) { if ((Object)(object)Player.m_localPlayer == (Object)null) { return true; } if (EffectsFactory.EffectList[BackpackEffect.WaterResistance].IsEffectActive((Humanoid)(object)Player.m_localPlayer)) { __result = false; return false; } return true; } } } public class FejdStartupPatches { [HarmonyPatch(typeof(FejdStartup), "Start")] [HarmonyAfter(new string[] { "org.bepinex.helpers.LocalizationManager" })] [HarmonyBefore(new string[] { "org.bepinex.helpers.ItemManager" })] public static class FejdStartupAwakePatch { private static void Postfix() { AdventureBackpacks.Waiter.ValheimIsAwake(awakeFlag: true); } } [HarmonyPatch(typeof(FejdStartup), "Start")] [HarmonyAfter(new string[] { "org.bepinex.helpers.ItemManager" })] private static class FejdStartupAfterItemManagerIconFix { private static void Postfix() { IronBackpackIconFix.Apply(); } } [HarmonyPatch(typeof(FejdStartup), "Start")] [HarmonyAfter(new string[] { "org.bepinex.helpers.ItemManager" })] private static class FejdStartupAfterItemManagerSilverIconFix { private static void Postfix() { SilverBackpackIconFix.Apply(); } } [HarmonyPatch(typeof(ObjectDB), "Awake")] private static class ObjectDBAwakeIronIconFix { private static void Postfix() { IronBackpackIconFix.Apply(); } } [HarmonyPatch(typeof(ObjectDB), "Awake")] private static class ObjectDBAwakeSilverIconFix { private static void Postfix() { SilverBackpackIconFix.Apply(); } } } public class GuiBarPatches { [HarmonyPatch(typeof(GuiBar), "Awake")] public static class GuiBarAwakePatch { public const string eaqsGUID = "randyknapp.mods.equipmentandquickslots"; private static bool Prefix(GuiBar __instance) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) if (!Chainloader.PluginInfos.ContainsKey("randyknapp.mods.equipmentandquickslots") && ((Object)__instance).name == "durability" && __instance.m_bar.sizeDelta.x != 54f) { __instance.m_bar.sizeDelta = new Vector2(54f, 0f); } return true; } } } public class HumanoidPatches { [HarmonyPatch(typeof(Humanoid), "UpdateEquipmentStatusEffects")] private static class HumanoidUpdateEquipmentStatusEffectsPatch { public static IEnumerable Transpiler(IEnumerable instructions) { bool patchedSuccess = false; List instrs = instructions.ToList(); int counter = 0; CodeInstruction ldlocInstruction = new CodeInstruction(OpCodes.Ldloc_0, (object)null); int i = 0; while (i < instrs.Count) { yield return LogMessage(instrs[i]); counter++; if (i > 0 && instrs[i].opcode == OpCodes.Stloc_0 && instrs[i - 1].opcode == OpCodes.Newobj) { if (instrs[i].labels.Count > 0) { CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldlocInstruction); } yield return LogMessage(ldlocInstruction); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_0, (object)null)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(EquipmentEffectCache), "AddActiveBackpackEffects", (Type[])null, (Type[])null))); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Stloc_0, (object)null)); counter++; patchedSuccess = true; } int num = i + 1; i = num; } if (!patchedSuccess) { AdventureBackpacks.Log.Error("UpdateEquipmentStatusEffects Transpiler Failed To Patch"); Thread.Sleep(5000); } CodeInstruction LogMessage(CodeInstruction instruction) { AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}"); return instruction; } } } [HarmonyPatch(typeof(Humanoid), "UnequipItem")] private static class HumanoidUnequipItemPatch { private static void Prefix(ItemData __0) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown if (__0 == null || (Object)(object)Player.m_localPlayer == (Object)null) { return; } Scene activeScene = SceneManager.GetActiveScene(); if (((Scene)(ref activeScene)).name.Equals("start")) { return; } Player localPlayer = Player.m_localPlayer; if (!__0.IsBackpack() || ((Humanoid)localPlayer).m_shoulderItem != __0) { return; } BackpackComponent equippedBackpack = localPlayer.GetEquippedBackpack(); if (equippedBackpack != null) { equippedBackpack.Save(); InventoryGui instance = InventoryGui.instance; if ((Object)(object)instance != (Object)null && instance.IsContainerOpen()) { instance.CloseContainer(); InventoryGuiPatches.BackpackIsOpen = false; } Container component = ((Component)localPlayer).gameObject.GetComponent(); if (!((Object)(object)component == (Object)null)) { component.m_inventory = new Inventory("Empty", (Sprite)null, 1, 1); InventoryGuiPatches.BackpackEquipped = false; } } } } [HarmonyPatch(typeof(Humanoid), "EquipItem")] private static class HumanoidEquipItemPatch { private static void Postfix(ItemData __0, bool __result) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) AdventureBackpacks.Log.Debug("########## EquipItem Start"); if (__0 == null || !__result || (Object)(object)Player.m_localPlayer == (Object)null) { return; } Scene activeScene = SceneManager.GetActiveScene(); if (((Scene)(ref activeScene)).name.Equals("start")) { return; } Player localPlayer = Player.m_localPlayer; if (__0.IsBackpack() && __0.TryGetBackpackItem(out var backpack)) { InventoryGuiPatches.BackpackEquipped = true; BackpackComponent orCreate = __0.Data().GetOrCreate(); if (!orCreate.IsEmptyingBackpack) { Vector2i inventorySize = backpack.GetInventorySize(orCreate.Item.m_quality); if (orCreate.InventoryNeedsValidating(inventorySize)) { Backpacks.ValidateBackpackInventorySizing(localPlayer, orCreate.Item); } else { Container backpackContainer = ((Component)localPlayer).gameObject.GetComponent(); if ((Object)(object)backpackContainer != (Object)null) { orCreate.UpdateContainerSizing(ref backpackContainer); } } } } AdventureBackpacks.Log.Debug("########## EquipItem End"); } } } public static class InventoryPatches { [HarmonyPatch(typeof(Inventory), "Changed")] private static class InventoryChangedPatch { private static void Postfix(Inventory __instance) { if (__instance == null || (Object)(object)Player.m_localPlayer == (Object)null) { return; } Player localPlayer = Player.m_localPlayer; if (!__instance.IsBackPackInventory()) { return; } new StackTrace(); AdventureBackpacks.Log.Debug("#### Patch Inventory Changed: " + __instance.m_name); AdventureBackpacks.Log.Debug($"#### Patch Inventory Count: {__instance.m_inventory.Count}"); if (!localPlayer.IsBackpackEquipped()) { return; } BackpackComponent equippedBackpack = localPlayer.GetEquippedBackpack(); AdventureBackpacks.Log.Debug("########################################"); AdventureBackpacks.Log.Debug("#### Inventory.Changed #####"); AdventureBackpacks.Log.Debug("Inventory Instance: " + __instance.m_name); AdventureBackpacks.Log.Debug("Backpack Name: " + equippedBackpack.Item.m_shared.m_name); AdventureBackpacks.Log.Debug("########################################"); if (equippedBackpack.GetInventory() == __instance) { AdventureBackpacks.Log.Debug($"#### Before Save BackpackComponent Inventory Count: {equippedBackpack.GetInventory().m_inventory.Count}"); if (equippedBackpack.IsLoadingInventory) { AdventureBackpacks.Log.Debug("Bypassing Save - Inventory Is Loading ----->"); } else { equippedBackpack.Save(__instance); } AdventureBackpacks.Log.Debug($"#### After Save BackpackComponent Inventory Count: {equippedBackpack.GetInventory().m_inventory.Count}"); } } } [HarmonyPatch(typeof(InventoryGui), "OnDropOutside")] [HarmonyPriority(800)] private static class OnDropOutsideItemPatch { private static void Prefix(InventoryGui __instance) { if (!((Object)(object)__instance == (Object)null) && __instance.m_dragItem != null) { if (__instance.m_dragItem.IsBackpack() && __instance.m_dragItem.m_stack == 0) { __instance.m_dragItem.m_stack = 1; } _droppingOutside = true; } } private static void Postfix() { _droppingOutside = false; } } [HarmonyPatch(typeof(Humanoid), "DropItem", new Type[] { typeof(Inventory), typeof(ItemData), typeof(int) })] [HarmonyPriority(800)] private static class HumanoidDropItemPatch { private static void Prefix(ItemData item) { _droppingOutside = true; } private static void Postfix() { _droppingOutside = false; } } [HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(ItemData) })] [HarmonyPriority(800)] private static class RemoveItem1Patch { private static bool Prefix(Inventory __instance, ItemData item, ref bool __result) { if (item == null || __instance == null) { return true; } if (!RemoveItemPrefix(__instance, item)) { __result = false; return false; } return true; } } [HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(ItemData), typeof(int) })] [HarmonyPriority(800)] private static class RemoveItem2Patch { private static bool Prefix(Inventory __instance, ItemData item, ref bool __result) { if (item == null || __instance == null) { return true; } if (!RemoveItemPrefix(__instance, item)) { __result = false; return false; } return true; } } [HarmonyPatch(typeof(Inventory), "RemoveOneItem", new Type[] { typeof(ItemData) })] [HarmonyPriority(800)] private static class RemoveItem3Patch { private static bool Prefix(Inventory __instance, ItemData item, ref bool __result) { if (item == null || __instance == null) { return true; } if (!RemoveItemPrefix(__instance, item)) { __result = false; return false; } return true; } } [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(string), typeof(int), typeof(int), typeof(int), typeof(long), typeof(string), typeof(Vector2i), typeof(bool) })] [HarmonyPriority(800)] private static class AddItemCraftingPatch { private static void Postfix(Inventory __instance, ref ItemData __result) { if (IsDoingCrafting && __instance != null) { _savedBackpackData = null; } } } [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })] [HarmonyPriority(800)] private static class AddItemPatch { private static bool Prefix(Inventory __instance, ItemData item, ref bool __result) { if (item == null) { return false; } if (item.IsBackpack() && __instance.HaveEmptySlot()) { bool flag = Backpacks.CheckForInception(__instance, item); if (flag && !_movingItemBetweenContainers) { ItemsAddedQueue.Enqueue(new KeyValuePair(item, DateTime.Now)); } __result = flag; return flag; } return true; } } [HarmonyPatch(typeof(InventoryGrid), "DropItem", new Type[] { typeof(Inventory), typeof(ItemData), typeof(int), typeof(Vector2i) })] [HarmonyPriority(800)] private static class InventoryGridDropItemPatch { private static bool Prefix(InventoryGrid __instance, Inventory fromInventory, ItemData item, int amount, Vector2i pos) { //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) ItemData itemAt = __instance.m_inventory.GetItemAt(pos.x, pos.y); if (itemAt == item) { return true; } if (itemAt == null || (!(itemAt.m_shared.m_name != item.m_shared.m_name) && (item.m_shared.m_maxQuality <= 1 || itemAt.m_quality == item.m_quality) && itemAt.m_shared.m_maxStackSize != 1) || item.m_stack != amount) { return true; } if (AdventureBackpacks.PerformYardSale) { return true; } if (itemAt.IsBackpack() && fromInventory.IsBackPackInventory()) { return Backpacks.CheckForInception(fromInventory, itemAt); } if (item.IsBackpack() && __instance.m_inventory.IsBackPackInventory()) { return Backpacks.CheckForInception(__instance.m_inventory, item); } _movingItemBetweenContainers = true; return true; } } [HarmonyPatch(typeof(Inventory), "MoveAll", new Type[] { typeof(Inventory) })] [HarmonyPriority(800)] private static class MoveAllPatch { private static void Prefix(Inventory fromInventory, Inventory __instance) { if (fromInventory != null && !__instance.IsBackPackInventory()) { _movingItemBetweenContainers = true; } } private static void Postfix() { _movingItemBetweenContainers = false; } } [HarmonyPatch(typeof(Inventory), "MoveItemToThis", new Type[] { typeof(Inventory), typeof(ItemData), typeof(int), typeof(int), typeof(int) })] [HarmonyPriority(800)] private static class MoveItemToThisPatch { private static bool Prefix(Inventory __0, ItemData __1, int __2, int __3, int __4, Inventory __instance) { if (__0 == null || __1 == null) { return false; } if (!__instance.IsBackPackInventory()) { _movingItemBetweenContainers = true; return true; } return Backpacks.CheckForInception(__instance, __1); } private static void Postfix() { _movingItemBetweenContainers = false; } } [HarmonyPatch(typeof(Inventory), "MoveItemToThis", new Type[] { typeof(Inventory), typeof(ItemData) })] [HarmonyPriority(800)] private static class MoveItemToThisOtherPatch { private static bool Prefix(Inventory __0, ItemData __1, Inventory __instance) { if (__0 == null || __1 == null) { return false; } if (!__instance.IsBackPackInventory()) { _movingItemBetweenContainers = true; return true; } return Backpacks.CheckForInception(__instance, __1); } private static void Postfix() { _movingItemBetweenContainers = false; } } [HarmonyPatch(typeof(Inventory), "UpdateTotalWeight")] private static class UpdateTotalWeightPatch { [HarmonyPatch(typeof(Inventory), "IsTeleportable")] private static class IsTeleportablePatch { private static void Postfix(Inventory __instance, ref bool __result) { if (__instance == null || (Object)(object)Player.m_localPlayer == (Object)null) { return; } List allItems = __instance.GetAllItems(); if (__instance != ((Humanoid)Player.m_localPlayer).GetInventory()) { return; } if (Player.m_localPlayer.IsBackpackEquipped()) { BackpackComponent equippedBackpack = Player.m_localPlayer.GetEquippedBackpack(); if (equippedBackpack != null && !equippedBackpack.GetInventory().IsTeleportable()) { __result = false; return; } } foreach (ItemData item in allItems) { if (item != null && item.IsBackpack() && !item.Data().GetOrCreate().GetInventory() .IsTeleportable()) { __result = false; break; } } } } private static void Postfix(Inventory __instance) { if (__instance == null || (Object)(object)Player.m_localPlayer == (Object)null) { return; } Player localPlayer = Player.m_localPlayer; if (__instance.IsBackPackInventory() && localPlayer.IsBackpackEquipped()) { BackpackComponent equippedBackpack = localPlayer.GetEquippedBackpack(); AdventureBackpacks.Log.Debug("########################################"); AdventureBackpacks.Log.Debug("#### UpdateTotalWeight #####"); AdventureBackpacks.Log.Debug("Inventory Instance: " + __instance.m_name); AdventureBackpacks.Log.Debug("Backpack Name: " + equippedBackpack.Item.m_shared.m_name); AdventureBackpacks.Log.Debug("########################################"); if (equippedBackpack.GetInventory() == __instance) { ((Humanoid)localPlayer).GetInventory().UpdateTotalWeight(); } } } } private static bool _movingItemBetweenContainers; private static bool _droppingOutside; public static bool IsDoingCrafting = false; private static BackpackComponent _savedBackpackData = null; private static readonly Queue> ItemsAddedQueue = new Queue>(); private static bool IsItemFromQueue(this ItemData item) { if (ItemsAddedQueue.Any((KeyValuePair x) => ((object)x.Key).Equals((object?)item))) { AdventureBackpacks.Log.Debug("Item " + item.m_shared.m_name + " Found!"); return true; } AdventureBackpacks.Log.Debug("Item Not Found!"); return false; } public static void ProcessItemsAddedQueue() { while (ItemsAddedQueue.Any() && DateTime.Now.Subtract(ItemsAddedQueue.Peek().Value).TotalSeconds > 0.5) { AdventureBackpacks.Log.Debug($"Process Cache Removing {ItemsAddedQueue.Peek().Key.m_shared.m_name} for Date {ItemsAddedQueue.Peek().Value} with a difference of {DateTime.Now.Subtract(ItemsAddedQueue.Peek().Value).TotalSeconds} total seconds."); ItemsAddedQueue.Dequeue(); } } private static bool RemoveItemPrefix(Inventory __instance, ItemData item) { if (__instance == null || (Object)(object)Player.m_localPlayer == (Object)null) { return true; } if (_movingItemBetweenContainers || _droppingOutside) { return true; } if (IsDoingCrafting) { if (item.IsBackpack()) { _savedBackpackData = item.Data().Get(); } return true; } if (AdventureBackpacks.PerformYardSale || AdventureBackpacks.QuickDropping || AdventureBackpacks.BypassMoveProtection) { return true; } if (!item.TryGetBackpackItem(out var _)) { return true; } AdventureBackpacks.Log.Debug("Checking for Backpack " + item.m_shared.m_name); if (item.IsItemFromQueue()) { AdventureBackpacks.Log.Debug("Exiting RemoveItem for " + item.m_shared.m_name); return true; } BackpackComponent backpackComponent = item.Data().Get(); if (backpackComponent == null) { return true; } Inventory inventory = backpackComponent.GetInventory(); if (inventory == null || inventory.m_inventory.Count == 0) { return true; } if (!Backpacks.PerformYardSale(Player.m_localPlayer, item, backpackOnly: true)) { ((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_yard_sale_blocked", 0, (Sprite)null); return false; } return true; } } internal static class InventoryGuiPatches { [HarmonyPatch(typeof(InventoryGui), "DoCrafting")] private static class InventoryGuiDoCraftingPrefix { [UsedImplicitly] private static void Prefix(InventoryGui __instance) { AdventureBackpacks.Log.Debug("########################################"); AdventureBackpacks.Log.Debug("#### DoCrafting.Prefix #####"); AdventureBackpacks.Log.Debug("########################################"); InventoryPatches.IsDoingCrafting = true; } private static void Postfix(InventoryGui __instance) { AdventureBackpacks.Log.Debug("########################################"); AdventureBackpacks.Log.Debug("#### DoCrafting.Postfix #####"); AdventureBackpacks.Log.Debug("########################################"); InventoryPatches.IsDoingCrafting = false; if ((Object)(object)Player.m_localPlayer == (Object)null) { return; } Player localPlayer = Player.m_localPlayer; if (__instance.m_craftUpgradeItem == null || !__instance.m_craftUpgradeItem.IsBackpack()) { return; } AdventureBackpacks.Log.Debug("Item: " + __instance.m_craftUpgradeItem.m_shared.m_name + " "); BackpackComponent backpackComponent = __instance.m_craftUpgradeItem.Data().Get(); AdventureBackpacks.Log.Debug("Backpack: " + __instance.m_craftUpgradeItem.m_shared.m_name + " "); if (backpackComponent != null) { backpackComponent?.Load(); if (localPlayer.IsThisBackpackEquipped(backpackComponent.Item)) { Container backpackContainer = ((Component)localPlayer).gameObject.GetComponent(); backpackComponent?.UpdateContainerSizing(ref backpackContainer); } ((Humanoid)localPlayer).UpdateEquipmentStatusEffects(); } } } [HarmonyPatch(typeof(InventoryGui), "OnSelectedItem")] private static class InventoryGuiOnSelectedItem { [UsedImplicitly] private static Exception Finalizer(Exception __exception, InventoryGrid grid, ItemData item, Vector2i pos, Modifier mod, InventoryGui __instance) { if (__exception != null) { if (__exception is NullReferenceException && (Object)(object)__instance != (Object)null && (Object)(object)__instance.m_currentContainer == (Object)null && (Object)(object)grid != (Object)null && grid.GetInventory() != null && (Object)(object)Player.m_localPlayer != (Object)null && item != null && item.m_shared != null && Backpacks.BackpackTypes.Contains(item.m_shared.m_name)) { ((Humanoid)Player.m_localPlayer).DropItem(((Humanoid)Player.m_localPlayer).GetInventory(), item, 1); BackpackIsOpen = false; __instance.Hide(); ((Character)Player.m_localPlayer).Message((MessageType)1, "$vapok_mod_you_droped_bag", 0, (Sprite)null); return null; } AdventureBackpacks.Log.Warning("The following error was captured by Adventure Backpacks, but was caused by another mod. Advanced Backpacks is going to allow the operation to continue, but is going to replay the error below:"); AdventureBackpacks.Log.Error("External Mod Error Message: " + __exception.Message); AdventureBackpacks.Log.Error("External Mod Error Source: " + __exception.Source); AdventureBackpacks.Log.Error("External Mod Error Stack Trace: " + __exception.StackTrace); AdventureBackpacks.Log.Warning("Please check with other mod authors listed above."); } return null; } } [HarmonyPatch(typeof(InventoryGui), "Update")] private static class InventoryGuiUpdateTranspiler { [UsedImplicitly] public static IEnumerable Transpiler(IEnumerable instructions, ILGenerator ilGenerator) { List instrs = instructions.ToList(); int counter = 0; bool patchedHideBackpackMethod = false; bool patchedShowBackpackMethod = false; bool patchedDetectInputHideMethod = false; bool patchedDetectInputShowMethod = false; MethodInfo resetButtonStatus = AccessTools.DeclaredMethod(typeof(ZInput), "ResetButtonStatus", (Type[])null, (Type[])null); AccessTools.DeclaredMethod(typeof(Menu), "IsVisible", (Type[])null, (Type[])null); MethodInfo hideMethod = AccessTools.DeclaredMethod(typeof(InventoryGui), "Hide", (Type[])null, (Type[])null); MethodInfo showMethod = AccessTools.DeclaredMethod(typeof(InventoryGui), "Show", (Type[])null, (Type[])null); MethodInfo tutorialMethod = AccessTools.DeclaredMethod(typeof(Player), "ShowTutorial", (Type[])null, (Type[])null); MethodInfo zInputKeyDown = AccessTools.DeclaredMethod(typeof(ZInput), "GetKeyDown", new Type[2] { typeof(KeyCode), typeof(bool) }, (Type[])null); MethodInfo zInputButtonDown = AccessTools.DeclaredMethod(typeof(ZInput), "GetButtonDown", new Type[1] { typeof(string) }, (Type[])null); int i = 0; while (i < instrs.Count) { if (i > 6 && instrs[i].opcode == OpCodes.Call && instrs[i].operand.Equals(resetButtonStatus) && instrs[i + 1].opcode == OpCodes.Ldarg_0 && instrs[i + 2].opcode == OpCodes.Call && instrs[i + 2].operand.Equals(hideMethod)) { CodeInstruction ldArgInstruction = new CodeInstruction(OpCodes.Ldarg_0, (object)null); if (instrs[i].labels.Count > 0) { CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction); } yield return LogMessage(instrs[i]); counter++; yield return LogMessage(ldArgInstruction); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(InventoryGuiPatches), "HideBackpack", (Type[])null, (Type[])null))); counter++; patchedHideBackpackMethod = true; } else if (i > 6 && ((instrs[i].opcode == OpCodes.Call && instrs[i].operand.Equals(showMethod) && instrs[i - 1].opcode == OpCodes.Ldc_I4_1 && instrs[i - 2].opcode == OpCodes.Ldnull && instrs[i - 3].opcode == OpCodes.Ldarg_0) || (instrs[i - 4].opcode == OpCodes.Callvirt && instrs[i - 4].operand.Equals(tutorialMethod)))) { CodeInstruction ldArgInstruction = new CodeInstruction(OpCodes.Ldloc_1, (object)null); if (instrs[i].labels.Count > 0) { CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction); } yield return LogMessage(instrs[i]); counter++; yield return LogMessage(ldArgInstruction); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_0, (object)null)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(InventoryGuiPatches), "ShowBackpack", (Type[])null, (Type[])null))); counter++; patchedShowBackpackMethod = true; } else if (i > 6 && instrs[i].opcode == OpCodes.Call && instrs[i].operand.Equals(zInputKeyDown) && instrs[i - 1].opcode == OpCodes.Ldc_I4_1 && instrs[i - 2].opcode == OpCodes.Ldc_I4_S && instrs[i - 2].operand.Equals((sbyte)27) && instrs[i + 2].opcode == OpCodes.Ldstr && instrs[i + 2].operand.Equals("Use")) { yield return LogMessage(instrs[i]); counter++; yield return LogMessage(instrs[i + 1]); counter++; Label label = (Label)instrs[i + 1].operand; CodeInstruction val = FindInstructionWithLabel(instrs, i + 2, label); if (val == null) { AdventureBackpacks.Log.Error($"Can't Find Instruction with Label {label}"); } else { i++; Label detectHideLabel = ilGenerator.DefineLabel(); val.labels.Add(detectHideLabel); yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_1, (object)null)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_0, (object)null)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(InventoryGuiPatches), "DetectInputToHide", (Type[])null, (Type[])null))); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Brtrue, (object)detectHideLabel)); counter++; patchedDetectInputHideMethod = true; } } else if (i > 6 && instrs[i].opcode == OpCodes.Call && instrs[i].operand.Equals(zInputButtonDown) && instrs[i - 1].operand.Equals("Inventory") && instrs[i + 1].opcode == OpCodes.Brtrue && instrs[i + 2].opcode == OpCodes.Ldstr && instrs[i + 2].operand.Equals("JoyButtonY")) { yield return LogMessage(instrs[i]); counter++; yield return LogMessage(instrs[i + 1]); counter++; Label label2 = (Label)instrs[i + 1].operand; CodeInstruction val2 = FindInstructionWithLabel(instrs, i + 2, label2); if (val2 == null) { AdventureBackpacks.Log.Error($"Can't Find Instruction with Label {label2}"); } else { i++; Label detectHideLabel = ilGenerator.DefineLabel(); val2.labels.Add(detectHideLabel); yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_1, (object)null)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_0, (object)null)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(InventoryGuiPatches), "DetectInputToShow", (Type[])null, (Type[])null))); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Brtrue, (object)detectHideLabel)); counter++; patchedDetectInputShowMethod = true; } } else { yield return LogMessage(instrs[i]); counter++; } int num = i + 1; i = num; } if (!patchedHideBackpackMethod || !patchedShowBackpackMethod || !patchedDetectInputHideMethod || !patchedDetectInputShowMethod) { AdventureBackpacks.Log.Error("InventoryGui.Update Transpiler Failed To Patch"); AdventureBackpacks.Log.Warning($" patchedHideBackpackMethod {patchedHideBackpackMethod}"); AdventureBackpacks.Log.Warning($" patchedShowBackpackMethod {patchedShowBackpackMethod}"); AdventureBackpacks.Log.Warning($" patchedDetectInputHideMethod {patchedDetectInputHideMethod}"); AdventureBackpacks.Log.Warning($" patchedDetectInputShowMethod {patchedDetectInputShowMethod}"); AdventureBackpacks.Log.Error("Please inform Mod Author."); Thread.Sleep(5000); } static CodeInstruction FindInstructionWithLabel(List codeInstructions, int index, Label label3) { if (index >= codeInstructions.Count) { return null; } if (codeInstructions[index].labels.Contains(label3)) { return codeInstructions[index]; } return FindInstructionWithLabel(codeInstructions, index + 1, label3); } CodeInstruction LogMessage(CodeInstruction instruction) { AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}"); return instruction; } } } [HarmonyPatch(typeof(InventoryGui), "SetupRequirement")] private static class InventoryGuiSetupRequirementPatch { public static IEnumerable Transpiler(IEnumerable instructions) { bool patchedSuccess = false; List instrs = instructions.ToList(); int counter = 0; CodeInstruction ldArgInstruction = new CodeInstruction(OpCodes.Ldarg_2, (object)null); MethodInfo countItemsMethod = AccessTools.DeclaredMethod(typeof(Inventory), "CountItems", new Type[3] { typeof(string), typeof(int), typeof(bool) }, (Type[])null); int i = 0; while (i < instrs.Count) { yield return LogMessage(instrs[i]); counter++; if (i > 5 && instrs[i - 1].opcode == OpCodes.Callvirt && instrs[i - 1].operand.Equals(countItemsMethod) && instrs[i].opcode == OpCodes.Stloc_S) { if (instrs[i].labels.Count > 0) { CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction); } yield return LogMessage(ldArgInstruction); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_1, (object)null)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_S, instrs[i].operand)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(PlayerPatches), "AdjustCountIfEquipped", (Type[])null, (Type[])null))); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Stloc_S, instrs[i].operand)); counter++; patchedSuccess = true; } int num = i + 1; i = num; } if (!patchedSuccess) { AdventureBackpacks.Log.Error("InventoryGui.SetupRequirement Transpiler Failed To Patch"); Thread.Sleep(5000); } CodeInstruction LogMessage(CodeInstruction instruction) { AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}"); return instruction; } } } public static bool BackpackIsOpen; public static bool BackpackEquipped; private static bool _showBackpack; public static bool CheckForTextInput() { return TextInput.IsVisible(); } public static void ShowBackpack(Player player, InventoryGui instance) { if (ConfigRegistry.OpenWithInventory.Value && !BackpackIsOpen && player.CanOpenBackpack()) { _showBackpack = true; } if (_showBackpack) { if (!BackpackIsOpen && (Object)(object)instance.m_currentContainer != (Object)null) { instance.m_currentContainer.SetInUse(false); instance.m_currentContainer = null; } _showBackpack = false; player.OpenBackpack(instance); } } public static void HideBackpack(InventoryGui instance) { if (BackpackIsOpen) { instance.CloseContainer(); BackpackIsOpen = false; if (ConfigRegistry.CloseInventory.Value && !ConfigRegistry.OpenWithHoverInteract.Value) { instance.Hide(); } } } public static bool DetectInputToHide(Player player, InventoryGui instance) { //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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) KeyboardShortcut value = ConfigRegistry.HotKeyOpen.Value; bool keyDown = ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey, true); bool flag = ConfigRegistry.CloseInventory.Value && keyDown && !ConfigRegistry.OpenWithHoverInteract.Value; int num; if (ConfigRegistry.OutwardMode.Value) { value = ConfigRegistry.HotKeyDrop.Value; num = (ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey, true) ? 1 : 0); } else { num = 0; } bool flag2 = (byte)num != 0; bool flag3 = keyDown && !BackpackIsOpen && player.CanOpenBackpack() && !ConfigRegistry.OpenWithHoverInteract.Value; List list = new List(); list.AddRange(((Component)instance.m_player).GetComponentsInChildren()); if (keyDown && !BackpackIsOpen && ConfigRegistry.OpenWithHoverInteract.Value && !CheckForTextInput()) { ItemData val = null; foreach (InventoryGrid item in list) { if (item.GetHoveredElement() != null) { Element hoveredElement = item.GetHoveredElement(); val = item.GetInventory().GetItemAt(hoveredElement.m_pos.x, hoveredElement.m_pos.y); } } if (ZInput.IsGamepadActive() && val == null) { foreach (InventoryGrid item2 in list) { if (item2.GetGamepadSelectedItem() != null) { val = item2.GetGamepadSelectedItem(); } } } if (val != null && val.IsBackpack() && val.m_equipped && !BackpackIsOpen && player.CanOpenBackpack()) { flag3 = true; } } if (flag3 & !CheckForTextInput()) { if ((Object)(object)instance.m_currentContainer != (Object)null) { instance.m_currentContainer.SetInUse(false); instance.m_currentContainer = null; } player.OpenBackpack(instance); return false; } if (keyDown && BackpackIsOpen && (!flag || ConfigRegistry.OpenWithHoverInteract.Value) && !CheckForTextInput()) { bool flag4 = false; if (ConfigRegistry.OpenWithHoverInteract.Value) { ItemData val2 = null; foreach (InventoryGrid item3 in list) { if (item3.GetHoveredElement() != null) { Element hoveredElement2 = item3.GetHoveredElement(); val2 = item3.GetInventory().GetItemAt(hoveredElement2.m_pos.x, hoveredElement2.m_pos.y); } } if (ZInput.IsGamepadActive() && val2 == null) { foreach (InventoryGrid item4 in list) { if (item4.GetGamepadSelectedItem() != null) { val2 = item4.GetGamepadSelectedItem(); } } } if (val2 != null && val2.IsBackpack() && val2.m_equipped && BackpackIsOpen) { flag4 = true; } } else { flag4 = true; } if (flag4) { instance.CloseContainer(); BackpackIsOpen = false; return false; } } if (flag2 && !CheckForTextInput()) { player.QuickDropBackpack(); } if (flag || flag2) { return !CheckForTextInput(); } return false; } public static bool DetectInputToShow(Player player, InventoryGui instance) { //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_000d: 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_002e: 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) KeyboardShortcut value = ConfigRegistry.HotKeyOpen.Value; bool keyDown = ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey, true); if (ConfigRegistry.OutwardMode.Value) { value = ConfigRegistry.HotKeyDrop.Value; if (ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey, true) && !CheckForTextInput()) { player.QuickDropBackpack(); } } if (keyDown && !ConfigRegistry.OpenWithHoverInteract.Value && !BackpackIsOpen && player.CanOpenBackpack() && !CheckForTextInput()) { _showBackpack = true; } if (_showBackpack) { return !CheckForTextInput(); } return false; } } public class ItemDropPatches { [HarmonyPatch(typeof(ItemData), "GetWeight")] private static class ItemDataGetWeightTranspiler { public static float OverrideBackpackWeight(ItemData item, float originalWeight) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) float num = originalWeight; if (!string.IsNullOrEmpty(item.m_shared.m_name) && item.TryGetBackpackItem(out var backpack)) { BackpackComponent orCreate = item.Data().GetOrCreate(); Vector2i inventorySize = backpack.GetInventorySize(orCreate.Item.m_quality); if (!orCreate.IsEmptyingBackpack && orCreate.InventoryNeedsValidating(inventorySize)) { AdventureBackpacks.Log.Debug("[GetWeight() - Item Name: " + item.m_shared.m_name); AdventureBackpacks.Log.Debug("[GetWeight() - Backpack Item: " + orCreate.Item.m_shared.m_name); AdventureBackpacks.Log.Debug("[GetWeight() - Backpack: " + backpack.ItemName); Backpacks.ValidateBackpackInventorySizing(Player.m_localPlayer, orCreate.Item); } Inventory inventory = orCreate.GetInventory(); float num2 = ((inventory != null) ? inventory.GetTotalWeight() : 0f); num += num2 * backpack.WeightMultiplier.Value; } return num; } public static IEnumerable Transpiler(IEnumerable instructions) { bool patchedSuccess = false; List instrs = instructions.ToList(); int counter = 0; FieldInfo scaleWeightByQualityField = AccessTools.DeclaredField(typeof(SharedData), "m_scaleWeightByQuality"); int i = 0; while (i < instrs.Count) { if (i > 6 && instrs[i].opcode == OpCodes.Ldloc_1 && instrs[i - 1].opcode == OpCodes.Stloc_1 && instrs[i - 2].opcode == OpCodes.Add && instrs[i - 3].opcode == OpCodes.Mul && instrs[i - 4].opcode == OpCodes.Ldfld && instrs[i - 4].operand.Equals(scaleWeightByQualityField)) { CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null); if (instrs[i].labels.Count > 0) { CodeInstructionExtensions.MoveLabelsTo(instrs[i], val); } yield return LogMessage(val); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_1, (object)null)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(ItemDataGetWeightTranspiler), "OverrideBackpackWeight", (Type[])null, (Type[])null))); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Stloc_1, (object)null)); counter++; yield return LogMessage(instrs[i]); counter++; patchedSuccess = true; } else { yield return LogMessage(instrs[i]); counter++; } int num = i + 1; i = num; } if (!patchedSuccess) { AdventureBackpacks.Log.Error("GetWeight Transpiler Failed To Patch"); Thread.Sleep(5000); } CodeInstruction LogMessage(CodeInstruction instruction) { AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}"); return instruction; } } } [HarmonyPatch(typeof(ItemData), "GetIcon")] private static class ItemDataGetIconHdBackpack { private static bool Prefix(ItemData __instance, ref Sprite __result) { if (IronBackpackIconFix.IsIronHdBackpack(__instance)) { Sprite orCreateIcon = IronBackpackIconFix.GetOrCreateIcon(); if ((Object)(object)orCreateIcon != (Object)null) { __result = orCreateIcon; IronBackpackIconFix.NotifyGetIconOverride(__instance); return false; } return true; } if (!SilverBackpackIconFix.IsSilverHdBackpack(__instance)) { return true; } Sprite orCreateIcon2 = SilverBackpackIconFix.GetOrCreateIcon(); if ((Object)(object)orCreateIcon2 == (Object)null) { return true; } __result = orCreateIcon2; SilverBackpackIconFix.NotifyGetIconOverride(__instance); return false; } } } public class PlayerPatches { [HarmonyPatch(typeof(Player), "Awake")] private static class PlayerAwakePatch { private static void Postfix(Player __instance) { ((Component)__instance).gameObject.AddComponent(); } } [HarmonyPatch(typeof(Player), "HaveRequirementItems")] private static class PlayerHaveRequirementItemsPatch { public static IEnumerable Transpiler(IEnumerable instructions, ILGenerator ilGenerator) { bool patchedSuccess = false; List instrs = instructions.ToList(); int counter = 0; CodeInstruction ldArgInstruction = new CodeInstruction(OpCodes.Ldarg_0, (object)null); AccessTools.DeclaredMethod(typeof(Inventory), "CountItems", new Type[3] { typeof(string), typeof(int), typeof(bool) }, (Type[])null); int i = 0; while (i < instrs.Count) { if (i > 5 && instrs[i].opcode == OpCodes.Stloc_S && instrs[i + 1].opcode == OpCodes.Ldloc_S && instrs[i + 2].opcode == OpCodes.Ldloc_S && instrs[i - 1].opcode == OpCodes.Callvirt) { if (instrs[i].labels.Count > 0) { CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction); } yield return LogMessage(instrs[i]); counter++; yield return LogMessage(ldArgInstruction); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_2, (object)null)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_S, instrs[i].operand)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(PlayerPatches), "AdjustCountIfEquipped", (Type[])null, (Type[])null))); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Stloc_S, instrs[i].operand)); counter++; patchedSuccess = true; } else { yield return LogMessage(instrs[i]); counter++; } int num = i + 1; i = num; } if (!patchedSuccess) { AdventureBackpacks.Log.Error("HaveRequirementItems Transpiler Failed To Patch"); Thread.Sleep(5000); } CodeInstruction LogMessage(CodeInstruction instruction) { AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}"); return instruction; } } } [HarmonyPatch(typeof(Player), "ConsumeResources")] private static class PlayerConsumeResourcesPatch { public static IEnumerable Transpiler(IEnumerable instructions) { bool patchedSuccess = false; List instrs = instructions.ToList(); int counter = 0; CodeInstruction ldArgInstruction = new CodeInstruction(OpCodes.Ldarg_0, (object)null); MethodInfo getAmountMethod = AccessTools.DeclaredMethod(typeof(Requirement), "GetAmount", new Type[1] { typeof(int) }, (Type[])null); int i = 0; while (i < instrs.Count) { yield return LogMessage(instrs[i]); counter++; if (i > 5 && instrs[i].opcode == OpCodes.Stloc_3 && instrs[i - 1].opcode == OpCodes.Mul && instrs[i - 2].opcode == OpCodes.Ldarg_S && instrs[i - 3].opcode == OpCodes.Callvirt && instrs[i - 3].operand.Equals(getAmountMethod)) { if (instrs[i].labels.Count > 0) { CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction); } yield return LogMessage(ldArgInstruction); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_2, (object)null)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_3, (object)null)); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(PlayerPatches), "ConsumeUnEquippedItems", (Type[])null, (Type[])null))); counter++; yield return LogMessage(new CodeInstruction(OpCodes.Stloc_3, (object)null)); counter++; patchedSuccess = true; } int num = i + 1; i = num; } if (!patchedSuccess) { AdventureBackpacks.Log.Error("ConsumeResources Transpiler Failed To Patch"); Thread.Sleep(5000); } CodeInstruction LogMessage(CodeInstruction instruction) { AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}"); return instruction; } } } public static int AdjustCountIfEquipped(Player player, Requirement resource, int itemCount) { int num = itemCount; if (num < 1 || !resource.m_resItem.m_itemData.IsEquipable()) { return num; } Inventory val = ((player != null) ? ((Humanoid)player).GetInventory() : null); if (val == null) { return num; } string itemName = resource.m_resItem.m_itemData.m_shared.m_name; if (val.GetEquippedItems().Any((ItemData x) => x.m_shared.m_name.Equals(itemName))) { num--; } return num; } public static int ConsumeUnEquippedItems(Player player, Requirement resource, int amount) { if (amount < 1 || !resource.m_resItem.m_itemData.IsEquipable()) { return amount; } string itemName = resource.m_resItem.m_itemData.m_shared.m_name; List list = (from x in ((Humanoid)player).m_inventory.GetAllItems() where x.m_shared.m_name.Equals(itemName) select x).ToList(); int num = 0; for (int num2 = 0; num2 < amount; num2++) { foreach (ItemData item in list) { if (!item.m_equipped && num < amount) { ((Humanoid)player).m_inventory.RemoveItem(item, 1); num++; } } } return amount - num; } } public static class SEManPatches { [HarmonyPatch(typeof(SEMan), "RemoveStatusEffect", new Type[] { typeof(int), typeof(bool) })] public static class RemoveStatusEffects { [UsedImplicitly] [HarmonyPriority(800)] public static bool Prefix(int nameHash, ref bool __result) { if (EquipmentEffectCache.ActiveEffects == null) { return true; } if (EquipmentEffectCache.ActiveEffects.Any((StatusEffect x) => x.NameHash().Equals(nameHash))) { __result = false; return false; } return true; } } } public static class ItemStandStandPatches { [HarmonyPatch(typeof(ItemStand), "UpdateAttach")] private static class ItemStandUpdateAttachPatch { private static void Prefix(ItemStand __instance) { AdventureBackpacks.BypassMoveProtection = true; } private static void Postfix(ItemStand __instance) { AdventureBackpacks.BypassMoveProtection = false; } } } public class InventoryGridPatches { [HarmonyPatch(typeof(InventoryGrid), "UpdateGui")] public static class UpdateGuiPatch { [UsedImplicitly] [HarmonyPriority(800)] public static bool Prefix(InventoryGrid __instance) { if (!((Object)__instance).name.Equals("ContainerGrid")) { return true; } if (__instance.m_elements.Count >= __instance.m_inventory.m_inventory.Count) { return true; } if (__instance.m_width != __instance.m_inventory.m_width || __instance.m_height != __instance.m_inventory.m_height) { return true; } __instance.m_width = __instance.m_inventory.m_width + 1; __instance.m_height = __instance.m_inventory.m_height + 1; return true; } } } } namespace AdventureBackpacks.Features { public static class EquipmentEffectCache { public static HashSet ActiveEffects = new HashSet(); public static HashSet AddActiveBackpackEffects(HashSet other, Humanoid instance) { if (other == null) { AdventureBackpacks.Log.Debug("other HashSet argument is null. Expecting initialized object."); other = new HashSet(); } Player val = (Player)(object)((instance is Player) ? instance : null); if (val != null && (Object)(object)val == (Object)(object)Player.m_localPlayer) { ActiveEffects = new HashSet(); foreach (KeyValuePair effect in EffectsFactory.EffectList) { if (effect.Value.HasActiveStatusEffect((Humanoid)(object)val, out var statusEffect)) { ActiveEffects.Add(statusEffect); } } other.UnionWith(ActiveEffects); AdventureBackpacks.Log.Debug($"Adding {other.Count} Active Backpack Effects."); } return other; } } public static class QuickTransfer { [HarmonyPatch(typeof(InventoryGui), "OnRightClickItem")] [HarmonyPriority(800)] private static class OnRightClickItemPatch { private static void Prefix(InventoryGui __instance, InventoryGrid grid, ItemData item) { //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Expected I4, but got Unknown if (!FeatureInitialized || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)__instance == (Object)null || item == null || (Object)(object)__instance.m_currentContainer == (Object)null || !__instance.IsContainerOpen() || !EnableQuickTransfer.Value) { return; } if (Chainloader.PluginInfos.ContainsKey("blumaye.quicktransfer")) { AdventureBackpacks.Log.Warning("blumaye.quicktransfer mod is enabled. Adventure Backpack's Quick Transfer disabled."); } else { if (item.m_equipped) { return; } if (item.IsEquipable() && grid.m_inventory == ((Humanoid)Player.m_localPlayer).GetInventory()) { ItemType itemType = item.m_shared.m_itemType; switch (itemType - 3) { case 3: if (((Humanoid)Player.m_localPlayer).m_helmetItem == null) { return; } break; case 4: if (((Humanoid)Player.m_localPlayer).m_chestItem == null) { return; } break; case 8: if (((Humanoid)Player.m_localPlayer).m_legItem == null) { return; } break; case 0: case 1: case 11: if (((Humanoid)Player.m_localPlayer).m_rightItem == null) { return; } break; case 14: if (((Humanoid)Player.m_localPlayer).m_shoulderItem == null) { return; } break; case 15: if (((Humanoid)Player.m_localPlayer).m_utilityItem == null) { return; } break; case 2: if (((Humanoid)Player.m_localPlayer).m_leftItem == null) { return; } break; } } Inventory inventory = __instance.m_currentContainer.GetInventory(); if (item.IsBackpack() && inventory.IsBackPackInventory()) { return; } Inventory inventory2 = ((Humanoid)Player.m_localPlayer).GetInventory(); if (inventory2 != null && inventory != null && !((Object)(object)grid == (Object)null)) { _inventoryGuiInstance = __instance; if (grid.m_inventory == inventory) { _fromInventory = inventory; _toInventory = inventory2; } else { _fromInventory = inventory2; _toInventory = inventory; } _processingRightClick = true; } } } private static void Postfix() { _processingRightClick = false; _toInventory = null; _fromInventory = null; _inventoryGuiInstance = null; } } [HarmonyPatch(typeof(Humanoid), "UseItem")] [HarmonyPriority(800)] private static class UseItemPatch { private static bool Prefix(ItemData item) { //IL_004d: 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) if (!_processingRightClick) { return true; } if (_toInventory == null || _fromInventory == null || (Object)(object)_inventoryGuiInstance == (Object)null || item == null) { return true; } _toInventory.MoveItemToThis(_fromInventory, item); _inventoryGuiInstance.m_moveItemEffects.Create(((Component)_inventoryGuiInstance).transform.position, Quaternion.identity, (Transform)null, 1f, -1); return false; } } public static bool FeatureInitialized; public static ConfigEntry EnableQuickTransfer; private static InventoryGui _inventoryGuiInstance; private static Inventory _fromInventory; private static Inventory _toInventory; private static bool _processingRightClick; static QuickTransfer() { ConfigRegistry.Waiter.StatusChanged += delegate { RegisterConfiguraitonFile(); }; } private static void RegisterConfiguraitonFile() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown ConfigSyncBase.UnsyncedConfig("Local Config", "Enable Quick Right Click Item Transfer", value: false, new ConfigDescription("When enabled, can move items to/from player inventory to container, by right clicking.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Order = 5 } }), ref EnableQuickTransfer); } } public static class Utilities { private const string EmbeddedFolder = "Assets.Bundles"; public static AssetBundle LoadAssetBundle(string assetBundleFileName, string folderName = "Assets.Bundles") { AssetBundle val = FindLoadedAssetBundle(assetBundleFileName); if ((Object)(object)val != (Object)null) { return val; } return AssetUtils.LoadAssetBundleFromResources(folderName + "." + assetBundleFileName, typeof(Utilities).Assembly); } public static AssetBundle FindLoadedAssetBundle(string bundleFileName) { foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { if (!((Object)(object)allLoadedAssetBundle == (Object)null) && !string.IsNullOrEmpty(((Object)allLoadedAssetBundle).name) && ((Object)allLoadedAssetBundle).name.IndexOf(bundleFileName, StringComparison.OrdinalIgnoreCase) >= 0) { return allLoadedAssetBundle; } } string probePrefabName = GetProbePrefabName(bundleFileName); if (probePrefabName == null) { return null; } foreach (AssetBundle allLoadedAssetBundle2 in AssetBundle.GetAllLoadedAssetBundles()) { if (!((Object)(object)allLoadedAssetBundle2 == (Object)null) && ContainsAsset(allLoadedAssetBundle2, probePrefabName)) { return allLoadedAssetBundle2; } } return null; } private static string GetProbePrefabName(string bundleFileName) { return bundleFileName switch { "vapokbackpacks" => "CapeIronBackpack", "backpack_meadows" => "BackpackMeadows", "backpack_black_forest" => "BackpackBlackForest", "backpack_swamp" => "BackpackSwamp", "backpack_mountains" => "BackpackMountains", "backpack_plains" => "BackpackPlains", "backpack_mistlands" => "BackpackMistlands", _ => null, }; } private static bool ContainsAsset(AssetBundle bundle, string assetName) where T : Object { if ((Object)(object)bundle.LoadAsset(assetName) != (Object)null) { return true; } return (Object)(object)bundle.LoadAsset("Assets/vapok/Prefabs/" + assetName + ".prefab") != (Object)null; } } } namespace AdventureBackpacks.Extensions { public static class InventoryExtensions { public static bool IsBackPackInventory(this Inventory inventory) { if (inventory != null && !string.IsNullOrEmpty(inventory.m_name)) { return inventory.m_name.Contains("$vapok_mod_level"); } return false; } public static bool ContainsBackpack(this Inventory inventory, ItemData backpackItem) { return IsBackpackItemAt(inventory.m_width - 1, inventory.m_height - 1); bool IsBackpackItemAt(int x, int y) { if (x < 0) { x = inventory.m_width - 1; y--; } if (y < 0) { return false; } ItemData itemAt = inventory.GetItemAt(x, y); if (itemAt != null && itemAt == backpackItem) { return true; } return IsBackpackItemAt(x - 1, y); } } public static bool HasEmptySlot(this Inventory inventory) { return IsBackpackItemAt(inventory.m_width - 1, inventory.m_height - 1); bool IsBackpackItemAt(int x, int y) { if (x < 0) { x = inventory.m_width - 1; y--; } if (y < 0) { return false; } if (inventory.GetItemAt(x, y) == null) { return true; } return IsBackpackItemAt(x - 1, y); } } public static ItemData FindNonBackpackItem(this Inventory inventory) { return GetNonBackpackItem(inventory.m_width - 1, inventory.m_height - 1); ItemData GetNonBackpackItem(int x, int y) { if (x < 0) { x = inventory.m_width - 1; y--; } if (y < 0) { return null; } ItemData val = inventory.GetItemAt(x, y); if (val != null && val.IsBackpack()) { val = GetNonBackpackItem(x - 1, y); } return val; } } } public static class ItemDataExtensions { public static bool IsBackpack(this ItemData item) { return Backpacks.BackpackTypes.Contains(item.m_shared.m_name); } } public static class PlayerExtensions { public static bool IsBackpackEquipped(this Player player) { if ((Object)(object)player == (Object)null || ((Humanoid)player).GetInventory() == null) { return false; } if (((Humanoid)player).m_shoulderItem == null) { return false; } return ((Humanoid)player).m_shoulderItem.IsBackpack(); } public static bool IsThisBackpackEquipped(this Player player, ItemData itemData) { if ((Object)(object)player == (Object)null || ((Humanoid)player).GetInventory() == null) { return false; } if (((Humanoid)player).m_shoulderItem == null) { return false; } if (!((Humanoid)player).m_shoulderItem.IsBackpack()) { return false; } return ((object)((Humanoid)player).m_shoulderItem).Equals((object?)itemData); } public static BackpackComponent GetEquippedBackpack(this Player player) { if ((Object)(object)player == (Object)null || ((Humanoid)player).GetInventory() == null) { return null; } if (((Humanoid)player).m_shoulderItem == null) { return null; } if (((Humanoid)player).m_shoulderItem.IsBackpack()) { return ((Humanoid)player).m_shoulderItem.Data().GetOrCreate(); } return null; } public static bool CanOpenBackpack(this Player player) { return player.IsBackpackEquipped(); } public static void OpenBackpack(this Player player, InventoryGui instance) { if (!((Object)(object)player == (Object)null)) { Container backpackContainer = ((Component)player).gameObject.GetComponent(); player.GetEquippedBackpack()?.UpdateContainerSizing(ref backpackContainer); InventoryGuiPatches.BackpackIsOpen = true; instance.Show(backpackContainer, 1); } } public static void QuickDropBackpack(this Player player) { //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null) { return; } BackpackComponent equippedBackpack = player.GetEquippedBackpack(); if (equippedBackpack == null) { return; } ItemData val = null; bool flag = false; Inventory inventory = ((Humanoid)player).GetInventory(); if (!inventory.ContainsBackpack(equippedBackpack.Item) && !inventory.HasEmptySlot()) { val = inventory.FindNonBackpackItem(); if (val == null || !inventory.RemoveItem(val)) { ((Character)player).Message((MessageType)2, "$vapok_mod_quick_drop_unavailable", 0, (Sprite)null); return; } flag = true; } AdventureBackpacks.QuickDropping = true; AdventureBackpacks.Log.Message("Quick dropping backpack."); ((Humanoid)player).RemoveEquipAction(equippedBackpack.Item); ((Humanoid)player).UnequipItem(equippedBackpack.Item, true); if (!((Humanoid)player).m_inventory.RemoveItem(equippedBackpack.Item)) { if (flag) { inventory.AddItem(val); } AdventureBackpacks.QuickDropping = false; ((Character)player).Message((MessageType)2, "$vapok_mod_quick_drop_unavailable", 0, (Sprite)null); return; } ItemDrop val2 = ItemDrop.DropItem(equippedBackpack.Item, 1, ((Component)player).transform.position - ((Component)player).transform.forward + ((Component)player).transform.up, ((Component)player).transform.rotation); if ((Object)(object)val2 != (Object)null) { Rigidbody component = ((Component)val2).GetComponent(); if ((Object)(object)component != (Object)null) { component.linearVelocity = (Vector3.up - ((Component)player).transform.forward) * 5f; } val2.Save(); } ((Humanoid)player).m_dropEffects.Create(((Component)player).transform.position, Quaternion.identity, (Transform)null, 1f, -1); if (flag) { inventory.AddItem(val); } InventoryGuiPatches.BackpackIsOpen = false; AdventureBackpacks.QuickDropping = false; } } } namespace AdventureBackpacks.Configuration { public class ConfigRegistry : ConfigSyncBase { internal static ConfigEntry HotKeyOpen; internal static ConfigEntry HotKeyDrop; internal static ConfigEntry OpenWithInventory; internal static ConfigEntry OpenWithHoverInteract; internal static ConfigEntry CloseInventory; internal static ConfigEntry OutwardMode; internal static ConfigEntry ReplaceShader; public static Waiting Waiter; public ConfigRegistry(IPluginInfo mod) : base(mod) { Waiter = new Waiting(); InitializeConfigurationSettings(); } public sealed override void InitializeConfigurationSettings() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_002c: 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_003e: Expected O, but got Unknown //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Expected O, but got Unknown //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Expected O, but got Unknown //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Expected O, but got Unknown //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Expected O, but got Unknown //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Expected O, but got Unknown //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Expected O, but got Unknown //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Expected O, but got Unknown //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Expected O, but got Unknown if (ConfigSyncBase._config != null) { ConfigSyncBase.UnsyncedConfig("Local Config", "Open Backpack", new KeyboardShortcut((KeyCode)105, Array.Empty()), new ConfigDescription("Hotkey to open backpack.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Order = 3 } }), ref HotKeyOpen); ConfigSyncBase.UnsyncedConfig("Local Config", "Quickdrop Backpack", new KeyboardShortcut((KeyCode)121, Array.Empty()), new ConfigDescription("Hotkey to quickly drop backpack while on the run.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Order = 1 } }), ref HotKeyDrop); ConfigSyncBase.UnsyncedConfig("Local Config", "Open with Inventory", value: false, new ConfigDescription("If enabled, both backpack and inventory will open when Inventory is opened.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Order = 3 } }), ref OpenWithInventory); ConfigSyncBase.UnsyncedConfig("Local Config", "Open with Interactive Hover", value: false, new ConfigDescription("If enabled, backpack will only open while hovering over equipped backpack and pressing hotkey. This option overrides Open with Inventory.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Order = 3 } }), ref OpenWithHoverInteract); ConfigSyncBase.UnsyncedConfig("Local Config", "Close Inventory", value: true, new ConfigDescription("If enabled, both backpack and inventory will close with Open Backpack keybind is pressed while Inventory is open.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Order = 2 } }), ref CloseInventory); ConfigSyncBase.UnsyncedConfig("Local Config", "Outward Mode", value: false, new ConfigDescription("You can use a hotkey to quickly drop your equipped backpack in order to run faster away from danger.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Order = 1 } }), ref OutwardMode); ConfigSyncBase.UnsyncedConfig("Local Config", "Replace Shader", value: true, new ConfigDescription("Toggle To use the Material Shader Replacer (Requires Game Restart)", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Order = 1 } }), ref ReplaceShader); } } } public class Waiting { public event EventHandler StatusChanged; public void ConfigurationComplete(bool configDone) { if (configDone) { this.StatusChanged?.Invoke(this, EventArgs.Empty); } } } } namespace AdventureBackpacks.Components { public class BackpackComponent : CustomItemData { public static string OldPluginCustomData = "JotunnBackpacks#JotunnBackpacks.BackpackComponent"; private Inventory _backpackInventory; private CustomSE _statusEffects; public bool IsLoadingInventory; public bool IsEmptyingBackpack; private ILogIt _log = AdventureBackpacks.Log; public void SetInventory(Inventory inventoryInstance) { _backpackInventory = inventoryInstance; Save(_backpackInventory); } public bool InventoryNeedsValidating(Vector2i backpackDimension) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (_backpackInventory.m_width == backpackDimension.x) { return _backpackInventory.m_height != backpackDimension.y; } return true; } public Inventory GetInventory() { return _backpackInventory; } public void UpdateContainerSizing(ref Container backpackContainer) { Inventory inventory = GetInventory(); backpackContainer.m_inventory = inventory; backpackContainer.m_width = inventory.m_width; backpackContainer.m_height = inventory.m_height; backpackContainer.m_bkg = base.Item.m_shared.m_icons[0]; } public string Serialize() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown _log.Debug($"[Serialize() - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Starting.."); ZPackage val = new ZPackage(); if (_backpackInventory == null) { _backpackInventory = Backpacks.NewInventoryInstance(base.Item.m_shared.m_name, base.Item.m_quality); } _backpackInventory.Save(val); string result = (base.Value = val.GetBase64()); _log.Debug($"[Serialize() - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Value = {base.Value}"); return result; } public void Deserialize(string data) { //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Expected O, but got Unknown _log.Debug($"[Deserialize() - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Starting.."); try { string name = base.Item.m_shared.m_name; _backpackInventory = Backpacks.NewInventoryInstance(name, base.Item.m_quality); _log.Debug($"[Deserialize() - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Value Before = {base.Value}"); _log.Debug($"[Deserialize() - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] data = {data}"); base.Value = data; _log.Debug($"[Deserialize() - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Value After = {base.Value}"); ZPackage val = new ZPackage(data); _log.Debug($"[Deserialize() - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Inventory Count Before Load: {_backpackInventory.m_inventory.Count}"); _backpackInventory.Load(val); _log.Debug($"[Deserialize() - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Inventory Count After Load: {_backpackInventory.m_inventory.Count}"); _statusEffects = Backpacks.UpdateStatusEffects(base.Item); } catch (Exception arg) { _log.Error($" - {base.Item.m_shared.m_name} Backpack info is corrupt!\n{arg}"); } } public override void FirstLoad() { string name = base.Item.m_shared.m_name; _log.Debug($"[FirstLoad - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] {name}"); if (!Backpacks.BackpackTypes.Contains(name)) { return; } if (_backpackInventory == null) { _backpackInventory = Backpacks.NewInventoryInstance(name, base.Item.m_quality); if (!string.IsNullOrEmpty(base.Value)) { Deserialize(base.Value); } if (base.Item.m_customData.ContainsKey(OldPluginCustomData) && string.IsNullOrEmpty(base.Value)) { string value = base.Item.m_customData[OldPluginCustomData]; base.Value = value; Deserialize(base.Value); } else { _log.Debug($"[Load - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Backpack null, creating..."); Serialize(); } } else if (string.IsNullOrEmpty(base.Value)) { Serialize(); } } public override void Load() { _log.Debug($"[Load - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Starting"); IsLoadingInventory = true; if (!string.IsNullOrEmpty(base.Value)) { _log.Debug($"[Load - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Value = {base.Value}"); Deserialize(base.Value); } else { if (_backpackInventory == null) { _log.Debug($"[Load - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Backpack null, creating..."); string name = base.Item.m_shared.m_name; _backpackInventory = Backpacks.NewInventoryInstance(name, base.Item.m_quality); } Serialize(); } IsLoadingInventory = false; } public override void Save() { if (_backpackInventory == null) { Serialize(); return; } _log.Debug($"[Save() - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Starting Value = {base.Value}"); _log.Debug($"[Save() - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Starting backpack count {_backpackInventory.m_inventory.Count}"); base.Value = Serialize(); _log.Debug($"[Save() - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Ending backpack count {_backpackInventory.m_inventory.Count}"); } public void Save(Inventory backpack) { if (backpack == null) { _log.Warning($"[Save(Inventory) - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Ignoring save: inventory argument was null."); return; } _log.Debug($"[Save(Inventory) - {base.Item.m_shared.m_name}-Q{base.Item.m_quality}] Starting backpack count {backpack.m_inventory.Count}"); _backpackInventory = backpack; Save(); } public CustomItemData Clone() { return MemberwiseClone() as CustomItemData; } } } namespace AdventureBackpacks.Assets { public static class Backpacks { private static ILogIt _log = AdventureBackpacks.Log; private static List _backpackTypes = new List(); public static List BackpackTypes => _backpackTypes; public static void LoadBackpackTypes(List backpackTypes) { _backpackTypes = backpackTypes; } internal static bool TryGetBackpackItem(this ItemData itemData, out BackpackItem backpack) { backpack = null; if (itemData == null) { return false; } return TryGetBackpackItemByName(itemData.m_shared.m_name, out backpack); } internal static bool TryGetBackpackItemByName(string name, out BackpackItem backpack) { backpack = null; if (Utility.IsNullOrWhiteSpace(name)) { return false; } backpack = BackpackFactory.BackpackItems.FirstOrDefault((BackpackItem x) => x.ItemName.Equals(name)); return backpack != null; } public static void UpdateItemDataConfigValues(object sender, EventArgs e) { Player player; if (!((Object)(object)Player.m_localPlayer == (Object)null) && ((Humanoid)Player.m_localPlayer).GetInventory() != null) { player = Player.m_localPlayer; if ((Object)(object)InventoryGui.instance != (Object)null) { InventoryGui.instance.Hide(); } Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory(); if (inventory != null) { SearchInventory(inventory.m_inventory); } List equippedItems = ((Humanoid)Player.m_localPlayer).GetInventory().GetEquippedItems(); if (equippedItems != null) { SearchInventory(equippedItems); } ((Humanoid)Player.m_localPlayer).UpdateEquipmentStatusEffects(); } void SearchInventory(List list) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) if (list == null) { return; } foreach (ItemData item in list) { if (item != null && item.IsBackpack() && item.TryGetBackpackItem(out var backpack)) { BackpackComponent orCreate = item.Data().GetOrCreate(); Vector2i inventorySize = backpack.GetInventorySize(orCreate.Item.m_quality); if (orCreate.InventoryNeedsValidating(inventorySize)) { ValidateBackpackInventorySizing(player, item); } } } } } public static Inventory NewInventoryInstance(string name, int itemMQuality = 1) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0028: 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: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown string text = $"{name} $vapok_mod_level {itemMQuality}"; if (!TryGetBackpackItemByName(name, out var backpack)) { return null; } Vector2i inventorySize = backpack.GetInventorySize(itemMQuality); return new Inventory(text, (Sprite)null, inventorySize.x, inventorySize.y); } public static Vector2 ValidateMinMaxChestSize(float x, float y) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) if (x < 1f) { x = 1f; } if (y < 1f) { y = 1f; } return new Vector2(x, y); } public static void ValidateBackpackInventorySizing(Player player, ItemData currentBackpack) { //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null || currentBackpack?.m_shared == null) { return; } AdventureBackpacks.Log.Debug("############################################"); AdventureBackpacks.Log.Debug("#### ValidateBackpackInventorySizing #####"); AdventureBackpacks.Log.Debug(currentBackpack.m_shared.m_name ?? ""); AdventureBackpacks.Log.Debug("############################################"); StackTrace stackTrace = new StackTrace(); for (int i = 1; i <= 20 && stackTrace.FrameCount >= i; i++) { MethodBase methodBase = stackTrace.GetFrame(i)?.GetMethod(); AdventureBackpacks.Log.Debug($"[{i}]Called by: {methodBase?.DeclaringType?.FullName}.{methodBase?.Name}"); } if (!currentBackpack.TryGetBackpackItem(out var backpack)) { return; } if (!backpack.BackpackSize.TryGetValue(currentBackpack.m_quality, out var value)) { AdventureBackpacks.Log.Warning($"Backpack '{currentBackpack.m_shared.m_name}' has unexpected quality '{currentBackpack.m_quality}'. " + "Falling back to quality 1."); value = backpack.BackpackSize[1]; } Vector2 val = ValidateMinMaxChestSize(value.Value.x, value.Value.y); int num = (int)Math.Floor(val.x) * (int)Math.Floor(val.y); AdventureBackpacks.Log.Debug($"[{currentBackpack.m_shared.m_name}]### Backpack Slot Size: {num}"); BackpackComponent orCreate = currentBackpack.Data().GetOrCreate(); Inventory inventory = orCreate.GetInventory(); if (inventory == null) { AdventureBackpacks.Log.Warning("[" + currentBackpack.m_shared.m_name + "] ValidateBackpackInventorySizing: backpack inventory was null; skipping."); return; } AdventureBackpacks.Log.Debug($"[{currentBackpack.m_shared.m_name}]### Current Inventory Slot Size: {inventory.m_inventory.Count}"); if (num < inventory.m_inventory.Count) { int num2 = inventory.m_inventory.Count - num; AdventureBackpacks.Log.Debug($"[{currentBackpack.m_shared.m_name}]### I need to YEET {num2} items"); PerformYardSale(player, orCreate.Item, backpackOnly: true, num2); int count = inventory.m_inventory.Count; AdventureBackpacks.Log.Debug($"[{currentBackpack.m_shared.m_name}]### New Inventory Size {count}"); orCreate.IsLoadingInventory = true; Inventory val2 = NewInventoryInstance(backpack.ItemName, currentBackpack.m_quality); if (val2 == null) { AdventureBackpacks.Log.Warning("[" + currentBackpack.m_shared.m_name + "] Could not create resized inventory instance; skipping MoveAll."); orCreate.IsLoadingInventory = false; } else { val2.MoveAll(inventory); orCreate.IsLoadingInventory = false; orCreate.Save(val2); } } orCreate.Load(); if (player.IsThisBackpackEquipped(currentBackpack)) { Container backpackContainer = ((Component)player).gameObject.GetComponent(); if ((Object)(object)backpackContainer != (Object)null) { orCreate.UpdateContainerSizing(ref backpackContainer); } } AdventureBackpacks.Log.Debug("############################################"); AdventureBackpacks.Log.Debug("DONE ValidateBackpackInventorySizing DONE"); AdventureBackpacks.Log.Debug(currentBackpack.m_shared.m_name ?? ""); AdventureBackpacks.Log.Debug("############################################"); } public static bool CheckForInception(Inventory instance, ItemData item) { if (instance.IsBackPackInventory() && (Object)(object)Player.m_localPlayer != (Object)null) { if (item.TryGetBackpackItem(out var backpack)) { backpack.InceptionCounter++; switch (backpack.InceptionCounter) { case 1: ((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_no_inception1", 0, (Sprite)null); break; case 2: ((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_no_inception2", 0, (Sprite)null); break; case 5: ((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_no_inception3", 0, (Sprite)null); break; case 10: { ((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_no_inception4", 0, (Sprite)null); int num = new Random(42).Next(5000, 20000); backpack.YardSaleTimer = new System.Timers.Timer(num); backpack.YardSaleTimer.AutoReset = false; backpack.YardSaleTimer.Enabled = false; backpack.YardSaleTimer.Elapsed += delegate { YardSaleEvent(backpack); }; backpack.YardSaleTimer.Start(); break; } } return false; } } return true; } public static bool PerformYardSale(Player mLocalPlayer, ItemData itemData, bool backpackOnly = false, int numberItems = 0) { if (!itemData.IsBackpack()) { return true; } BackpackComponent backpack = itemData.Data().Get(); if (backpack == null) { return true; } bool dropWasBlocked = false; EmtpyInventory(backpack.GetInventory()); if (dropWasBlocked) { if (!backpackOnly) { AdventureBackpacks.PerformYardSale = false; } return false; } if (!backpackOnly) { Inventory inventory = ((Humanoid)mLocalPlayer).GetInventory(); EmtpyInventory(inventory); ((Humanoid)mLocalPlayer).UnequipAllItems(); EmtpyInventory(inventory); ((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_no_inception5", 0, (Sprite)null); AdventureBackpacks.PerformYardSale = false; } else { ((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_thor_saves_contents", 0, (Sprite)null); } return true; void EmtpyInventory(Inventory val) { if (backpack.IsEmptyingBackpack) { return; } AdventureBackpacks.Log.Debug($"[{itemData.m_shared.m_name}]Number of Items: {numberItems}"); AdventureBackpacks.Log.Debug($"[{itemData.m_shared.m_name}]Inventory Count: {val.m_inventory.Count}"); backpack.IsEmptyingBackpack = true; try { if (numberItems == 0) { while (val.m_inventory.Count > 0 && val.m_inventory.Count != 0 && val.m_inventory[0] != null) { ItemData val2 = val.m_inventory[0]; int num = val.CountItems(val2.m_shared.m_name, -1, true); int num2 = ((num > val2.m_stack) ? val2.m_stack : num); int num3 = val.CountItems(val2.m_shared.m_name, -1, true); ((Humanoid)mLocalPlayer).DropItem(val, val2, num2); if (val.CountItems(val2.m_shared.m_name, -1, true) >= num3) { AdventureBackpacks.Log.Warning("[" + itemData.m_shared.m_name + "] DropItem did not remove from inventory (another mod may have blocked it). Stopping to avoid duplication."); dropWasBlocked = true; break; } } } else { for (int i = 0; i < numberItems; i++) { if (val.m_inventory.Count <= 0) { break; } if (val.m_inventory.Count == 0) { break; } if (val.m_inventory[0] == null) { break; } ItemData val3 = val.m_inventory[0]; int num4 = val.CountItems(val3.m_shared.m_name, -1, true); AdventureBackpacks.Log.Debug($"[{itemData.m_shared.m_name}] Number of {val3.m_shared.m_name}: {num4}"); AdventureBackpacks.Log.Debug($"[{itemData.m_shared.m_name}] Stack Size of {val3.m_shared.m_name}: {val3.m_stack}"); int num5 = ((num4 > val3.m_stack) ? val3.m_stack : num4); AdventureBackpacks.Log.Debug($"[{itemData.m_shared.m_name}] Drop Amount: {num5}"); int num6 = val.CountItems(val3.m_shared.m_name, -1, true); ((Humanoid)mLocalPlayer).DropItem(val, val3, num5); if (val.CountItems(val3.m_shared.m_name, -1, true) >= num6) { AdventureBackpacks.Log.Warning("[" + itemData.m_shared.m_name + "] DropItem did not remove from inventory (another mod may have blocked it). Stopping to avoid duplication."); dropWasBlocked = true; break; } } } AdventureBackpacks.Log.Debug($"[{itemData.m_shared.m_name}] Inventory Count (end): {val.m_inventory.Count}"); } finally { backpack.IsEmptyingBackpack = false; } } } private static void YardSaleEvent(BackpackItem backpack) { backpack.YardSaleTimer.Stop(); AdventureBackpacks.PerformYardSale = true; } public static CustomSE UpdateStatusEffects(ItemData itemData) { //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) if (itemData == null) { return null; } if (!itemData.TryGetBackpackItem(out var backpack)) { return null; } string name = itemData.m_shared.m_name; int quality = itemData.m_quality; CustomSE customSE = new CustomSE(Enums.StatusEffects.Stats, $"SE_{name}_{quality}"); string text = $"{name} $vapok_mod_level {quality} $vapok_mod_effect"; if (backpack.ShowBackpackStatusEffect.Value) { customSE.Effect.m_name = (string.IsNullOrEmpty(backpack.CustomStatusEffectName.Value) ? text : backpack.CustomStatusEffectName.Value); customSE.Effect.m_startMessageType = (MessageType)1; customSE.Effect.m_startMessage = "$vapok_mod_useful_backpack"; } List list = new List(); itemData.m_shared.m_armor = itemData.m_shared.m_armorPerLevel * (float)quality; if (EffectsFactory.EffectList[BackpackEffect.FrostResistance].IsEffectActive(itemData)) { list.Add(FrostResistance.EffectMod); } if (EffectsFactory.EffectList[BackpackEffect.TrollArmor].HasActiveStatusEffect(itemData, out var statusEffect)) { itemData.m_shared.m_setName = "troll"; itemData.m_shared.m_setSize = 4; itemData.m_shared.m_setStatusEffect = statusEffect; } else { itemData.m_shared.m_setName = string.Empty; itemData.m_shared.m_setSize = 0; itemData.m_shared.m_setStatusEffect = null; } backpack.UpdateStatusEffects(quality, customSE, list, itemData); itemData.m_shared.m_maxDurability = 1000f; ((SE_Stats)customSE.Effect).m_mods = list; if (backpack.ShowBackpackStatusEffect.Value) { ((StatusEffect)(SE_Stats)customSE.Effect).m_icon = itemData.GetIcon(); } itemData.AddSEToItem(customSE); return customSE; } } } namespace AdventureBackpacks.Assets.Items { internal interface IAssetItem { string PrefabName { get; } string ItemName { get; } Item Item { get; } } internal abstract class AssetItem : IAssetItem { private readonly string _assetFolderName = "Assets.Bundles"; private readonly Item _item; public string AssetName { get; } public string PrefabName { get; } public string ItemName { get; } public Item Item => _item; internal AssetItem(GameObject goItem, string itemName) { PrefabName = ((Object)goItem).name; ItemName = itemName; _item = new Item(goItem) { Configurable = Configurability.Disabled }; SetupItem(); } internal AssetItem(AssetBundle bundle, string prefabName, string itemName) { PrefabName = prefabName; ItemName = itemName; _item = new Item(bundle, prefabName) { Configurable = Configurability.Disabled }; SetupItem(); } internal AssetItem(string assetName, string prefabName, string itemName) { AssetName = assetName; PrefabName = prefabName; ItemName = itemName; _item = new Item(AssetName, PrefabName, _assetFolderName) { Configurable = Configurability.Disabled }; SetupItem(); } private void SetupItem() { SetPersistence(); ResetPrefabArmor(); } internal void AssignCraftingTable(ItemManager.CraftingTable craftingTable, int stationLevel) { _item.Crafting.Add(craftingTable, stationLevel); } internal void AssignCraftingTable(string craftingTable, int stationLevel) { if (Enum.TryParse(craftingTable, ignoreCase: true, out var result)) { _item.Crafting.Add(result, stationLevel); } else { _item.Crafting.Add(craftingTable, stationLevel); } } internal void AddRecipeIngredient(string prefabName, int quantity) { _item.RequiredItems.Add(prefabName, quantity); } internal void AddUpgradeIngredient(string prefabName, int quantity) { _item.RequiredUpgradeItems.Add(prefabName, quantity); } internal ItemDrop GetItemDrop() { Item item = _item; if (item == null) { return null; } return item.Prefab.GetComponent(); } internal void RegisterShaderSwap(MaterialReplacer.ShaderType shaderType = MaterialReplacer.ShaderType.PieceShader) { if (ConfigRegistry.ReplaceShader.Value) { MaterialReplacer.RegisterGameObjectForShaderSwap(_item.Prefab, shaderType); } } internal void SetPersistence() { _item.Prefab.GetComponent().m_persistent = true; } internal void ResetPrefabArmor() { ItemDrop itemDrop = GetItemDrop(); ItemData itemData = itemDrop.m_itemData; if (itemData != null) { itemDrop.m_autoPickup = true; itemData.m_shared.m_armor = itemData.m_shared.m_armorPerLevel; itemDrop.Save(); } } } internal static class IronBackpackIconFix { internal const string IconTextureName = "IronBackpack_Icon"; private const string EmbeddedPngSuffix = "Icons.IronBackpack_Icon.png"; private static readonly string[] TargetPrefabNames = new string[2] { "BackpackBlackForest", "CapeIronBackpack" }; private static readonly string[] ItemNameTokens = new string[2] { "vapok_mod_item_backpack_blackforest", "vapok_mod_item_rugged_backpack" }; private static Sprite _cachedIcon; private static bool _loggedFailure; private static bool _loggedGetIcon; internal static bool IsIronHdBackpack(SharedData shared) { if (shared == null || shared.m_name == null) { return false; } string[] itemNameTokens = ItemNameTokens; foreach (string value in itemNameTokens) { if (shared.m_name.Contains(value)) { return true; } } return false; } internal static bool IsIronHdBackpack(ItemData item) { if (item?.m_shared == null) { return false; } if (IsIronHdBackpack(item.m_shared)) { return true; } if (item.TryGetBackpackItem(out var backpack) && IsTargetPrefab(backpack.PrefabName)) { return true; } if ((Object)(object)ObjectDB.instance == (Object)null) { return false; } string[] targetPrefabNames = TargetPrefabNames; foreach (string text in targetPrefabNames) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text); ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent() : null); if ((Object)(object)val != (Object)null && item.m_shared == val.m_itemData.m_shared) { return true; } } return false; } private static bool IsTargetPrefab(string prefabName) { if (string.IsNullOrEmpty(prefabName)) { return false; } string[] targetPrefabNames = TargetPrefabNames; foreach (string b in targetPrefabNames) { if (string.Equals(prefabName, b, StringComparison.Ordinal)) { return true; } } return false; } internal static Sprite GetOrCreateIcon() { if ((Object)(object)_cachedIcon != (Object)null) { return _cachedIcon; } _cachedIcon = LoadEmbeddedPngIcon(); if ((Object)(object)_cachedIcon != (Object)null) { AdventureBackpacks.Log.Message($"[IronBackpack] Icon loaded from embedded PNG ({((Texture)_cachedIcon.texture).width}x{((Texture)_cachedIcon.texture).height})."); return _cachedIcon; } foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { if (!((Object)(object)allLoadedAssetBundle == (Object)null) && TryCreateIconFromBundleTexture(allLoadedAssetBundle, out _cachedIcon)) { AdventureBackpacks.Log.Message($"[IronBackpack] Icon built from bundle texture '{((Object)allLoadedAssetBundle).name}' ({((Texture)_cachedIcon.texture).width}x{((Texture)_cachedIcon.texture).height})."); return _cachedIcon; } } LogOnce("Could not load IronBackpack_Icon (embedded PNG or bundle texture)."); return null; } private static Sprite LoadEmbeddedPngIcon() { //IL_00ca: 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) Assembly assembly = typeof(IronBackpackIconFix).Assembly; string text = null; string[] manifestResourceNames = assembly.GetManifestResourceNames(); foreach (string text2 in manifestResourceNames) { if (text2.EndsWith("Icons.IronBackpack_Icon.png", StringComparison.OrdinalIgnoreCase) || text2.EndsWith("IronBackpack_Icon.png", StringComparison.OrdinalIgnoreCase)) { text = text2; break; } } if (text == null) { AdventureBackpacks.Log.Warning("[IronBackpack] Embedded PNG resource not found in mod assembly."); return null; } using Stream stream = assembly.GetManifestResourceStream(text); if (stream == null) { return null; } byte[] array = new byte[stream.Length]; stream.Read(array, 0, array.Length); Texture2D val = AssetUtils.LoadImage(array); if ((Object)(object)val == (Object)null) { return null; } Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f); ((Object)obj).name = "IronBackpack_Icon"; return obj; } private static bool TryCreateIconFromBundleTexture(AssetBundle bundle, out Sprite icon) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) icon = null; if ((Object)(object)bundle == (Object)null) { return false; } Texture2D val = null; Texture2D[] array = bundle.LoadAllAssets(); foreach (Texture2D val2 in array) { if ((Object)(object)val2 != (Object)null && ((Object)val2).name.IndexOf("IronBackpack_Icon", StringComparison.OrdinalIgnoreCase) >= 0) { val = val2; break; } } if (val == null) { val = bundle.LoadAsset("IronBackpack_Icon"); } if (val == null) { val = bundle.LoadAsset("Assets/Texture2D/IronBackpack_Icon.png"); } if ((Object)(object)val == (Object)null) { return false; } Texture2D val3 = DuplicateReadableTexture(val); if ((Object)(object)val3 == (Object)null) { return false; } icon = Sprite.Create(val3, new Rect(0f, 0f, (float)((Texture)val3).width, (float)((Texture)val3).height), new Vector2(0.5f, 0.5f), 100f); ((Object)icon).name = "IronBackpack_Icon"; return true; } private static Texture2D DuplicateReadableTexture(Texture2D source) { if ((Object)(object)source == (Object)null) { return null; } try { return AssetUtils.DuplicateTexture(source); } catch (Exception ex) { AdventureBackpacks.Log.Warning("[IronBackpack] DuplicateTexture failed: " + ex.Message); return null; } } internal static void Apply() { Sprite orCreateIcon = GetOrCreateIcon(); if ((Object)(object)orCreateIcon == (Object)null) { return; } string[] targetPrefabNames = TargetPrefabNames; foreach (string text in targetPrefabNames) { foreach (BackpackItem backpackItem in BackpackFactory.BackpackItems) { if (string.Equals(backpackItem.PrefabName, text, StringComparison.Ordinal)) { Item item = backpackItem.Item; object drop; if (item == null) { drop = null; } else { GameObject prefab = item.Prefab; drop = ((prefab != null) ? prefab.GetComponent() : null); } ApplyToItemDrop((ItemDrop)drop, orCreateIcon); } } if ((Object)(object)ZNetScene.instance != (Object)null) { GameObject prefab2 = ZNetScene.instance.GetPrefab(text); ApplyToItemDrop((prefab2 != null) ? prefab2.GetComponent() : null, orCreateIcon); } if ((Object)(object)ObjectDB.instance != (Object)null) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text); ApplyToItemDrop((itemPrefab != null) ? itemPrefab.GetComponent() : null, orCreateIcon); } } AdventureBackpacks.Log.Message("[IronBackpack] Prefab icon arrays patched (BackpackBlackForest, CapeIronBackpack)."); } internal static void NotifyGetIconOverride(ItemData item) { if (!_loggedGetIcon) { _loggedGetIcon = true; string text = item?.m_shared?.m_name ?? "(unknown)"; AdventureBackpacks.Log.Message("[IronBackpack] GetIcon override active for '" + text + "'."); } } private static void ApplyToItemDrop(ItemDrop drop, Sprite icon) { if (drop?.m_itemData?.m_shared != null) { Sprite[] array = (Sprite[])(object)new Sprite[Math.Max(1, drop.m_itemData.m_shared.m_variants)]; for (int i = 0; i < array.Length; i++) { array[i] = icon; } drop.m_itemData.m_shared.m_icons = array; drop.Save(); } } private static void LogOnce(string message) { if (!_loggedFailure) { _loggedFailure = true; AdventureBackpacks.Log.Warning("[IronBackpack] Inventory icon fix failed: " + message); } } } internal static class SilverBackpackIconFix { internal const string IconTextureName = "SilverBackpack_Icon"; private const string EmbeddedPngSuffix = "Icons.SilverBackpack_Icon.png"; private static readonly string[] TargetPrefabNames = new string[2] { "BackpackMountains", "CapeSilverBackpack" }; private static readonly string[] ItemNameTokens = new string[2] { "vapok_mod_item_backpack_mountains", "vapok_mod_item_arctic_backpack" }; private static Sprite _cachedIcon; private static bool _loggedFailure; private static bool _loggedGetIcon; internal static bool IsSilverHdBackpack(SharedData shared) { if (shared == null || shared.m_name == null) { return false; } string[] itemNameTokens = ItemNameTokens; foreach (string value in itemNameTokens) { if (shared.m_name.Contains(value)) { return true; } } return false; } internal static bool IsSilverHdBackpack(ItemData item) { if (item?.m_shared == null) { return false; } if (IsSilverHdBackpack(item.m_shared)) { return true; } if (item.TryGetBackpackItem(out var backpack) && IsTargetPrefab(backpack.PrefabName)) { return true; } if ((Object)(object)ObjectDB.instance == (Object)null) { return false; } string[] targetPrefabNames = TargetPrefabNames; foreach (string text in targetPrefabNames) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text); ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent() : null); if ((Object)(object)val != (Object)null && item.m_shared == val.m_itemData.m_shared) { return true; } } return false; } private static bool IsTargetPrefab(string prefabName) { if (string.IsNullOrEmpty(prefabName)) { return false; } string[] targetPrefabNames = TargetPrefabNames; foreach (string b in targetPrefabNames) { if (string.Equals(prefabName, b, StringComparison.Ordinal)) { return true; } } return false; } internal static Sprite GetOrCreateIcon() { if ((Object)(object)_cachedIcon != (Object)null) { return _cachedIcon; } _cachedIcon = LoadEmbeddedPngIcon(); if ((Object)(object)_cachedIcon != (Object)null) { AdventureBackpacks.Log.Message($"[SilverBackpack] Icon loaded from embedded PNG ({((Texture)_cachedIcon.texture).width}x{((Texture)_cachedIcon.texture).height})."); return _cachedIcon; } foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { if (!((Object)(object)allLoadedAssetBundle == (Object)null) && TryCreateIconFromBundleTexture(allLoadedAssetBundle, out _cachedIcon)) { AdventureBackpacks.Log.Message($"[SilverBackpack] Icon built from bundle texture '{((Object)allLoadedAssetBundle).name}' ({((Texture)_cachedIcon.texture).width}x{((Texture)_cachedIcon.texture).height})."); return _cachedIcon; } } LogOnce("Could not load SilverBackpack_Icon (embedded PNG or bundle texture)."); return null; } private static Sprite LoadEmbeddedPngIcon() { //IL_00ca: 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) Assembly assembly = typeof(SilverBackpackIconFix).Assembly; string text = null; string[] manifestResourceNames = assembly.GetManifestResourceNames(); foreach (string text2 in manifestResourceNames) { if (text2.EndsWith("Icons.SilverBackpack_Icon.png", StringComparison.OrdinalIgnoreCase) || text2.EndsWith("SilverBackpack_Icon.png", StringComparison.OrdinalIgnoreCase)) { text = text2; break; } } if (text == null) { AdventureBackpacks.Log.Warning("[SilverBackpack] Embedded PNG resource not found in mod assembly."); return null; } using Stream stream = assembly.GetManifestResourceStream(text); if (stream == null) { return null; } byte[] array = new byte[stream.Length]; stream.Read(array, 0, array.Length); Texture2D val = AssetUtils.LoadImage(array); if ((Object)(object)val == (Object)null) { return null; } Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f); ((Object)obj).name = "SilverBackpack_Icon"; return obj; } private static bool TryCreateIconFromBundleTexture(AssetBundle bundle, out Sprite icon) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) icon = null; if ((Object)(object)bundle == (Object)null) { return false; } Texture2D val = null; Texture2D[] array = bundle.LoadAllAssets(); foreach (Texture2D val2 in array) { if ((Object)(object)val2 != (Object)null && ((Object)val2).name.IndexOf("SilverBackpack_Icon", StringComparison.OrdinalIgnoreCase) >= 0) { val = val2; break; } } if (val == null) { val = bundle.LoadAsset("SilverBackpack_Icon"); } if (val == null) { val = bundle.LoadAsset("Assets/Texture2D/SilverBackpack_Icon.png"); } if ((Object)(object)val == (Object)null) { return false; } Texture2D val3 = DuplicateReadableTexture(val); if ((Object)(object)val3 == (Object)null) { return false; } icon = Sprite.Create(val3, new Rect(0f, 0f, (float)((Texture)val3).width, (float)((Texture)val3).height), new Vector2(0.5f, 0.5f), 100f); ((Object)icon).name = "SilverBackpack_Icon"; return true; } private static Texture2D DuplicateReadableTexture(Texture2D source) { if ((Object)(object)source == (Object)null) { return null; } try { return AssetUtils.DuplicateTexture(source); } catch (Exception ex) { AdventureBackpacks.Log.Warning("[SilverBackpack] DuplicateTexture failed: " + ex.Message); return null; } } internal static void Apply() { Sprite orCreateIcon = GetOrCreateIcon(); if ((Object)(object)orCreateIcon == (Object)null) { return; } string[] targetPrefabNames = TargetPrefabNames; foreach (string text in targetPrefabNames) { foreach (BackpackItem backpackItem in BackpackFactory.BackpackItems) { if (string.Equals(backpackItem.PrefabName, text, StringComparison.Ordinal)) { Item item = backpackItem.Item; object drop; if (item == null) { drop = null; } else { GameObject prefab = item.Prefab; drop = ((prefab != null) ? prefab.GetComponent() : null); } ApplyToItemDrop((ItemDrop)drop, orCreateIcon); } } if ((Object)(object)ZNetScene.instance != (Object)null) { GameObject prefab2 = ZNetScene.instance.GetPrefab(text); ApplyToItemDrop((prefab2 != null) ? prefab2.GetComponent() : null, orCreateIcon); } if ((Object)(object)ObjectDB.instance != (Object)null) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text); ApplyToItemDrop((itemPrefab != null) ? itemPrefab.GetComponent() : null, orCreateIcon); } } AdventureBackpacks.Log.Message("[SilverBackpack] Prefab icon arrays patched (BackpackMountains, CapeSilverBackpack)."); } internal static void NotifyGetIconOverride(ItemData item) { if (!_loggedGetIcon) { _loggedGetIcon = true; string text = item?.m_shared?.m_name ?? "(unknown)"; AdventureBackpacks.Log.Message("[SilverBackpack] GetIcon override active for '" + text + "'."); } } private static void ApplyToItemDrop(ItemDrop drop, Sprite icon) { if (drop?.m_itemData?.m_shared != null) { Sprite[] array = (Sprite[])(object)new Sprite[Math.Max(1, drop.m_itemData.m_shared.m_variants)]; for (int i = 0; i < array.Length; i++) { array[i] = icon; } drop.m_itemData.m_shared.m_icons = array; drop.Save(); } } private static void LogOnce(string message) { if (!_loggedFailure) { _loggedFailure = true; AdventureBackpacks.Log.Warning("[SilverBackpack] Inventory icon fix failed: " + message); } } } internal interface IBackpackItem : IAssetItem { } internal abstract class BackpackItem : AssetItem, IBackpackItem, IAssetItem { private static ConfigSyncBase _config; private static ILogIt _logger; private string _configSection; private string _englishSection; private string _localizedCategory; public System.Timers.Timer InceptionTimer; public System.Timers.Timer YardSaleTimer; private int _inceptionCounter; internal Dictionary> BackpackSize; internal ConfigEntry WeightMultiplier; internal ConfigEntry CarryBonus; internal ConfigEntry SpeedMod; internal ConfigEntry EnableFreezing; internal ConfigEntry ShowBackpackStatusEffect; internal ConfigEntry CustomStatusEffectName; internal ConfigEntry BackpackBiome; public int InceptionCounter { get { return _inceptionCounter; } set { _inceptionCounter = value; if (value > 0) { InceptionTimer.Stop(); InceptionTimer.Start(); } } } internal ConfigSyncBase Config => _config; internal ILogIt Log => _logger; protected BackpackItem(ABAPI.BackpackDefinition definition, GameObject goItem) : base(goItem, definition.ItemName) { _configSection = (string.IsNullOrEmpty(definition.ConfigSection) ? ("Backpack: " + definition.ItemName) : definition.ConfigSection); SetupLocalization(); SetupBackpackDef(); } protected BackpackItem(ABAPI.BackpackDefinition definition) : base(definition.AssetBundle, definition.PrefabName, definition.ItemName) { _configSection = (string.IsNullOrEmpty(definition.ConfigSection) ? ("Backpack: " + definition.ItemName) : definition.ConfigSection); SetupLocalization(); SetupBackpackDef(); } protected BackpackItem(string assetName, string prefabName, string itemName, string configSection = "", bool externalLocalize = false) : base(assetName, prefabName, itemName) { _configSection = (string.IsNullOrEmpty(configSection) ? ("Backpack: " + itemName) : configSection); _englishSection = Localizer.GetTranslation("English", _configSection); if (externalLocalize) { _localizedCategory = Localization.m_instance.Localize(_configSection); } else { _localizedCategory = Localization.instance.Localize(_configSection); } SetupBackpackDef(); } internal void SetupLocalization() { _englishSection = Localizer.GetTranslation("English", _configSection); _localizedCategory = Localization.m_instance.Localize(_configSection); if (_localizedCategory.Equals(_configSection)) { _localizedCategory = Localization.instance.Localize(_configSection); } } private void SetupBackpackDef() { base.Item.SectionName = _configSection; BackpackSize = new Dictionary>(); InceptionTimer = new System.Timers.Timer(10000.0); InceptionTimer.AutoReset = false; InceptionTimer.Enabled = false; InceptionTimer.Elapsed += InceptionCounterReset; } private void InceptionCounterReset(object source, ElapsedEventArgs e) { InceptionCounter = 0; Log.Message("Odin walks away."); } internal static void SetConfig(ConfigSyncBase configSync) { _config = configSync; } internal static void SetLogger(ILogIt logger) { _logger = logger; } internal abstract void RegisterConfigSettings(); internal virtual Vector2i GetInventorySize(int quality) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) quality = Mathf.Clamp(quality, 1, 4); return new Vector2i(Mathf.Clamp((int)BackpackSize[quality].Value.x, 1, 256), Mathf.Clamp((int)BackpackSize[quality].Value.y, 1, 256)); } internal abstract void UpdateStatusEffects(int quality, CustomSE statusEffects, List modifierList, ItemData itemData); internal virtual void RegisterBackpackSize(int quality = 1, int x = 6, int y = 3) { //IL_001c: 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_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown ConfigEntry configEntry = null; ConfigSyncBase.SyncedConfig(_englishSection, $"Backpack Size - Level {quality}", new Vector2((float)x, (float)y), new ConfigDescription("Backpack size (width, height).\nMax width is 8 unless you want to break things.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Category = _localizedCategory, Order = 3 } }), ref configEntry); BackpackSize.Add(quality, configEntry); BackpackSize[quality].SettingChanged += Backpacks.UpdateItemDataConfigValues; } internal virtual void RegisterWeightMultiplier(float defaultValue = 0.5f) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_0046: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown ConfigSyncBase.SyncedConfig(_englishSection, "Weight Multiplier", defaultValue, new ConfigDescription("The weight of items stored in the backpack gets multiplied by this value. Setting to 100% or 1.0 disables weight reduction.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), new object[1] { (object)new ConfigurationManagerAttributes { Category = _localizedCategory, Order = 4 } }), ref WeightMultiplier); WeightMultiplier.SettingChanged += Backpacks.UpdateItemDataConfigValues; } internal virtual void RegisterBackpackBiome(BackpackBiomes defaultValue = BackpackBiomes.None) { //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_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown ConfigSyncBase.SyncedConfig(_englishSection, "Backpack Biome", defaultValue, new ConfigDescription("The Biome this bag will draw it's effects from.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Category = _localizedCategory, Order = 5 } }), ref BackpackBiome); BackpackBiome.SettingChanged += Backpacks.UpdateItemDataConfigValues; } internal virtual void RegisterCarryBonus(int defaultValue = 0) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_0053: Expected O, but got Unknown ConfigSyncBase.SyncedConfig(_englishSection, "Carry Bonus", defaultValue, new ConfigDescription("Increases your carry capacity by this much (multiplied by item level) while wearing the backpack.", (AcceptableValueBase)(object)new AcceptableValueRange(0, 300), new object[1] { (object)new ConfigurationManagerAttributes { Category = _localizedCategory, Order = 6 } }), ref CarryBonus); CarryBonus.SettingChanged += Backpacks.UpdateItemDataConfigValues; } internal virtual void RegisterStatusEffectInfo(bool defaultShowStatus = true, string defaultEffectName = "") { //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_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown //IL_0089: 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_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected O, but got Unknown ConfigSyncBase.SyncedConfig(_englishSection, "Show Status Effect", defaultShowStatus, new ConfigDescription("Toggles the visibility of the Backpack Status Effect", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Category = _localizedCategory, Order = 1 } }), ref ShowBackpackStatusEffect); ShowBackpackStatusEffect.SettingChanged += Backpacks.UpdateItemDataConfigValues; ConfigSyncBase.SyncedConfig(_englishSection, "Custom Effect Name", defaultEffectName, new ConfigDescription("Set your own effect name. Leave Empty to use Default Effect name", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Category = _localizedCategory, Order = 2 } }), ref CustomStatusEffectName); CustomStatusEffectName.SettingChanged += Backpacks.UpdateItemDataConfigValues; } internal virtual void RegisterSpeedMod(float defaultValue = -0.15f) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_0046: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown ConfigSyncBase.SyncedConfig(_englishSection, "Speed Modifier", defaultValue, new ConfigDescription("Wearing the backpack slows you down by this much.", (AcceptableValueBase)(object)new AcceptableValueRange(-1f, -0f), new object[1] { (object)new ConfigurationManagerAttributes { Category = _localizedCategory, Order = 7 } }), ref SpeedMod); SpeedMod.SettingChanged += Backpacks.UpdateItemDataConfigValues; } internal virtual void RegisterEnableFreezing(bool defaultValue = true) { //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_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown ConfigSyncBase.SyncedConfig(_englishSection, "Prevent freezing/cold?", defaultValue, new ConfigDescription("Wearing the backpack protects you against freezing/cold, just like capes.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Category = _localizedCategory, Order = 8 } }), ref EnableFreezing); EnableFreezing.SettingChanged += Backpacks.UpdateItemDataConfigValues; } } } namespace AdventureBackpacks.Assets.Items.BackpackItems { internal class BackpackBlackForest : BackpackItem { public BackpackBlackForest(string assetName, string prefabName, string itemName) : base(assetName, prefabName, itemName) { RegisterConfigSettings(); base.Item.Configurable = Configurability.Recipe | Configurability.Drop; AssignCraftingTable(ItemManager.CraftingTable.Forge, 1); base.Item.MaximumRequiredStationLevel = 3; AddRecipeIngredient("CapeTrollHide", 1); AddRecipeIngredient("Copper", 5); AddUpgradeIngredient("TrollHide", 3); AddUpgradeIngredient("Bronze", 3); base.Item.DropsFrom.Add("Greydwarf", 0.002f); base.Item.DropsFrom.Add("Greydwarf_Elite", 0.004f); base.Item.DropsFrom.Add("Greydwarf_Shaman", 0.004f); base.Item.DropsFrom.Add("Troll", 0.01f); base.Item.DropsFrom.Add("Bjorn", 0.04f); base.Item.DropsFrom.Add("gd_king", 0.08f); } internal sealed override void RegisterConfigSettings() { RegisterBackpackBiome(BackpackBiomes.BlackForest); RegisterBackpackSize(1, 3, 2); RegisterBackpackSize(2, 4, 2); RegisterBackpackSize(3, 5, 2); RegisterBackpackSize(4, 6, 2); RegisterStatusEffectInfo(); RegisterWeightMultiplier(); RegisterCarryBonus(10); RegisterSpeedMod(); if ((BackpackBiome.Value & BackpackBiomes.BlackForest) != BackpackBiomes.None) { EffectsFactory.EffectList[BackpackEffect.ColdResistance].RegisterEffectBiomeQuality(BackpackBiomes.BlackForest, 1); EffectsFactory.EffectList[BackpackEffect.TrollArmor].RegisterEffectBiomeQuality(BackpackBiomes.BlackForest, 2); } } internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List modifierList, ItemData itemData) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) itemData.m_shared.m_movementModifier = SpeedMod.Value / (float)quality; ((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = CarryBonus.Value * quality; } } internal class BackpackMeadows : BackpackItem { public BackpackMeadows(string assetName, string prefabName, string itemName) : base(assetName, prefabName, itemName) { RegisterConfigSettings(); base.Item.Configurable = Configurability.Recipe | Configurability.Drop; AssignCraftingTable(ItemManager.CraftingTable.Workbench, 2); base.Item.MaximumRequiredStationLevel = 3; AddRecipeIngredient("CapeDeerHide", 1); AddRecipeIngredient("DeerHide", 8); AddRecipeIngredient("BoneFragments", 2); AddUpgradeIngredient("LeatherScraps", 5); AddUpgradeIngredient("DeerHide", 3); base.Item.DropsFrom.Add("Greyling", 0.002f); base.Item.DropsFrom.Add("Eikthyr", 0.04f); } internal sealed override void RegisterConfigSettings() { RegisterBackpackBiome(BackpackBiomes.Meadows); RegisterBackpackSize(1, 3, 1); RegisterBackpackSize(2, 4, 1); RegisterBackpackSize(3, 5, 1); RegisterBackpackSize(4, 6, 1); RegisterStatusEffectInfo(); RegisterWeightMultiplier(); RegisterCarryBonus(5); RegisterSpeedMod(); if ((BackpackBiome.Value & BackpackBiomes.Meadows) != BackpackBiomes.None) { EffectsFactory.EffectList[BackpackEffect.ColdResistance].RegisterEffectBiomeQuality(BackpackBiomes.Meadows, 3); } } internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List modifierList, ItemData itemData) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) itemData.m_shared.m_movementModifier = SpeedMod.Value / (float)quality; ((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = CarryBonus.Value * quality; } } internal class BackpackMistlands : BackpackItem { public BackpackMistlands(string assetName, string prefabName, string itemName) : base(assetName, prefabName, itemName) { RegisterConfigSettings(); base.Item.Configurable = Configurability.Recipe | Configurability.Drop; AssignCraftingTable(ItemManager.CraftingTable.BlackForge, 1); base.Item.MaximumRequiredStationLevel = 2; AddRecipeIngredient("CapeFeather", 1); AddRecipeIngredient("ScaleHide", 5); AddRecipeIngredient("Eitr", 10); AddUpgradeIngredient("ScaleHide", 4); AddUpgradeIngredient("Eitr", 2); AddUpgradeIngredient("Softtissue", 5); base.Item.DropsFrom.Add("Dverger", 0.002f); base.Item.DropsFrom.Add("DvergerMage", 0.002f); base.Item.DropsFrom.Add("DvergerMageFire", 0.002f); base.Item.DropsFrom.Add("DvergerMageIce", 0.002f); base.Item.DropsFrom.Add("DvergerMageSupport", 0.002f); base.Item.DropsFrom.Add("SeekerQueen", 0.08f); } internal sealed override void RegisterConfigSettings() { RegisterBackpackBiome(BackpackBiomes.Mistlands); RegisterBackpackSize(1, 8, 2); RegisterBackpackSize(2, 5, 4); RegisterBackpackSize(3, 6, 4); RegisterBackpackSize(4, 7, 4); RegisterStatusEffectInfo(); RegisterWeightMultiplier(); RegisterCarryBonus(30); RegisterSpeedMod(); if ((BackpackBiome.Value & BackpackBiomes.Mistlands) != BackpackBiomes.None) { EffectsFactory.EffectList[BackpackEffect.FeatherFall].RegisterEffectBiomeQuality(BackpackBiomes.Mistlands, 3); EffectsFactory.EffectList[BackpackEffect.Demister].RegisterEffectBiomeQuality(BackpackBiomes.Mistlands, 4); EffectsFactory.EffectList[BackpackEffect.FrostResistance].RegisterEffectBiomeQuality(BackpackBiomes.Mistlands, 2); EffectsFactory.EffectList[BackpackEffect.ColdResistance].RegisterEffectBiomeQuality(BackpackBiomes.Mistlands, 1); } } internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List modifierList, ItemData itemData) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) itemData.m_shared.m_movementModifier = SpeedMod.Value / (float)quality; ((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = CarryBonus.Value * quality; } } internal class BackpackMountains : BackpackItem { public BackpackMountains(string assetName, string prefabName, string itemName) : base(assetName, prefabName, itemName) { RegisterConfigSettings(); base.Item.Configurable = Configurability.Recipe | Configurability.Drop; AssignCraftingTable(ItemManager.CraftingTable.Forge, 3); base.Item.MaximumRequiredStationLevel = 7; AddRecipeIngredient("CapeWolf", 1); AddRecipeIngredient("WolfHairBundle", 10); AddUpgradeIngredient("WolfPelt", 5); AddUpgradeIngredient("Silver", 5); base.Item.DropsFrom.Add("Fenring_Cultist", 0.002f); base.Item.DropsFrom.Add("Ulv", 0.001f); base.Item.DropsFrom.Add("Fenring", 0.008f); base.Item.DropsFrom.Add("Dragon", 0.04f); } internal sealed override void RegisterConfigSettings() { RegisterBackpackBiome(BackpackBiomes.Mountains); RegisterBackpackSize(1, 3); RegisterBackpackSize(2, 4); RegisterBackpackSize(3, 5); RegisterBackpackSize(4); RegisterStatusEffectInfo(); RegisterWeightMultiplier(); RegisterCarryBonus(20); RegisterSpeedMod(); if ((BackpackBiome.Value & BackpackBiomes.Mountains) != BackpackBiomes.None) { EffectsFactory.EffectList[BackpackEffect.FeatherFall].RegisterEffectBiomeQuality(BackpackBiomes.Mountains, 4); EffectsFactory.EffectList[BackpackEffect.FrostResistance].RegisterEffectBiomeQuality(BackpackBiomes.Mountains, 1); EffectsFactory.EffectList[BackpackEffect.ColdResistance].RegisterEffectBiomeQuality(BackpackBiomes.Mountains, 1); } } internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List modifierList, ItemData itemData) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) itemData.m_shared.m_movementModifier = SpeedMod.Value / (float)quality; ((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = CarryBonus.Value * quality; } } internal class BackpackPlains : BackpackItem { public BackpackPlains(string assetName, string prefabName, string itemName) : base(assetName, prefabName, itemName) { RegisterConfigSettings(); base.Item.Configurable = Configurability.Recipe | Configurability.Drop; AssignCraftingTable(ItemManager.CraftingTable.Forge, 3); base.Item.MaximumRequiredStationLevel = 7; AddRecipeIngredient("CapeLox", 1); AddRecipeIngredient("Tar", 5); AddRecipeIngredient("BlackMetal", 5); AddUpgradeIngredient("LoxPelt", 2); AddUpgradeIngredient("BlackMetal", 5); base.Item.DropsFrom.Add("Goblin", 0.002f); base.Item.DropsFrom.Add("GoblinArcher", 0.002f); base.Item.DropsFrom.Add("GoblinBrute", 0.002f); base.Item.DropsFrom.Add("GoblinShaman", 0.002f); base.Item.DropsFrom.Add("Unbjorn", 0.02f); base.Item.DropsFrom.Add("GoblinKing", 0.04f); } internal sealed override void RegisterConfigSettings() { RegisterBackpackBiome(BackpackBiomes.Plains); RegisterBackpackSize(1, 3, 4); RegisterBackpackSize(2, 4, 4); RegisterBackpackSize(3, 5, 4); RegisterBackpackSize(4, 6, 4); RegisterStatusEffectInfo(); RegisterWeightMultiplier(); RegisterCarryBonus(25); RegisterSpeedMod(); if ((BackpackBiome.Value & BackpackBiomes.Plains) != BackpackBiomes.None) { EffectsFactory.EffectList[BackpackEffect.FrostResistance].RegisterEffectBiomeQuality(BackpackBiomes.Plains, 3); EffectsFactory.EffectList[BackpackEffect.ColdResistance].RegisterEffectBiomeQuality(BackpackBiomes.Plains, 1); } } internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List modifierList, ItemData itemData) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) itemData.m_shared.m_movementModifier = SpeedMod.Value / (float)quality; ((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = CarryBonus.Value * quality; } } internal class BackpackSwamp : BackpackItem { public BackpackSwamp(string assetName, string prefabName, string itemName) : base(assetName, prefabName, itemName) { RegisterConfigSettings(); base.Item.Configurable = Configurability.Recipe | Configurability.Drop; AssignCraftingTable(ItemManager.CraftingTable.Workbench, 2); base.Item.MaximumRequiredStationLevel = 5; AddRecipeIngredient("Bloodbag", 10); AddRecipeIngredient("Root", 4); AddRecipeIngredient("Guck", 4); AddUpgradeIngredient("Bloodbag", 2); AddUpgradeIngredient("Iron", 5); base.Item.DropsFrom.Add("Draugr", 0.002f); base.Item.DropsFrom.Add("Draugr_Ranged", 0.004f); base.Item.DropsFrom.Add("Draugr_Elite", 0.004f); base.Item.DropsFrom.Add("Abomination", 0.008f); base.Item.DropsFrom.Add("Bonemass", 0.04f); } internal sealed override void RegisterConfigSettings() { RegisterBackpackBiome(BackpackBiomes.Swamp); RegisterBackpackSize(1, 2); RegisterBackpackSize(2, 3); RegisterBackpackSize(3, 4); RegisterBackpackSize(4, 5); RegisterStatusEffectInfo(); RegisterWeightMultiplier(); RegisterCarryBonus(15); RegisterSpeedMod(); if ((BackpackBiome.Value & BackpackBiomes.Swamp) != BackpackBiomes.None) { EffectsFactory.EffectList[BackpackEffect.WaterResistance].RegisterEffectBiomeQuality(BackpackBiomes.Swamp, 2); EffectsFactory.EffectList[BackpackEffect.ColdResistance].RegisterEffectBiomeQuality(BackpackBiomes.Swamp, 1); } } internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List modifierList, ItemData itemData) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) itemData.m_shared.m_movementModifier = SpeedMod.Value / (float)quality; ((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = CarryBonus.Value * quality; } } internal class LegacyIronBackpack : BackpackItem { public LegacyIronBackpack(string assetName, string prefabName, string itemName) : base(assetName, prefabName, itemName) { RegisterConfigSettings(); } internal sealed override void RegisterConfigSettings() { RegisterBackpackBiome(); RegisterBackpackSize(); RegisterStatusEffectInfo(); RegisterWeightMultiplier(); RegisterCarryBonus(25); RegisterSpeedMod(); RegisterEnableFreezing(defaultValue: false); } internal override Vector2i GetInventorySize(int quality) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return base.GetInventorySize(1); } internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List modifierList, ItemData itemData) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) itemData.m_shared.m_movementModifier = SpeedMod.Value / (float)quality; if (EnableFreezing.Value) { modifierList.Add(FrostResistance.EffectMod); } ((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = CarryBonus.Value * quality; } } internal class LegacySilverBackpack : BackpackItem { public LegacySilverBackpack(string assetName, string prefabName, string itemName) : base(assetName, prefabName, itemName) { RegisterConfigSettings(); } internal sealed override void RegisterConfigSettings() { RegisterBackpackBiome(); RegisterBackpackSize(); RegisterStatusEffectInfo(); RegisterWeightMultiplier(); RegisterCarryBonus(45); RegisterSpeedMod(); RegisterEnableFreezing(); } internal override Vector2i GetInventorySize(int quality) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return base.GetInventorySize(1); } internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List modifierList, ItemData itemData) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) itemData.m_shared.m_movementModifier = SpeedMod.Value / (float)quality; if (EnableFreezing.Value) { modifierList.Add(FrostResistance.EffectMod); } ((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = CarryBonus.Value * quality; } } internal class ExternalBackpack : BackpackItem { private readonly ABAPI.BackpackDefinition _backpackDefinition; private static EffectsBase _setEffectsBase; public ExternalBackpack(ABAPI.BackpackDefinition backpackDefinition, GameObject goItem) : base(backpackDefinition, goItem) { _backpackDefinition = backpackDefinition; SetupBackpack(); } public ExternalBackpack(ABAPI.BackpackDefinition backpackDefinition) : base(backpackDefinition) { _backpackDefinition = backpackDefinition; SetupBackpack(); } public void SetupBackpack() { RegisterConfigSettings(); base.Item.Configurable = Configurability.Recipe | Configurability.Drop; AssignCraftingTable(_backpackDefinition.CraftingTable, _backpackDefinition.StationLevel); base.Item.MaximumRequiredStationLevel = _backpackDefinition.MaxRequiredStationLevel; foreach (ABAPI.RecipeIngredient recipeIngredient in _backpackDefinition.RecipeIngredients) { AddRecipeIngredient(recipeIngredient.ItemPrefabName, recipeIngredient.Quantity); } foreach (ABAPI.RecipeIngredient upgradeIngredient in _backpackDefinition.UpgradeIngredients) { AddUpgradeIngredient(upgradeIngredient.ItemPrefabName, upgradeIngredient.Quantity); } foreach (ABAPI.DropTarget item in _backpackDefinition.DropsFrom) { base.Item.DropsFrom.Add(item.Creature, item.Chance, item.Min, item.Max); } AdventureBackpacks.Waiter.StatusChanged += delegate { RegisterEffects(); }; } private void RegisterEffects() { foreach (KeyValuePair> item in _backpackDefinition.EffectsToApply) { if ((BackpackBiome.Value & item.Key) == 0) { continue; } foreach (EffectsBase allEffect in EffectsFactory.AllEffects) { if ((Object)(object)allEffect.GetStatusEffect() == (Object)null) { allEffect.LoadStatusEffect(); } if (allEffect.GetStatusEffect().m_name.Equals(item.Value.Key.m_name)) { if ((Object)(object)_backpackDefinition.ItemSetStatusEffect != (Object)null && _backpackDefinition.ItemSetStatusEffect.m_name.Equals(allEffect.GetStatusEffect().m_name)) { _setEffectsBase = allEffect; } allEffect.RegisterEffectBiomeQuality(item.Key, item.Value.Value); } } } } internal sealed override void RegisterConfigSettings() { //IL_0036: 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) RegisterBackpackBiome(_backpackDefinition.BackpackBiome); foreach (KeyValuePair item in _backpackDefinition.BackpackSizeByQuality) { RegisterBackpackSize(item.Key, (int)item.Value.x, (int)item.Value.y); } RegisterStatusEffectInfo(); RegisterWeightMultiplier(_backpackDefinition.WeightMultiplier); RegisterCarryBonus(_backpackDefinition.CarryBonus); RegisterSpeedMod(_backpackDefinition.SpeedMod); RegisterShaderSwap(); } internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List modifierList, ItemData itemData) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) itemData.m_shared.m_movementModifier = SpeedMod.Value / (float)quality; if (_setEffectsBase != null) { if (_setEffectsBase.HasActiveStatusEffect(itemData, out var statusEffect)) { itemData.m_shared.m_setStatusEffect = statusEffect; } else { itemData.m_shared.m_setStatusEffect = null; } } ((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = CarryBonus.Value * quality; } } } namespace AdventureBackpacks.Assets.Factories { internal abstract class AssetFactory : FactoryBase { internal AssetFactory(ILogIt logger, ConfigSyncBase configs) : base(logger, configs) { } internal abstract void CreateAssets(); } internal class BackpackFactory : AssetFactory { private static HashSet _backpackItems = new HashSet(); private static bool _initialized; private static List _externalBackpacks = new List(); internal static IEnumerable BackpackItems => _backpackItems; internal BackpackFactory(ILogIt logger, ConfigSyncBase configSync) : base(logger, configSync) { if (!_initialized) { BackpackItem.SetConfig(configSync); BackpackItem.SetLogger(logger); _initialized = true; } } public static void RegisterExternalBackpack(ABAPI.BackpackDefinition backpackDefinition) { _externalBackpacks.Add(backpackDefinition); } internal override void CreateAssets() { _backpackItems.Add(new BackpackMeadows("backpack_meadows", "BackpackMeadows", "$vapok_mod_item_backpack_meadows")); _backpackItems.Add(new BackpackBlackForest("backpack_black_forest", "BackpackBlackForest", "$vapok_mod_item_backpack_blackforest")); _backpackItems.Add(new BackpackSwamp("backpack_swamp", "BackpackSwamp", "$vapok_mod_item_backpack_swamp")); _backpackItems.Add(new BackpackMountains("backpack_mountains", "BackpackMountains", "$vapok_mod_item_backpack_mountains")); _backpackItems.Add(new BackpackPlains("backpack_plains", "BackpackPlains", "$vapok_mod_item_backpack_plains")); _backpackItems.Add(new BackpackMistlands("backpack_mistlands", "BackpackMistlands", "$vapok_mod_item_backpack_mistlands")); _backpackItems.Add(new LegacyIronBackpack("vapokbackpacks", "CapeIronBackpack", "$vapok_mod_item_rugged_backpack")); _backpackItems.Add(new LegacySilverBackpack("vapokbackpacks", "CapeSilverBackpack", "$vapok_mod_item_arctic_backpack")); foreach (ABAPI.BackpackDefinition backpackDefinition in _externalBackpacks) { if (_backpackItems.Any((BackpackItem x) => x.ItemName.Equals(backpackDefinition.ItemName))) { break; } ExternalBackpack item = (((Object)(object)backpackDefinition.BackPackGo != (Object)null) ? new ExternalBackpack(backpackDefinition, backpackDefinition.BackPackGo) : new ExternalBackpack(backpackDefinition)); _backpackItems.Add(item); } } internal static List BackpackTypes() { return BackpackItems.Select((BackpackItem x) => x.ItemName).ToList(); } } public enum BackpackEffect { FeatherFall, ColdResistance, Demister, WaterResistance, FrostResistance, TrollArmor, NecromancyArmor, ExternalEffect } public class EffectsFactory : FactoryBase { private static Dictionary _effectList = new Dictionary(); private static HashSet _externalEffects = new HashSet(); private static HashSet _allEffects = new HashSet(); private static readonly List PerFrameToggleEffects = new List(); private static bool _registerEffectsCompleted; public static EffectsFactory Instance; public static HashSet AllEffects => _allEffects; public static Dictionary EffectList => _effectList; public EffectsFactory(ILogIt logger, ConfigSyncBase configs) : base(logger, configs) { Instance = this; } public static HashSet GetRegisteredEffects() { HashSet hashSet = new HashSet(); foreach (KeyValuePair effect in _effectList) { hashSet.Add(effect.Value.GetStatusEffect()); } foreach (EffectsBase externalEffect in _externalEffects) { hashSet.Add(externalEffect.GetStatusEffect()); } return hashSet; } public static void RegisterExternalEffect(ABAPI.EffectDefinition effectDefinition) { if (_externalEffects.Any((EffectsBase x) => x.EffectName.Equals(effectDefinition.EffectName))) { return; } ExternalEffect externalEffect = new ExternalEffect(effectDefinition); _externalEffects.Add(externalEffect); if (_registerEffectsCompleted) { externalEffect.RegisterEffectConfiguration(); _allEffects.Add(externalEffect); if (externalEffect.RequiresPerFrameToggle) { PerFrameToggleEffects.Add(externalEffect); } } } public void RegisterEffects() { _effectList.Add(BackpackEffect.FeatherFall, new FeatherFall("Feather Fall", "When activated allows you to slow fall gracefully and without damage from high elevations.")); _effectList.Add(BackpackEffect.ColdResistance, new ColdResistance("Cold Immunity", "When activated keeps you from feeling cold. Does not prevent freezing.")); _effectList.Add(BackpackEffect.Demister, new Demister("Demister", "When activated provides you with the Wisplight Effect, which clears mist from a small area around you while in the Mistlands.")); _effectList.Add(BackpackEffect.WaterResistance, new Waterproof("Water Resistance", "When activated allows you to stay dry from the rain. Will still get wet if swimming.")); _effectList.Add(BackpackEffect.FrostResistance, new FrostResistance("Frost Resistance", "When activated allows you to stay warm in freezing conditions, negating the freezing debuff.")); _effectList.Add(BackpackEffect.TrollArmor, new TrollArmor("Troll Armor Set", "When activated the backpack acts as the Shoulder Set piece of the Troll Armor Set allowing the set to complete for the Sneak Effect")); foreach (BackpackEffect value in Enum.GetValues(typeof(BackpackEffect))) { switch (value) { case BackpackEffect.ExternalEffect: foreach (EffectsBase externalEffect in _externalEffects) { _allEffects.Add(externalEffect); externalEffect.RegisterEffectConfiguration(); } break; case BackpackEffect.FeatherFall: case BackpackEffect.ColdResistance: case BackpackEffect.Demister: case BackpackEffect.WaterResistance: case BackpackEffect.FrostResistance: case BackpackEffect.TrollArmor: case BackpackEffect.NecromancyArmor: if (EffectList.ContainsKey(value)) { _allEffects.Add(EffectList[value]); EffectList[value].RegisterEffectConfiguration(); } break; } } _registerEffectsCompleted = true; RebuildPerFrameToggleList(); } private static void RebuildPerFrameToggleList() { PerFrameToggleEffects.Clear(); foreach (EffectsBase allEffect in _allEffects) { if (allEffect.RequiresPerFrameToggle) { PerFrameToggleEffects.Add(allEffect); } } } public void ToggleEffects() { for (int i = 0; i < PerFrameToggleEffects.Count; i++) { PerFrameToggleEffects[i].ToggleEffect(); } } } public abstract class FactoryBase { private ILogIt _logger; private ConfigSyncBase _config; internal ILogIt Log => _logger; internal ConfigSyncBase Config => _config; internal FactoryBase(ILogIt logger, ConfigSyncBase configs) { _logger = logger; _config = configs; } } } namespace AdventureBackpacks.Assets.Effects { public class ColdResistance : EffectsBase { private StatusEffect _externalStatusEffect; public ColdResistance(string effectName, string effectDesc) : base(effectName, effectDesc) { } private void LoadExternalStatusEffect() { if ((Object)(object)_externalStatusEffect == (Object)null) { StatusEffect statusEffect = ObjectDB.instance.GetStatusEffect("Cold".GetHashCode()); CustomSE customSE = new CustomSE(Enums.StatusEffects.Stats, "SE_vapok_ab_cold_immunity"); customSE.Effect.m_name = "$vapok_mod_se_cold_immunity"; customSE.Effect.m_icon = statusEffect.m_icon; _externalStatusEffect = customSE.Effect; SetStatusEffect(_externalStatusEffect); } } public override void LoadStatusEffect() { LoadExternalStatusEffect(); } public override bool HasActiveStatusEffect(Humanoid human, out StatusEffect statusEffect) { LoadExternalStatusEffect(); SetStatusEffect(_externalStatusEffect); return base.HasActiveStatusEffect(human, out statusEffect); } public override bool HasActiveStatusEffect(ItemData item, out StatusEffect statusEffect) { LoadExternalStatusEffect(); SetStatusEffect(_externalStatusEffect); return base.HasActiveStatusEffect(item, out statusEffect); } } public class Demister : EffectsBase { private static Biome _previouseBiome; private static ConfigEntry WisplightKeyToggle; private static ConfigEntry WisplightBiomeLogic; public override bool RequiresPerFrameToggle => true; public Demister(string effectName, string effectDesc) : base(effectName, effectDesc) { } public override void ToggleEffect() { //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Invalid comparison between Unknown and I4 //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)Player.m_localPlayer) || !Object.op_Implicit((Object)(object)ZNetScene.instance)) { return; } Player localPlayer = Player.m_localPlayer; ref Biome currentBiome = ref localPlayer.m_currentBiome; object obj = (object)(Biome)512; if ((((object)Unsafe.As(ref currentBiome)/*cast due to .constrained prefix*/).Equals(obj) && WisplightBiomeLogic.Value) || !WisplightBiomeLogic.Value) { if (Player.m_localPlayer.IsBackpackEquipped()) { if ((int)_previouseBiome != 512 && WisplightBiomeLogic.Value) { SetEffectSwitch(switchValue: true); ((Humanoid)localPlayer).UpdateEquipmentStatusEffects(); } KeyboardShortcut value = WisplightKeyToggle.Value; if (ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey, true) && IsEffectActive((Humanoid)(object)Player.m_localPlayer)) { ToggleEffectSwitch(); ((Humanoid)localPlayer).UpdateEquipmentStatusEffects(); } } } else if (CurrectSwitchSetting() && WisplightBiomeLogic.Value && IsEffectActive((Humanoid)(object)Player.m_localPlayer)) { SetEffectSwitch(switchValue: false); ((Humanoid)localPlayer).UpdateEquipmentStatusEffects(); } _previouseBiome = localPlayer.GetCurrentBiome(); } public override void LoadStatusEffect() { if (CurrectSwitchSetting()) { SetStatusEffect("Demister"); } } public override bool HasActiveStatusEffect(Humanoid human, out StatusEffect statusEffect) { if (!CurrectSwitchSetting()) { statusEffect = null; return false; } SetStatusEffect("Demister"); return base.HasActiveStatusEffect(human, out statusEffect); } public override void RegisterEffectConfiguration() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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_003c: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown base.RegisterEffectConfiguration(); ConfigSyncBase.UnsyncedConfig("Wisplight Client Settings", "Wisplight Effect Key Toggle", new KeyboardShortcut((KeyCode)108, Array.Empty()), new ConfigDescription("Hotkey to turn Wisplight on and off", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Order = 1 } }), ref WisplightKeyToggle); ConfigSyncBase.UnsyncedConfig("Wisplight Client Settings", "Wisplight Biome Logic", value: true, new ConfigDescription("If enabled, the Wisplight will automatically turn on when entering Mistlands, and turn off when exiting.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Order = 2 } }), ref WisplightBiomeLogic); } } public abstract class EffectsBase { public ConfigEntry EnabledEffect; public Dictionary> BiomeQualityLevels; private string _configSection; private string _effectName; private string _description; private StatusEffect _statusEffect; private bool _isSetItemStatusEffect; private bool _effectSwitch = true; public string EffectName => _effectName; public virtual bool RequiresPerFrameToggle => false; public EffectsBase(string effectName, string effectDesc, bool IsItemSetStatusEffect = false) { _effectName = effectName; _description = (string.IsNullOrEmpty(effectDesc) ? "Enables the effect." : effectDesc); _configSection = "Effect: " + effectName; _isSetItemStatusEffect = IsItemSetStatusEffect; AdventureBackpacks.Waiter.StatusChanged += delegate { LoadStatusEffect(); }; } public abstract void LoadStatusEffect(); public virtual StatusEffect GetStatusEffect() { return _statusEffect; } public virtual void SetStatusEffect(StatusEffect statusEffect) { _statusEffect = statusEffect; } public virtual void SetStatusEffect(string effectName) { _statusEffect = (((Object)(object)_statusEffect == (Object)null) ? ObjectDB.instance.GetStatusEffect(effectName.GetHashCode()) : _statusEffect); } public virtual bool HasActiveStatusEffect(Humanoid human, out StatusEffect statusEffect) { statusEffect = _statusEffect; if ((Object)(object)statusEffect != (Object)null && IsEffectActive(human)) { return !_isSetItemStatusEffect; } return false; } public virtual bool HasActiveStatusEffect(ItemData item, out StatusEffect statusEffect) { statusEffect = _statusEffect; if ((Object)(object)statusEffect != (Object)null) { return IsEffectActive(item); } return false; } public virtual bool IsEffectActive(Humanoid human) { Player val = (Player)(object)((human is Player) ? human : null); if (val != null) { BackpackComponent equippedBackpack = val.GetEquippedBackpack(); if (equippedBackpack == null || !EnabledEffect.Value) { return false; } ItemData item = equippedBackpack.Item; item.TryGetBackpackItem(out var backpack); BackpackBiomes value = backpack.BackpackBiome.Value; int num = 0; foreach (BackpackBiomes key in BiomeQualityLevels.Keys) { if ((value & key) != BackpackBiomes.None) { num = ((BiomeQualityLevels[key].Value > num) ? BiomeQualityLevels[key].Value : num); } } if (num == 0) { return false; } return item.m_quality >= num; } return false; } public virtual void ToggleEffect() { } public virtual void ToggleEffectSwitch() { _effectSwitch = !_effectSwitch; } public virtual void SetEffectSwitch(bool switchValue) { _effectSwitch = switchValue; } public virtual bool CurrectSwitchSetting() { return _effectSwitch; } public virtual bool IsEffectActive(ItemData itemData) { if (!EnabledEffect.Value) { return false; } if (itemData != null && itemData.TryGetBackpackItem(out var backpack)) { BackpackBiomes value = backpack.BackpackBiome.Value; int num = 0; foreach (BackpackBiomes key in BiomeQualityLevels.Keys) { if ((value & key) != BackpackBiomes.None) { num = ((BiomeQualityLevels[key].Value > num) ? BiomeQualityLevels[key].Value : num); } } if (num == 0) { return false; } return itemData.m_quality >= num; } return false; } public virtual void RegisterEffectConfiguration() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown BiomeQualityLevels = new Dictionary>(); ConfigSyncBase.SyncedConfig(_configSection, "Effect Enabled", value: true, new ConfigDescription(_description, (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { Order = 1 } }), ref EnabledEffect); ConfigRegistry.Waiter.StatusChanged += delegate { AdditionalConfiguration(_configSection); }; } public virtual void AdditionalConfiguration(string configSection) { FillBiomeSettings(); } private void FillBiomeSettings() { foreach (BackpackBiomes value in Enum.GetValues(typeof(BackpackBiomes))) { RegisterEffectBiomeQuality(value); } } public void RegisterEffectBiomeQuality(BackpackBiomes biome, int defaultQuality = 0) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Expected O, but got Unknown //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown if (biome == BackpackBiomes.None) { return; } foreach (BackpackBiomes value in Enum.GetValues(typeof(BackpackBiomes))) { if ((biome & value) != BackpackBiomes.None) { ConfigEntry configEntry = null; ConfigSyncBase.SyncedConfig(_configSection, "Effective Quality Level: " + value, defaultQuality, new ConfigDescription("Quality Level needed to apply effect to backpack. Zero disables effect for Biome.", (AcceptableValueBase)(object)new AcceptableValueRange(0, 5), new object[1] { (object)new ConfigurationManagerAttributes { Order = 2 } }), ref configEntry); ConfigEntry val = configEntry; if (!BiomeQualityLevels.ContainsKey(value) && val != null) { BiomeQualityLevels.Add(value, val); val.SettingChanged += Backpacks.UpdateItemDataConfigValues; } } } } } public class FeatherFall : EffectsBase { public FeatherFall(string effectName, string effectDesc) : base(effectName, effectDesc) { } public override void LoadStatusEffect() { SetStatusEffect("SlowFall"); } public override bool HasActiveStatusEffect(Humanoid human, out StatusEffect statusEffect) { SetStatusEffect("SlowFall"); return base.HasActiveStatusEffect(human, out statusEffect); } } public class FrostResistance : EffectsBase { private StatusEffect _externalStatusEffect; public static DamageModPair EffectMod = new DamageModPair { m_type = (DamageType)64, m_modifier = (DamageModifier)1 }; public FrostResistance(string effectName, string effectDesc) : base(effectName, effectDesc) { } private void LoadExternalStatusEffect() { if ((Object)(object)_externalStatusEffect == (Object)null) { StatusEffect statusEffect = ObjectDB.instance.GetStatusEffect("Freezing".GetHashCode()); CustomSE customSE = new CustomSE(Enums.StatusEffects.Stats, "SE_vapok_ab_frost_resistance"); customSE.Effect.m_name = "$vapok_mod_se_frost_resistance"; customSE.Effect.m_icon = statusEffect.m_icon; _externalStatusEffect = customSE.Effect; SetStatusEffect(_externalStatusEffect); } } public override void LoadStatusEffect() { LoadExternalStatusEffect(); } public override bool HasActiveStatusEffect(Humanoid human, out StatusEffect statusEffect) { LoadExternalStatusEffect(); SetStatusEffect(_externalStatusEffect); return base.HasActiveStatusEffect(human, out statusEffect); } public override bool HasActiveStatusEffect(ItemData item, out StatusEffect statusEffect) { LoadExternalStatusEffect(); SetStatusEffect(_externalStatusEffect); return base.HasActiveStatusEffect(item, out statusEffect); } public override bool IsEffectActive(Humanoid human) { Player val = (Player)(object)((human is Player) ? human : null); if (val != null) { BackpackComponent equippedBackpack = val.GetEquippedBackpack(); if (equippedBackpack == null || !EnabledEffect.Value) { return false; } ItemData item = equippedBackpack.Item; return IsEffectActive(item); } return false; } } public class TrollArmor : EffectsBase { private string _effectName = "SetEffect_TrollArmor"; public TrollArmor(string effectName, string effectDesc) : base(effectName, effectDesc, IsItemSetStatusEffect: true) { } public override void LoadStatusEffect() { SetStatusEffect(_effectName); } public override bool HasActiveStatusEffect(ItemData item, out StatusEffect statusEffect) { SetStatusEffect(_effectName); return base.HasActiveStatusEffect(item, out statusEffect); } public override bool IsEffectActive(Humanoid human) { Player val = (Player)(object)((human is Player) ? human : null); if (val != null) { BackpackComponent equippedBackpack = val.GetEquippedBackpack(); if (equippedBackpack == null || !EnabledEffect.Value) { return false; } ItemData item = equippedBackpack.Item; return IsEffectActive(item); } return false; } } public class Waterproof : EffectsBase { private StatusEffect _externalStatusEffect; public Waterproof(string effectName, string effectDesc) : base(effectName, effectDesc) { } private void LoadExternalStatusEffect() { if ((Object)(object)_externalStatusEffect == (Object)null) { StatusEffect statusEffect = ObjectDB.instance.GetStatusEffect("Wet".GetHashCode()); CustomSE customSE = new CustomSE(Enums.StatusEffects.Stats, "SE_vapok_ab_wet_resistance"); customSE.Effect.m_name = "$vapok_mod_se_wet_resistance"; customSE.Effect.m_icon = statusEffect.m_icon; _externalStatusEffect = customSE.Effect; SetStatusEffect(_externalStatusEffect); } } public override void LoadStatusEffect() { LoadExternalStatusEffect(); } public override bool HasActiveStatusEffect(Humanoid human, out StatusEffect statusEffect) { LoadExternalStatusEffect(); SetStatusEffect(_externalStatusEffect); return base.HasActiveStatusEffect(human, out statusEffect); } public override bool HasActiveStatusEffect(ItemData item, out StatusEffect statusEffect) { LoadExternalStatusEffect(); SetStatusEffect(_externalStatusEffect); return base.HasActiveStatusEffect(item, out statusEffect); } } public class ExternalEffect : EffectsBase { private string _effectName = string.Empty; private StatusEffect _externalStatusEffect; private ABAPI.EffectDefinition _effectDefinition; public ExternalEffect(ABAPI.EffectDefinition effectDefinition) : base(effectDefinition.Name, effectDefinition.Description) { _effectDefinition = effectDefinition; if (!string.IsNullOrEmpty(_effectDefinition.EffectName)) { _effectName = _effectDefinition.EffectName; } } public override void RegisterEffectConfiguration() { base.RegisterEffectConfiguration(); if ((Object)(object)_effectDefinition.StatusEffect == (Object)null) { AdventureBackpacks.Log.Error("Status Effect is null for " + _effectDefinition.Name + " - Disabling Status Effect"); EnabledEffect.Value = false; } } public override void AdditionalConfiguration(string configSection) { } private void LoadExternalStatusEffect() { try { if (!((Object)(object)_externalStatusEffect != (Object)null)) { _externalStatusEffect = _effectDefinition.StatusEffect; SetStatusEffect(_externalStatusEffect); } } catch (Exception ex) { AdventureBackpacks.Log.Error("Can't Load External Status Effect: " + _effectName + " - Message: " + ex.Message); } } public override void LoadStatusEffect() { LoadExternalStatusEffect(); } public override bool HasActiveStatusEffect(Humanoid human, out StatusEffect statusEffect) { statusEffect = null; if (!EnabledEffect.Value) { return false; } LoadExternalStatusEffect(); SetStatusEffect(_externalStatusEffect); return base.HasActiveStatusEffect(human, out statusEffect); } public override bool HasActiveStatusEffect(ItemData item, out StatusEffect statusEffect) { statusEffect = null; if (!EnabledEffect.Value) { return false; } LoadExternalStatusEffect(); SetStatusEffect(_externalStatusEffect); return base.HasActiveStatusEffect(item, out statusEffect); } public override bool IsEffectActive(Humanoid human) { Player val = (Player)(object)((human is Player) ? human : null); if (val != null) { BackpackComponent equippedBackpack = val.GetEquippedBackpack(); if (equippedBackpack == null || !EnabledEffect.Value) { return false; } ItemData item = equippedBackpack.Item; return IsEffectActive(item); } return false; } } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace ItemManager { [PublicAPI] internal enum CraftingTable { Disabled, Inventory, [InternalName("piece_workbench")] Workbench, [InternalName("piece_cauldron")] Cauldron, [InternalName("forge")] Forge, [InternalName("piece_artisanstation")] ArtisanTable, [InternalName("piece_stonecutter")] StoneCutter, [InternalName("piece_magetable")] MageTable, [InternalName("blackforge")] BlackForge, [InternalName("piece_preptable")] FoodPreparationTable, [InternalName("piece_MeadCauldron")] MeadKetill, Custom } [PublicAPI] internal enum ConversionPiece { Disabled, [InternalName("smelter")] Smelter, [InternalName("charcoal_kiln")] CharcoalKiln, [InternalName("blastfurnace")] BlastFurnace, [InternalName("windmill")] Windmill, [InternalName("piece_spinningwheel")] SpinningWheel, [InternalName("eitrrefinery")] EitrRefinery, Custom } internal class InternalName : Attribute { public readonly string internalName; public InternalName(string internalName) { this.internalName = internalName; } } [PublicAPI] internal class RequiredResourceList { public readonly List Requirements = new List(); public bool Free; public void Add(string itemName, int amount, int quality = 0) { Requirements.Add(new Requirement { itemName = itemName, amount = amount, quality = quality }); } public void Add(string itemName, ConfigEntry amountConfig, int quality = 0) { Requirements.Add(new Requirement { itemName = itemName, amountConfig = amountConfig, quality = quality }); } } [PublicAPI] internal class CraftingStationList { public readonly List Stations = new List(); public void Add(CraftingTable table, int level) { Stations.Add(new CraftingStationConfig { Table = table, level = level }); } public void Add(string customTable, int level) { Stations.Add(new CraftingStationConfig { Table = CraftingTable.Custom, level = level, custom = customTable }); } } [PublicAPI] internal class ItemRecipe { public readonly RequiredResourceList RequiredItems = new RequiredResourceList(); public readonly RequiredResourceList RequiredUpgradeItems = new RequiredResourceList(); public readonly CraftingStationList Crafting = new CraftingStationList(); public int CraftAmount = 1; public bool RequireOnlyOneIngredient; public float QualityResultAmountMultiplier = 1f; public ConfigEntryBase? RecipeIsActive; } [PublicAPI] internal class Trade { public Trader Trader; public uint Price; public uint Stack = 1u; public string? RequiredGlobalKey; } [PublicAPI] [Flags] internal enum Trader { None = 0, Haldor = 1, Hildir = 2 } internal struct Requirement { public string itemName; public int amount; public ConfigEntry? amountConfig; [Description("Set to a non-zero value to apply the requirement only for a specific quality")] public int quality; } internal struct CraftingStationConfig { public CraftingTable Table; public int level; public string? custom; } [Flags] internal enum Configurability { Disabled = 0, Recipe = 1, Stats = 2, Drop = 4, Trader = 8, Full = 0xF } [PublicAPI] internal class DropTargets { public readonly List Drops = new List(); public void Add(string creatureName, float chance, int min = 1, int? max = null, bool levelMultiplier = true) { Drops.Add(new DropTarget { creature = creatureName, chance = chance, min = min, max = (max ?? min), levelMultiplier = levelMultiplier }); } } internal struct DropTarget { public string creature; public int min; public int max; public float chance; public bool levelMultiplier; } internal enum Toggle { On = 1, Off = 0 } [PublicAPI] internal class Item { private class ItemConfig { public ConfigEntry? craft; public ConfigEntry? upgrade; public ConfigEntry table; public ConfigEntry tableLevel; public ConfigEntry customTable; public ConfigEntry? maximumTableLevel; public ConfigEntry requireOneIngredient; public ConfigEntry qualityResultAmountMultiplier; } private class TraderConfig { public ConfigEntry trader; public ConfigEntry price; public ConfigEntry stack; public ConfigEntry requiredGlobalKey; } private class RequirementQuality { public int quality; } private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] public string? Category; [UsedImplicitly] public Action? CustomDrawer; public Func? browsability; } [PublicAPI] public enum DamageModifier { Normal, Resistant, Weak, Immune, Ignore, VeryResistant, VeryWeak, None } private delegate void setDmgFunc(ref DamageTypes dmg, float value); private class SerializedRequirements { public readonly List Reqs; public SerializedRequirements(List reqs) { Reqs = reqs; } public SerializedRequirements(string reqs) : this(reqs.Split(new char[1] { ',' }).Select(delegate(string r) { string[] array = r.Split(new char[1] { ':' }); int result; int result2; return new Requirement { itemName = array[0], amount = ((array.Length <= 1 || !int.TryParse(array[1], out result)) ? 1 : result), quality = ((array.Length > 2 && int.TryParse(array[2], out result2)) ? result2 : 0) }; }).ToList()) { } public override string ToString() { return string.Join(",", Reqs.Select((Requirement r) => $"{r.itemName}:{r.amount}")); } public static ItemDrop? fetchByName(ObjectDB objectDB, string name) { GameObject itemPrefab = objectDB.GetItemPrefab(name); ItemDrop obj = ((itemPrefab != null) ? itemPrefab.GetComponent() : null); if ((Object)(object)obj == (Object)null) { LogManager.Log.Warning("The required item '" + name + "' does not exist."); } return obj; } public static Requirement[] toPieceReqs(ObjectDB objectDB, SerializedRequirements craft, SerializedRequirements upgrade) { //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Expected O, but got Unknown //IL_0194: Expected O, but got Unknown //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Expected O, but got Unknown Dictionary dictionary = craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func)((Requirement r) => r.itemName), (Func)delegate(Requirement r) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: 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_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown ItemDrop val6 = ResItem(r); return (val6 != null) ? new Requirement { m_amount = (r.amountConfig?.Value ?? r.amount), m_resItem = val6, m_amountPerLevel = 0 } : ((Requirement)null); }); List list = dictionary.Values.Where((Requirement v) => v != null).ToList(); foreach (Requirement item in upgrade.Reqs.Where((Requirement r) => r.itemName != "")) { if (item.quality > 0) { ItemDrop val = ResItem(item); if (val != null) { Requirement val2 = new Requirement { m_resItem = val, m_amountPerLevel = (item.amountConfig?.Value ?? item.amount), m_amount = 0 }; list.Add(val2); requirementQuality.Add(val2, new RequirementQuality { quality = item.quality }); } continue; } if (!dictionary.TryGetValue(item.itemName, out var value) || value == null) { ItemDrop val3 = ResItem(item); if (val3 != null) { string itemName = item.itemName; Requirement val4 = new Requirement { m_resItem = val3, m_amount = 0 }; Requirement val5 = val4; dictionary[itemName] = val4; value = val5; list.Add(value); } } if (value != null) { value.m_amountPerLevel = item.amountConfig?.Value ?? item.amount; } } return list.ToArray(); ItemDrop? ResItem(Requirement r) { return fetchByName(objectDB, r.itemName); } } } private class SerializedDrop { public readonly List Drops; public SerializedDrop(List drops) { Drops = drops; } public SerializedDrop(string drops) { Drops = ((drops == "") ? ((IEnumerable)Array.Empty()) : ((IEnumerable)drops.Split(new char[1] { ',' }))).Select(delegate(string r) { string[] array = r.Split(new char[1] { ':' }); if (array.Length <= 2 || !int.TryParse(array[2], out var result)) { result = 1; } if (array.Length <= 3 || !int.TryParse(array[3], out var result2)) { result2 = result; } bool levelMultiplier = array.Length <= 4 || array[4] != "0"; float result3; return new DropTarget { creature = array[0], chance = ((array.Length > 1 && float.TryParse(array[1], out result3)) ? result3 : 1f), min = result, max = result2, levelMultiplier = levelMultiplier }; }).ToList(); } public override string ToString() { return string.Join(",", Drops.Select((DropTarget r) => $"{r.creature}:{r.chance.ToString(CultureInfo.InvariantCulture)}:{r.min}:" + ((r.min == r.max) ? "" : $"{r.max}") + (r.levelMultiplier ? "" : ":0"))); } private static Character? fetchByName(ZNetScene netScene, string name) { GameObject prefab = netScene.GetPrefab(name); Character obj = ((prefab != null) ? prefab.GetComponent() : null); if ((Object)(object)obj == (Object)null) { LogManager.Log.Debug("The drop target character '" + name + "' does not exist."); } return obj; } public Dictionary toCharacterDrops(ZNetScene netScene, GameObject item) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0046: 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) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown Dictionary dictionary = new Dictionary(); foreach (DropTarget drop in Drops) { Character val = fetchByName(netScene, drop.creature); if (val != null) { dictionary[val] = new Drop { m_prefab = item, m_amountMin = drop.min, m_amountMax = drop.max, m_chance = drop.chance, m_levelMultiplier = drop.levelMultiplier }; } } return dictionary; } } private static bool _initialized = false; private static readonly List registeredItems = new List(); private static readonly Dictionary itemDropMap = new Dictionary(); private static Dictionary>> activeRecipes = new Dictionary>>(); private static Dictionary hiddenCraftRecipes = new Dictionary(); private static Dictionary hiddenUpgradeRecipes = new Dictionary(); private static Dictionary> itemCraftConfigs = new Dictionary>(); private static Dictionary> itemDropConfigs = new Dictionary>(); private static Dictionary> itemDropEnabledConfig = new Dictionary>(); private Dictionary characterDrops = new Dictionary(); private readonly Dictionary statsConfigs = new Dictionary(); private static readonly ConditionalWeakTable requirementQuality = new ConditionalWeakTable(); public string SectionName = string.Empty; public static Configurability DefaultConfigurability = Configurability.Full; public Configurability? Configurable; private Configurability configurationVisible = Configurability.Full; private TraderConfig? traderConfig; public readonly GameObject Prefab; [Description("Specifies the maximum required crafting station level to upgrade and repair the item.\nDefault is calculated from crafting station level and maximum quality.")] public int MaximumRequiredStationLevel = int.MaxValue; [Description("Assigns the item as a drop item to a creature.\nUses a creature name, a drop chance and a minimum and maximum amount.")] public readonly DropTargets DropsFrom = new DropTargets(); [Description("Configures whether the item can be bought at the trader.\nDon't forget to set cost to something above 0 or the item will be sold for free.")] public readonly Trade Trade = new Trade(); internal List Conversions = new List(); internal List conversions = new List(); public Dictionary Recipes = new Dictionary(); private static object? configManager; private static BaseUnityPlugin? _plugin; private Configurability configurability => Configurable ?? DefaultConfigurability; [Description("Specifies the resources needed to craft the item.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the item should need.")] public RequiredResourceList RequiredItems => this[""].RequiredItems; [Description("Specifies the resources needed to upgrade the item.\nUse .Add to add resources with their internal ID and an amount. This amount will be multipled by the item quality level.\nUse one .Add for each resource type the upgrade should need.")] public RequiredResourceList RequiredUpgradeItems => this[""].RequiredUpgradeItems; [Description("Specifies the crafting station needed to craft the item.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.\nUse one .Add for each crafting station.")] public CraftingStationList Crafting => this[""].Crafting; [Description("Specifies a config entry which toggles whether a recipe is active.")] public ConfigEntryBase? RecipeIsActive { get { return this[""].RecipeIsActive; } set { this[""].RecipeIsActive = value; } } [Description("Specifies the number of items that should be given to the player with a single craft of the item.\nDefaults to 1.")] public int CraftAmount { get { return this[""].CraftAmount; } set { this[""].CraftAmount = value; } } public bool RequireOnlyOneIngredient { get { return this[""].RequireOnlyOneIngredient; } set { this[""].RequireOnlyOneIngredient = value; } } public float QualityResultAmountMultiplier { get { return this[""].QualityResultAmountMultiplier; } set { this[""].QualityResultAmountMultiplier = value; } } public ItemRecipe this[string name] { get { if (Recipes.TryGetValue(name, out ItemRecipe value)) { return value; } return Recipes[name] = new ItemRecipe(); } } private static BaseUnityPlugin plugin { get { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown if (_plugin == null) { IEnumerable source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First((TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } public static void Init() { if (!_initialized) { _initialized = true; } } public Item(string assetBundleFileName, string prefabName, string folderName = "assets") : this(PrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName) { } public Item(AssetBundle bundle, string prefabName) : this(PrefabManager.RegisterPrefab(bundle, prefabName, addToObjectDb: true), skipRegistering: true) { } public Item(GameObject prefab, bool skipRegistering = false) { if (!skipRegistering) { PrefabManager.RegisterPrefab(prefab, addToObjectDb: true); } Prefab = prefab; registeredItems.Add(this); itemDropMap[Prefab.GetComponent()] = this; Prefab.GetComponent().m_itemData.m_dropPrefab = Prefab; } public void ToggleConfigurationVisibility(Configurability visible) { configurationVisible = visible; if (itemDropConfigs.TryGetValue(this, out ConfigEntry value)) { Toggle((ConfigEntryBase)(object)value, Configurability.Drop); } if (itemCraftConfigs.TryGetValue(this, out Dictionary value2)) { foreach (ItemConfig value4 in value2.Values) { ToggleObj(value4, Configurability.Recipe); } } foreach (Conversion conversion in Conversions) { if (conversion.config != null) { ToggleObj(conversion.config, Configurability.Recipe); } } foreach (KeyValuePair statsConfig in statsConfigs) { Toggle(statsConfig.Key, Configurability.Stats); if ((visible & Configurability.Stats) != Configurability.Disabled) { statsConfig.Value(); } } reloadConfigDisplay(); void Toggle(ConfigEntryBase cfg, Configurability check) { object[] tags = cfg.Description.Tags; for (int i = 0; i < tags.Length; i++) { if (tags[i] is ConfigurationManagerAttributes configurationManagerAttributes) { configurationManagerAttributes.Browsable = (visible & check) != Configurability.Disabled && (configurationManagerAttributes.browsability == null || configurationManagerAttributes.browsability()); } } } void ToggleObj(object obj, Configurability check) { FieldInfo[] fields = obj.GetType().GetFields(); for (int i = 0; i < fields.Length; i++) { object? value3 = fields[i].GetValue(obj); ConfigEntryBase val = (ConfigEntryBase)((value3 is ConfigEntryBase) ? value3 : null); if (val != null) { Toggle(val, check); } } } } internal static void reloadConfigDisplay() { object obj = configManager?.GetType().GetProperty("DisplayingWindow").GetValue(configManager); if (obj is bool && (bool)obj) { configManager.GetType().GetMethod("BuildSettingList").Invoke(configManager, Array.Empty()); } } private void UpdateItemTableConfig(string recipeKey, CraftingTable table, string customTableValue) { if (activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(recipeKey, out List value)) { value.First().m_enabled = table != CraftingTable.Disabled; if ((uint)table <= 1u) { value.First().m_craftingStation = null; } else if (table == CraftingTable.Custom) { Recipe obj = value.First(); GameObject prefab = ZNetScene.instance.GetPrefab(customTableValue); obj.m_craftingStation = ((prefab != null) ? prefab.GetComponent() : null); } else { value.First().m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName(table)).GetComponent(); } } } private void UpdateCraftConfig(string recipeKey, SerializedRequirements craftRequirements, SerializedRequirements upgradeRequirements) { if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || !activeRecipes.ContainsKey(this) || !activeRecipes[this].TryGetValue(recipeKey, out List value)) { return; } foreach (Recipe item in value) { item.m_resources = SerializedRequirements.toPieceReqs(ObjectDB.instance, craftRequirements, upgradeRequirements); } } internal static void Patch_FejdStartup() { //IL_107a: Unknown result type (might be due to invalid IL or missing references) //IL_107f: Unknown result type (might be due to invalid IL or missing references) //IL_2333: Unknown result type (might be due to invalid IL or missing references) //IL_2340: Expected O, but got Unknown //IL_1143: Unknown result type (might be due to invalid IL or missing references) //IL_1146: Unknown result type (might be due to invalid IL or missing references) //IL_119c: Expected I4, but got Unknown //IL_0c4a: Unknown result type (might be due to invalid IL or missing references) //IL_0c5c: Expected O, but got Unknown //IL_0d1c: Unknown result type (might be due to invalid IL or missing references) //IL_0d29: Expected O, but got Unknown //IL_12d0: Unknown result type (might be due to invalid IL or missing references) //IL_12d3: Unknown result type (might be due to invalid IL or missing references) //IL_12d5: Invalid comparison between Unknown and I4 //IL_03a3: Unknown result type (might be due to invalid IL or missing references) //IL_03ba: Expected O, but got Unknown //IL_12d7: Unknown result type (might be due to invalid IL or missing references) //IL_12db: Invalid comparison between Unknown and I4 //IL_0e7d: Unknown result type (might be due to invalid IL or missing references) //IL_0e99: Expected O, but got Unknown //IL_0f29: Unknown result type (might be due to invalid IL or missing references) //IL_0f45: Expected O, but got Unknown //IL_12dd: Unknown result type (might be due to invalid IL or missing references) //IL_12e1: Invalid comparison between Unknown and I4 //IL_0fde: Unknown result type (might be due to invalid IL or missing references) //IL_0ffa: Expected O, but got Unknown //IL_14dc: Unknown result type (might be due to invalid IL or missing references) //IL_14df: Unknown result type (might be due to invalid IL or missing references) //IL_14e1: Invalid comparison between Unknown and I4 //IL_0497: Unknown result type (might be due to invalid IL or missing references) //IL_04ae: Expected O, but got Unknown //IL_14e3: Unknown result type (might be due to invalid IL or missing references) //IL_14e7: Unknown result type (might be due to invalid IL or missing references) //IL_14e9: Invalid comparison between Unknown and I4 //IL_14eb: Unknown result type (might be due to invalid IL or missing references) //IL_14ef: Invalid comparison between Unknown and I4 //IL_05d3: Unknown result type (might be due to invalid IL or missing references) //IL_05ea: Expected O, but got Unknown //IL_15c4: Unknown result type (might be due to invalid IL or missing references) //IL_15c9: Unknown result type (might be due to invalid IL or missing references) //IL_15cb: Unknown result type (might be due to invalid IL or missing references) //IL_15ce: Invalid comparison between Unknown and I4 //IL_15d0: Unknown result type (might be due to invalid IL or missing references) //IL_15d4: Invalid comparison between Unknown and I4 //IL_06ec: Unknown result type (might be due to invalid IL or missing references) //IL_0703: Expected O, but got Unknown //IL_1643: Unknown result type (might be due to invalid IL or missing references) //IL_1646: Unknown result type (might be due to invalid IL or missing references) //IL_1648: Invalid comparison between Unknown and I4 //IL_164a: Unknown result type (might be due to invalid IL or missing references) //IL_164e: Unknown result type (might be due to invalid IL or missing references) //IL_1650: Invalid comparison between Unknown and I4 //IL_07cc: Unknown result type (might be due to invalid IL or missing references) //IL_07e3: Expected O, but got Unknown //IL_1652: Unknown result type (might be due to invalid IL or missing references) //IL_1656: Invalid comparison between Unknown and I4 //IL_1793: Unknown result type (might be due to invalid IL or missing references) //IL_1796: Invalid comparison between Unknown and I4 //IL_08d7: Unknown result type (might be due to invalid IL or missing references) //IL_08ee: Expected O, but got Unknown //IL_1993: Unknown result type (might be due to invalid IL or missing references) //IL_199a: Invalid comparison between Unknown and I4 //IL_1a63: Unknown result type (might be due to invalid IL or missing references) //IL_1a68: Unknown result type (might be due to invalid IL or missing references) //IL_1a6a: Unknown result type (might be due to invalid IL or missing references) //IL_1a6e: Unknown result type (might be due to invalid IL or missing references) //IL_1a70: Invalid comparison between Unknown and I4 //IL_1adf: Unknown result type (might be due to invalid IL or missing references) //IL_1ae2: Unknown result type (might be due to invalid IL or missing references) //IL_1ae4: Invalid comparison between Unknown and I4 //IL_1709: Unknown result type (might be due to invalid IL or missing references) //IL_170e: Unknown result type (might be due to invalid IL or missing references) //IL_1ae6: Unknown result type (might be due to invalid IL or missing references) //IL_1aea: Invalid comparison between Unknown and I4 //IL_1aec: Unknown result type (might be due to invalid IL or missing references) //IL_1af0: Invalid comparison between Unknown and I4 //IL_1f5d: Unknown result type (might be due to invalid IL or missing references) //IL_1f60: Invalid comparison between Unknown and I4 Type type = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager"); configManager = ((type == null) ? null : Chainloader.ManagerObject.GetComponent(type)); if (DefaultConfigurability != Configurability.Disabled) { bool saveOnConfigSet = plugin.Config.SaveOnConfigSet; plugin.Config.SaveOnConfigSet = false; foreach (Item item3 in registeredItems.Where((Item i) => i.configurability != Configurability.Disabled)) { Item item = item3; string text = (string.IsNullOrEmpty(item.SectionName) ? item.Prefab.GetComponent().m_itemData.m_shared.m_name : item.SectionName); string englishName = new Regex("['[\"\\]]").Replace(Localizer.GetTranslation("English", text), "").Trim(); string localizedName = Localization.instance.Localize(text).Trim(); int order = 0; if ((item.configurability & Configurability.Recipe) != Configurability.Disabled) { itemCraftConfigs[item] = new Dictionary(); foreach (string item4 in item.Recipes.Keys.DefaultIfEmpty("")) { string configKey = item4; string text2 = ((configKey == "") ? "" : (" (" + configKey + ")")); if (configKey == "") { Configurability? configurable = item.Configurable; if (configurable.HasValue && item.Crafting.Stations.Count == 0) { item.Crafting.Add(CraftingTable.Disabled, 1); } } if (!item.Recipes.ContainsKey(configKey) || item.Recipes[configKey].Crafting.Stations.Count <= 0) { continue; } ItemConfig itemConfig = (itemCraftConfigs[item][configKey] = new ItemConfig()); ItemConfig cfg = itemConfig; List hideWhenNoneAttributes = new List(); ConfigSyncBase.SyncedConfig(englishName, "Crafting Station" + text2, item.Recipes[configKey].Crafting.Stations.First().Table, new ConfigDescription("Crafting station where " + englishName + " is available.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), Browsable = ((item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName } }), ref cfg.table); ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = CustomTableBrowsability, Browsable = (CustomTableBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; ConfigSyncBase.SyncedConfig(englishName, "Custom Crafting Station" + text2, item.Recipes[configKey].Crafting.Stations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes }), ref cfg.customTable); cfg.table.SettingChanged += TableConfigChanged; cfg.customTable.SettingChanged += TableConfigChanged; ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = TableLevelBrowsability, Browsable = (TableLevelBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; hideWhenNoneAttributes.Add(configurationManagerAttributes); ConfigSyncBase.SyncedConfig(englishName, "Crafting Station Level" + text2, item.Recipes[configKey].Crafting.Stations.First().level, new ConfigDescription("Required crafting station level to craft " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes }), ref cfg.tableLevel); cfg.tableLevel.SettingChanged += delegate { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List value)) { value.First().m_minStationLevel = cfg.tableLevel.Value; } }; if (item.Prefab.GetComponent().m_itemData.m_shared.m_maxQuality > 1) { ConfigSyncBase.SyncedConfig(englishName, "Maximum Crafting Station Level" + text2, (item.MaximumRequiredStationLevel == int.MaxValue) ? (item.Recipes[configKey].Crafting.Stations.First().level + item.Prefab.GetComponent().m_itemData.m_shared.m_maxQuality - 1) : item.MaximumRequiredStationLevel, new ConfigDescription("Maximum crafting station level to upgrade and repair " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes }), ref cfg.maximumTableLevel); } ConfigSyncBase.SyncedConfig(englishName, "Require only one resource" + text2, item.Recipes[configKey].RequireOnlyOneIngredient ? Toggle.On : Toggle.Off, new ConfigDescription("Whether only one of the ingredients is needed to craft " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), browsability = TableLevelBrowsability, Browsable = (TableLevelBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName } }), ref cfg.requireOneIngredient); ConfigurationManagerAttributes qualityResultAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = QualityResultBrowsability, Browsable = (QualityResultBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; cfg.requireOneIngredient.SettingChanged += delegate { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List value)) { foreach (Recipe item5 in value) { item5.m_requireOnlyOneIngredient = cfg.requireOneIngredient.Value == Toggle.On; } } qualityResultAttributes.Browsable = QualityResultBrowsability(); reloadConfigDisplay(); }; ConfigSyncBase.SyncedConfig(englishName, "Quality Multiplier" + text2, item.Recipes[configKey].QualityResultAmountMultiplier, new ConfigDescription("Multiplies the crafted amount based on the quality of the resources when crafting " + englishName + ". Only works, if Require Only One Resource is true.", (AcceptableValueBase)null, new object[1] { qualityResultAttributes }), ref cfg.qualityResultAmountMultiplier); cfg.qualityResultAmountMultiplier.SettingChanged += delegate { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List value)) { foreach (Recipe item6 in value) { item6.m_qualityResultAmountMultiplier = cfg.qualityResultAmountMultiplier.Value; } } }; if ((!item.Recipes[configKey].RequiredItems.Free || item.Recipes[configKey].RequiredItems.Requirements.Count > 0) && item.Recipes[configKey].RequiredItems.Requirements.All((Requirement r) => r.amountConfig == null)) { cfg.craft = itemConfig3("Crafting Costs" + text2, new SerializedRequirements(item.Recipes[configKey].RequiredItems.Requirements).ToString(), "Item costs to craft " + englishName, isUpgrade: false); } if (item.Prefab.GetComponent().m_itemData.m_shared.m_maxQuality > 1 && (!item.Recipes[configKey].RequiredUpgradeItems.Free || item.Recipes[configKey].RequiredUpgradeItems.Requirements.Count > 0) && item.Recipes[configKey].RequiredUpgradeItems.Requirements.All((Requirement r) => r.amountConfig == null)) { cfg.upgrade = itemConfig3("Upgrading Costs" + text2, new SerializedRequirements(item.Recipes[configKey].RequiredUpgradeItems.Requirements).ToString(), "Item costs per level to upgrade " + englishName, isUpgrade: true); } if (cfg.craft != null) { cfg.craft.SettingChanged += ConfigChanged; } if (cfg.upgrade != null) { cfg.upgrade.SettingChanged += ConfigChanged; } void ConfigChanged(object o, EventArgs e) { item.UpdateCraftConfig(configKey, new SerializedRequirements(cfg.craft?.Value ?? ""), new SerializedRequirements(cfg.upgrade?.Value ?? "")); } bool CustomTableBrowsability() { return cfg.table.Value == CraftingTable.Custom; } bool ItemBrowsability() { return cfg.table.Value != CraftingTable.Disabled; } bool QualityResultBrowsability() { return cfg.requireOneIngredient.Value == Toggle.On; } void TableConfigChanged(object o, EventArgs e) { item.UpdateItemTableConfig(configKey, cfg.table.Value, cfg.customTable.Value); customTableAttributes.Browsable = cfg.table.Value == CraftingTable.Custom; foreach (ConfigurationManagerAttributes item7 in hideWhenNoneAttributes) { item7.Browsable = cfg.table.Value != CraftingTable.Disabled; } reloadConfigDisplay(); } bool TableLevelBrowsability() { return cfg.table.Value != CraftingTable.Disabled; } ConfigEntry itemConfig3(string name, string value, string desc, bool isUpgrade) { //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes { CustomDrawer = drawRequirementsConfigTable(item, isUpgrade), Order = (order -= 1), browsability = ItemBrowsability, Browsable = (ItemBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; hideWhenNoneAttributes.Add(configurationManagerAttributes2); ConfigEntry configEntry3 = null; ConfigSyncBase.SyncedConfig(englishName, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes2 }), ref configEntry3); return configEntry3; } } if ((item.configurability & Configurability.Drop) != Configurability.Disabled) { ConfigEntry dropsEnabledConfig = null; ConfigSyncBase.SyncedConfig(englishName, "Drops Enabled", value: false, new ConfigDescription("Enables " + englishName + " drops", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Drop) != 0) } }), ref dropsEnabledConfig); itemDropEnabledConfig[item] = dropsEnabledConfig; ConfigEntry configEntry = null; ConfigSyncBase.SyncedConfig(englishName, "Drops from", new SerializedDrop(item.DropsFrom.Drops).ToString(), new ConfigDescription("Creatures " + englishName + " drops from", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { CustomDrawer = drawDropsConfigTable, Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Drop) != 0) } }), ref configEntry); itemDropConfigs[item] = configEntry; dropsEnabledConfig.SettingChanged += delegate { item.UpdateCharacterDrop(dropsEnabledConfig.Value); }; configEntry.SettingChanged += delegate { item.UpdateCharacterDrop(dropsEnabledConfig.Value); }; item.UpdateCharacterDrop(dropsEnabledConfig.Value); } for (int num = 0; num < item.Conversions.Count; num++) { string text3 = ((item.Conversions.Count > 1) ? $"{num + 1}. " : ""); Conversion conversion = item.Conversions[num]; conversion.config = new Conversion.ConversionConfig(); int index = num; ConfigSyncBase.SyncedConfig(englishName, text3 + "Conversion Input Item", conversion.Input, new ConfigDescription("Input item to create " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Recipe) != 0) } }), ref conversion.config.input); conversion.config.input.SettingChanged += delegate { if (index < item.conversions.Count) { ObjectDB instance = ObjectDB.instance; if (instance != null) { ItemDrop val = SerializedRequirements.fetchByName(instance, conversion.config.input.Value); item.conversions[index].m_from = val; UpdatePiece(); } } }; ConfigSyncBase.SyncedConfig(englishName, text3 + "Conversion Piece", conversion.Piece, new ConfigDescription("Conversion piece used to create " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Recipe) != 0) } }), ref conversion.config.piece); conversion.config.piece.SettingChanged += delegate { UpdatePiece(); }; ConfigSyncBase.SyncedConfig(englishName, text3 + "Conversion Custom Piece", conversion.customPiece ?? "", new ConfigDescription("Custom conversion piece to create " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Recipe) != 0) } }), ref conversion.config.customPiece); conversion.config.customPiece.SettingChanged += delegate { UpdatePiece(); }; void UpdatePiece() { if (index < item.conversions.Count && Object.op_Implicit((Object)(object)ZNetScene.instance)) { string text4 = ((conversion.config.piece.Value == ConversionPiece.Disabled) ? null : ((conversion.config.piece.Value == ConversionPiece.Custom) ? conversion.config.customPiece.Value : getInternalName(conversion.config.piece.Value))); string activePiece = conversion.config.activePiece; if (conversion.config.activePiece != null) { int num4 = ZNetScene.instance.GetPrefab(conversion.config.activePiece).GetComponent().m_conversion.IndexOf(item.conversions[index]); if (num4 >= 0) { Smelter[] array3 = Resources.FindObjectsOfTypeAll(); foreach (Smelter val in array3) { if (Utils.GetPrefabName(((Component)val).gameObject) == activePiece) { val.m_conversion.RemoveAt(num4); } } } conversion.config.activePiece = null; } if (item.conversions[index].m_from != null && conversion.config.piece.Value != ConversionPiece.Disabled) { GameObject prefab = ZNetScene.instance.GetPrefab(text4); if (((prefab != null) ? prefab.GetComponent() : null) != null) { conversion.config.activePiece = text4; Smelter[] array3 = Resources.FindObjectsOfTypeAll(); foreach (Smelter val2 in array3) { if (Utils.GetPrefabName(((Component)val2).gameObject) == text4) { val2.m_conversion.Add(item.conversions[index]); } } } } } } } } if ((item.configurability & Configurability.Stats) != Configurability.Disabled) { item.statsConfigs.Clear(); SharedData shared = item.Prefab.GetComponent().m_itemData.m_shared; ItemType itemType = shared.m_itemType; statcfg("Weight", "Weight of " + englishName + ".", (SharedData val) => val.m_weight, delegate(SharedData val, float value) { val.m_weight = value; }); statcfg("Trader Value", "Trader value of " + englishName + ".", (SharedData val) => val.m_value, delegate(SharedData val, int value) { val.m_value = value; }); bool flag; switch (itemType - 3) { case 0: case 1: case 2: case 3: case 4: case 8: case 9: case 11: case 14: case 16: case 19: flag = true; break; default: flag = false; break; } if (flag) { statcfg("Durability", "Durability of " + englishName + ".", (SharedData val) => val.m_maxDurability, delegate(SharedData val, float value) { val.m_maxDurability = value; }); statcfg("Durability per Level", "Durability gain per level of " + englishName + ".", (SharedData val) => val.m_durabilityPerLevel, delegate(SharedData val, float value) { val.m_durabilityPerLevel = value; }); statcfg("Movement Speed Modifier", "Movement speed modifier of " + englishName + ".", (SharedData val) => val.m_movementModifier, delegate(SharedData val, float value) { val.m_movementModifier = value; }); } if ((itemType - 3 <= 2 || (int)itemType == 14 || (int)itemType == 22) ? true : false) { statcfg("Block Armor", "Block armor of " + englishName + ".", (SharedData val) => val.m_blockPower, delegate(SharedData val, float value) { val.m_blockPower = value; }); statcfg("Block Armor per Level", "Block armor per level for " + englishName + ".", (SharedData val) => val.m_blockPowerPerLevel, delegate(SharedData val, float value) { val.m_blockPowerPerLevel = value; }); statcfg("Block Force", "Block force of " + englishName + ".", (SharedData val) => val.m_deflectionForce, delegate(SharedData val, float value) { val.m_deflectionForce = value; }); statcfg("Block Force per Level", "Block force per level for " + englishName + ".", (SharedData val) => val.m_deflectionForcePerLevel, delegate(SharedData val, float value) { val.m_deflectionForcePerLevel = value; }); statcfg("Parry Bonus", "Parry bonus of " + englishName + ".", (SharedData val) => val.m_timedBlockBonus, delegate(SharedData val, float value) { val.m_timedBlockBonus = value; }); } else if ((itemType - 6 <= 1 || itemType - 11 <= 1 || (int)itemType == 17) ? true : false) { statcfg("Armor", "Armor of " + englishName + ".", (SharedData val) => val.m_armor, delegate(SharedData val, float value) { val.m_armor = value; }); statcfg("Armor per Level", "Armor per level for " + englishName + ".", (SharedData val) => val.m_armorPerLevel, delegate(SharedData val, float value) { val.m_armorPerLevel = value; }); } SkillType skillType = shared.m_skillType; if (((int)skillType == 7 || (int)skillType == 12) ? true : false) { statcfg("Tool tier", "Tool tier of " + englishName + ".", (SharedData val) => val.m_toolTier, delegate(SharedData val, int value) { val.m_toolTier = value; }); } if ((itemType - 5 <= 2 || itemType - 11 <= 1 || (int)itemType == 17) ? true : false) { Dictionary modifiers = shared.m_damageModifiers.ToDictionary((DamageModPair d) => d.m_type, (DamageModPair d) => (DamageModifier)d.m_modifier); DamageType[] first = (DamageType[])Enum.GetValues(typeof(DamageType)); DamageType[] array = new DamageType[5]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); foreach (DamageType damageType in first.Except((IEnumerable)(object)array)) { statcfg(((object)Unsafe.As(ref damageType)/*cast due to .constrained prefix*/).ToString() + " Resistance", ((object)Unsafe.As(ref damageType)/*cast due to .constrained prefix*/).ToString() + " resistance of " + englishName + ".", (SharedData _) => (!modifiers.TryGetValue(damageType, out var value)) ? DamageModifier.None : value, delegate(SharedData val2, DamageModifier value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) DamageModPair val = new DamageModPair { m_type = damageType, m_modifier = (DamageModifier)value }; for (int i = 0; i < val2.m_damageModifiers.Count; i++) { if (val2.m_damageModifiers[i].m_type == damageType) { if (value == DamageModifier.None) { val2.m_damageModifiers.RemoveAt(i); } else { val2.m_damageModifiers[i] = val; } return; } } if (value != DamageModifier.None) { val2.m_damageModifiers.Add(val); } }); } } if ((int)itemType == 2 && shared.m_food > 0f) { statcfg("Health", "Health value of " + englishName + ".", (SharedData val) => val.m_food, delegate(SharedData val, float value) { val.m_food = value; }); statcfg("Stamina", "Stamina value of " + englishName + ".", (SharedData val) => val.m_foodStamina, delegate(SharedData val, float value) { val.m_foodStamina = value; }); statcfg("Eitr", "Eitr value of " + englishName + ".", (SharedData val) => val.m_foodEitr, delegate(SharedData val, float value) { val.m_foodEitr = value; }); statcfg("Duration", "Duration of " + englishName + ".", (SharedData val) => val.m_foodBurnTime, delegate(SharedData val, float value) { val.m_foodBurnTime = value; }); statcfg("Health Regen", "Health regen value of " + englishName + ".", (SharedData val) => val.m_foodRegen, delegate(SharedData val, float value) { val.m_foodRegen = value; }); } if ((int)shared.m_skillType == 10) { statcfg("Health Cost", "Health cost of " + englishName + ".", (SharedData val) => val.m_attack.m_attackHealth, delegate(SharedData val, float value) { val.m_attack.m_attackHealth = value; }); statcfg("Health Cost Percentage", "Health cost percentage of " + englishName + ".", (SharedData val) => val.m_attack.m_attackHealthPercentage, delegate(SharedData val, float value) { val.m_attack.m_attackHealthPercentage = value; }); } skillType = shared.m_skillType; if (skillType - 9 <= 1) { statcfg("Eitr Cost", "Eitr cost of " + englishName + ".", (SharedData val) => val.m_attack.m_attackEitr, delegate(SharedData val, float value) { val.m_attack.m_attackEitr = value; }); } if ((itemType - 3 <= 1 || (int)itemType == 14 || (int)itemType == 22) ? true : false) { statcfg("Knockback", "Knockback of " + englishName + ".", (SharedData val) => val.m_attackForce, delegate(SharedData val, float value) { val.m_attackForce = value; }); statcfg("Backstab Bonus", "Backstab bonus of " + englishName + ".", (SharedData val) => val.m_backstabBonus, delegate(SharedData val, float value) { val.m_backstabBonus = value; }); statcfg("Attack Stamina", "Attack stamina of " + englishName + ".", (SharedData val) => val.m_attack.m_attackStamina, delegate(SharedData val, float value) { val.m_attack.m_attackStamina = value; }); SetDmg("True", (DamageTypes dmg) => dmg.m_damage, delegate(ref DamageTypes dmg, float val) { dmg.m_damage = val; }); SetDmg("Slash", (DamageTypes dmg) => dmg.m_slash, delegate(ref DamageTypes dmg, float val) { dmg.m_slash = val; }); SetDmg("Pierce", (DamageTypes dmg) => dmg.m_pierce, delegate(ref DamageTypes dmg, float val) { dmg.m_pierce = val; }); SetDmg("Blunt", (DamageTypes dmg) => dmg.m_blunt, delegate(ref DamageTypes dmg, float val) { dmg.m_blunt = val; }); SetDmg("Chop", (DamageTypes dmg) => dmg.m_chop, delegate(ref DamageTypes dmg, float val) { dmg.m_chop = val; }); SetDmg("Pickaxe", (DamageTypes dmg) => dmg.m_pickaxe, delegate(ref DamageTypes dmg, float val) { dmg.m_pickaxe = val; }); SetDmg("Fire", (DamageTypes dmg) => dmg.m_fire, delegate(ref DamageTypes dmg, float val) { dmg.m_fire = val; }); SetDmg("Poison", (DamageTypes dmg) => dmg.m_poison, delegate(ref DamageTypes dmg, float val) { dmg.m_poison = val; }); SetDmg("Frost", (DamageTypes dmg) => dmg.m_frost, delegate(ref DamageTypes dmg, float val) { dmg.m_frost = val; }); SetDmg("Lightning", (DamageTypes dmg) => dmg.m_lightning, delegate(ref DamageTypes dmg, float val) { dmg.m_lightning = val; }); SetDmg("Spirit", (DamageTypes dmg) => dmg.m_spirit, delegate(ref DamageTypes dmg, float val) { dmg.m_spirit = val; }); if ((int)itemType == 4) { statcfg("Projectiles", "Number of projectiles that " + englishName + " shoots at once.", (SharedData val) => val.m_attack.m_projectileBursts, delegate(SharedData val, int value) { val.m_attack.m_projectileBursts = value; }); statcfg("Burst Interval", "Time between the projectiles " + englishName + " shoots at once.", (SharedData val) => val.m_attack.m_burstInterval, delegate(SharedData val, float value) { val.m_attack.m_burstInterval = value; }); statcfg("Minimum Accuracy", "Minimum accuracy for " + englishName + ".", (SharedData val) => val.m_attack.m_projectileAccuracyMin, delegate(SharedData val, float value) { val.m_attack.m_projectileAccuracyMin = value; }); statcfg("Accuracy", "Accuracy for " + englishName + ".", (SharedData val) => val.m_attack.m_projectileAccuracy, delegate(SharedData val, float value) { val.m_attack.m_projectileAccuracy = value; }); statcfg("Minimum Velocity", "Minimum velocity for " + englishName + ".", (SharedData val) => val.m_attack.m_projectileVelMin, delegate(SharedData val, float value) { val.m_attack.m_projectileVelMin = value; }); statcfg("Velocity", "Velocity for " + englishName + ".", (SharedData val) => val.m_attack.m_projectileVel, delegate(SharedData val, float value) { val.m_attack.m_projectileVel = value; }); statcfg("Maximum Draw Time", "Time until " + englishName + " is fully drawn at skill level 0.", (SharedData val) => val.m_attack.m_drawDurationMin, delegate(SharedData val, float value) { val.m_attack.m_drawDurationMin = value; }); statcfg("Stamina Drain", "Stamina drain per second while drawing " + englishName + ".", (SharedData val) => val.m_attack.m_drawStaminaDrain, delegate(SharedData val, float value) { val.m_attack.m_drawStaminaDrain = value; }); } } } List traderAttributes; if ((item.configurability & Configurability.Trader) != Configurability.Disabled) { traderAttributes = new List(); ConfigEntry configEntry2 = null; ConfigSyncBase.SyncedConfig(englishName, "Trader Selling", item.Trade.Trader, new ConfigDescription("Which traders sell " + englishName + ".", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), Browsable = ((item.configurationVisible & Configurability.Trader) != 0), Category = localizedName } }), ref configEntry2); item.traderConfig = new TraderConfig { trader = configEntry2 }; item.traderConfig.trader.SettingChanged += delegate { item.ReloadTraderConfiguration(); foreach (ConfigurationManagerAttributes item8 in traderAttributes) { item8.Browsable = TraderBrowsability(); } reloadConfigDisplay(); }; item.traderConfig.price = traderConfig("Trader Price", item.Trade.Price, "Price of " + englishName + " at the trader."); item.traderConfig.stack = traderConfig("Trader Stack", item.Trade.Stack, "Stack size of " + englishName + " in the trader. Also known as the number of items sold by a trader in one transaction."); item.traderConfig.requiredGlobalKey = traderConfig("Trader Required Global Key", item.Trade.RequiredGlobalKey ?? "", "Required global key to unlock " + englishName + " at the trader."); if (item.traderConfig.trader.Value != Trader.None) { PrefabManager.AddItemToTrader(item.Prefab, item.traderConfig.trader.Value, item.traderConfig.price.Value, item.traderConfig.stack.Value, item.traderConfig.requiredGlobalKey.Value); } } else if (item.Trade.Trader != Trader.None) { PrefabManager.AddItemToTrader(item.Prefab, item.Trade.Trader, item.Trade.Price, item.Trade.Stack, item.Trade.RequiredGlobalKey); } void SetDmg(string dmgType, Func readDmg, setDmgFunc setDmg) { statcfg(dmgType + " Damage", dmgType + " damage dealt by " + englishName + ".", (SharedData val) => readDmg(val.m_damages), delegate(SharedData val2, float val) { setDmg(ref val2.m_damages, val); }); statcfg(dmgType + " Damage Per Level", dmgType + " damage dealt increase per level for " + englishName + ".", (SharedData val) => readDmg(val.m_damagesPerLevel), delegate(SharedData val2, float val) { setDmg(ref val2.m_damagesPerLevel, val); }); } bool TraderBrowsability() { return item.traderConfig.trader.Value != Trader.None; } void statcfg(string configName, string description, Func readDefault, Action setValue) where T : notnull { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown SharedData shared2 = item.Prefab.GetComponent().m_itemData.m_shared; ConfigEntry cfg2 = null; ConfigSyncBase.SyncedConfig(englishName, configName, readDefault(shared2), new ConfigDescription(description, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Stats) != 0) } }), ref cfg2); if ((item.configurationVisible & Configurability.Stats) != Configurability.Disabled) { setValue(shared2, cfg2.Value); } item.statsConfigs.Add((ConfigEntryBase)(object)cfg2, ApplyConfig); cfg2.SettingChanged += delegate { if ((item.configurationVisible & Configurability.Stats) != Configurability.Disabled) { ApplyConfig(); } }; void ApplyConfig() { item.ApplyToAllInstances(delegate(ItemData val) { setValue(val.m_shared, cfg2.Value); }); } } ConfigEntry traderConfig(string name, T value, string desc) where T : notnull { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = TraderBrowsability, Browsable = (TraderBrowsability() && (item.configurationVisible & Configurability.Trader) != 0), Category = localizedName }; traderAttributes.Add(configurationManagerAttributes2); ConfigEntry configEntry3 = null; ConfigSyncBase.SyncedConfig(englishName, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes2 }), ref configEntry3); configEntry3.SettingChanged += delegate { item.ReloadTraderConfiguration(); }; return configEntry3; } } if (saveOnConfigSet) { plugin.Config.SaveOnConfigSet = true; plugin.Config.Save(); } } configManager = ((type == null) ? null : Chainloader.ManagerObject.GetComponent(type)); foreach (Item registeredItem in registeredItems) { Item item2 = registeredItem; foreach (KeyValuePair recipe in item2.Recipes) { KeyValuePair kv = recipe; RequiredResourceList[] array2 = new RequiredResourceList[2] { kv.Value.RequiredItems, kv.Value.RequiredUpgradeItems }; foreach (RequiredResourceList requiredResourceList in array2) { for (int num3 = 0; num3 < requiredResourceList.Requirements.Count; num3++) { ConfigEntry amountCfg; int resourceIndex; if ((item2.configurability & Configurability.Recipe) != Configurability.Disabled) { amountCfg = requiredResourceList.Requirements[num3].amountConfig; if (amountCfg != null) { resourceIndex = num3; amountCfg.SettingChanged += ConfigChanged2; } } void ConfigChanged2(object o, EventArgs e) { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(item2) && activeRecipes[item2].TryGetValue(kv.Key, out List value)) { foreach (Recipe item9 in value) { item9.m_resources[resourceIndex].m_amount = amountCfg.Value; } } } } } } item2.InitializeNewRegisteredItem(); } } private void InitializeNewRegisteredItem() { foreach (KeyValuePair recipe in Recipes) { KeyValuePair kv = recipe; ConfigEntryBase enabledCfg = kv.Value.RecipeIsActive; if (enabledCfg != null) { ((object)enabledCfg).GetType().GetEvent("SettingChanged").AddEventHandler(enabledCfg, new EventHandler(ConfigChanged)); } void ConfigChanged(object o, EventArgs e) { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(kv.Key, out List value)) { foreach (Recipe item in value) { item.m_enabled = (int)enabledCfg.BoxedValue != 0; } } } } } public void ReloadCraftingConfiguration() { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && ObjectDB.instance.GetItemPrefab(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name)) == null) { registerRecipesInObjectDB(ObjectDB.instance); ObjectDB.instance.m_items.Add(Prefab); ObjectDB.instance.m_itemByHash.Add(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name), Prefab); ZNetScene.instance.m_prefabs.Add(Prefab); ZNetScene.instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name), Prefab); } foreach (string item in Recipes.Keys.DefaultIfEmpty("")) { if (Recipes.TryGetValue(item, out ItemRecipe value) && value.Crafting.Stations.Count > 0) { UpdateItemTableConfig(item, value.Crafting.Stations.First().Table, value.Crafting.Stations.First().custom ?? ""); UpdateCraftConfig(item, new SerializedRequirements(value.RequiredItems.Requirements), new SerializedRequirements(value.RequiredUpgradeItems.Requirements)); } } } private void ReloadTraderConfiguration() { if (traderConfig.trader.Value == Trader.None) { PrefabManager.RemoveItemFromTrader(Prefab); } else { PrefabManager.AddItemToTrader(Prefab, traderConfig.trader.Value, traderConfig.price.Value, traderConfig.stack.Value, traderConfig.requiredGlobalKey.Value); } } public static void ApplyToAllInstances(GameObject prefab, Action callback) { callback(prefab.GetComponent().m_itemData); string name = prefab.GetComponent().m_itemData.m_shared.m_name; Inventory[] source = (from c in Player.s_players.Select((Player p) => ((Humanoid)p).GetInventory()).Concat(from c in Object.FindObjectsByType((FindObjectsInactive)1, (FindObjectsSortMode)1) select c.GetInventory()) where c != null select c).ToArray(); foreach (ItemData item in (from i in (from p in ObjectDB.instance.m_items select p.GetComponent() into c where Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((Component)c).GetComponent()) select c).Concat(ItemDrop.s_instances) select i.m_itemData).Concat(source.SelectMany((Inventory i) => i.GetAllItems()))) { if (item.m_shared.m_name == name) { callback(item); } } } public void ApplyToAllInstances(Action callback) { ApplyToAllInstances(Prefab, callback); } private static string getInternalName(T value) where T : struct { return ((InternalName)typeof(T).GetMember(value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName; } private void registerRecipesInObjectDB(ObjectDB objectDB) { //IL_045a: Unknown result type (might be due to invalid IL or missing references) //IL_045f: Unknown result type (might be due to invalid IL or missing references) //IL_0492: Unknown result type (might be due to invalid IL or missing references) //IL_04a8: Expected O, but got Unknown activeRecipes[this] = new Dictionary>(); itemCraftConfigs.TryGetValue(this, out Dictionary value); foreach (KeyValuePair recipe in Recipes) { List list = new List(); foreach (CraftingStationConfig station in recipe.Value.Crafting.Stations) { ItemConfig itemConfig = value?[recipe.Key]; Recipe val = ScriptableObject.CreateInstance(); string name = ((Object)Prefab).name; CraftingTable table = station.Table; ((Object)val).name = name + "_Recipe_" + table; val.m_amount = recipe.Value.CraftAmount; ConfigEntryBase? recipeIsActive = recipe.Value.RecipeIsActive; val.m_enabled = (int)(((recipeIsActive != null) ? recipeIsActive.BoxedValue : null) ?? ((object)1)) != 0 && (itemConfig == null || itemConfig.table.Value != CraftingTable.Disabled); val.m_item = Prefab.GetComponent(); val.m_resources = SerializedRequirements.toPieceReqs(objectDB, (itemConfig?.craft == null) ? new SerializedRequirements(recipe.Value.RequiredItems.Requirements) : new SerializedRequirements(itemConfig.craft.Value), (itemConfig?.upgrade == null) ? new SerializedRequirements(recipe.Value.RequiredUpgradeItems.Requirements) : new SerializedRequirements(itemConfig.upgrade.Value)); table = ((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value); if ((uint)table <= 1u) { val.m_craftingStation = null; } else if (((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value) == CraftingTable.Custom) { GameObject prefab = ZNetScene.instance.GetPrefab((itemConfig == null || list.Count > 0) ? station.custom : itemConfig.customTable.Value); if (prefab != null) { val.m_craftingStation = prefab.GetComponent(); } else { Debug.LogWarning((object)("Custom crafting station '" + ((itemConfig == null || list.Count > 0) ? station.custom : itemConfig.customTable.Value) + "' does not exist")); } } else { val.m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value)).GetComponent(); } val.m_minStationLevel = ((itemConfig == null || list.Count > 0) ? station.level : itemConfig.tableLevel.Value); val.m_requireOnlyOneIngredient = ((itemConfig == null) ? recipe.Value.RequireOnlyOneIngredient : (itemConfig.requireOneIngredient.Value == Toggle.On)); val.m_qualityResultAmountMultiplier = itemConfig?.qualityResultAmountMultiplier.Value ?? recipe.Value.QualityResultAmountMultiplier; list.Add(val); RequiredResourceList requiredItems; if (station.Table != CraftingTable.Disabled) { requiredItems = recipe.Value.RequiredItems; if (requiredItems != null && !requiredItems.Free) { List requirements = requiredItems.Requirements; if (requirements != null && requirements.Count == 0) { hiddenCraftRecipes.Add(val, recipe.Value.RecipeIsActive); } } } requiredItems = recipe.Value.RequiredUpgradeItems; if (requiredItems != null && !requiredItems.Free) { List requirements = requiredItems.Requirements; if (requirements != null && requirements.Count == 0) { hiddenUpgradeRecipes.Add(val, recipe.Value.RecipeIsActive); } } } activeRecipes[this].Add(recipe.Key, list); objectDB.m_recipes.AddRange(list); } conversions = new List(); for (int i = 0; i < Conversions.Count; i++) { Conversion conversion = Conversions[i]; conversions.Add(new ItemConversion { m_from = SerializedRequirements.fetchByName(ObjectDB.instance, conversion.config?.input.Value ?? conversion.Input), m_to = Prefab.GetComponent() }); ConversionPiece conversionPiece = conversion.config?.piece.Value ?? conversion.Piece; string text = null; if (conversionPiece != ConversionPiece.Disabled && conversions[i].m_from != null) { text = ((conversionPiece != ConversionPiece.Custom) ? getInternalName(conversionPiece) : (conversion.config?.customPiece.Value ?? conversion.customPiece)); GameObject prefab2 = ZNetScene.instance.GetPrefab(text); Smelter val2 = ((prefab2 != null) ? prefab2.GetComponent() : null); if (val2 != null) { val2.m_conversion.Add(conversions[i]); } else { text = null; } } if (conversion.config != null) { conversion.config.activePiece = text; } } } [HarmonyPriority(0)] internal static void Patch_ObjectDBInit(ObjectDB __instance) { if ((Object)(object)__instance.GetItemPrefab("Wood") == (Object)null) { return; } hiddenCraftRecipes.Clear(); hiddenUpgradeRecipes.Clear(); foreach (Item registeredItem in registeredItems) { registeredItem.registerRecipesInObjectDB(__instance); } } internal static void Patch_TraderGetAvailableItems(Trader __instance, ref List __result) { string prefabName = Utils.GetPrefabName(((Component)__instance).gameObject); Trader trader = ((prefabName == "Haldor") ? Trader.Haldor : ((prefabName == "Hildir") ? Trader.Hildir : Trader.None)); Trader trader2 = trader; __result.AddRange(from tuple in PrefabManager.CustomTradeItems.Values where (tuple.Item1 & trader2) != 0 select tuple.Item2 into tradeItem where string.IsNullOrEmpty(tradeItem.m_requiredGlobalKey) || ZoneSystem.instance.GetGlobalKey(tradeItem.m_requiredGlobalKey) select tradeItem); } internal static void Patch_OnAddSmelterInput(ItemData item, bool __result) { if (__result) { ((Humanoid)Player.m_localPlayer).UnequipItem(item, true); } } internal static void Patch_MaximumRequiredStationLevel(Recipe __instance, ref int __result, int quality) { if (!itemDropMap.TryGetValue(__instance.m_item, out Item value)) { return; } IEnumerable source; if (!itemCraftConfigs.TryGetValue(value, out Dictionary value2)) { source = Enumerable.Empty(); } else { CraftingStation currentCraftingStation = Player.m_localPlayer.GetCurrentCraftingStation(); if (currentCraftingStation != null) { string stationName = Utils.GetPrefabName(((Component)currentCraftingStation).gameObject); source = from c in value2.Where(delegate(KeyValuePair c) { switch (c.Value.table.Value) { case CraftingTable.Disabled: case CraftingTable.Inventory: return false; case CraftingTable.Custom: return c.Value.customTable.Value == stationName; default: return getInternalName(c.Value.table.Value) == stationName; } }) select c.Value; } else { source = value2.Values; } } __result = Mathf.Min(Mathf.Max(1, __instance.m_minStationLevel) + (quality - 1), (from cfg in source where cfg.maximumTableLevel != null select cfg.maximumTableLevel.Value).DefaultIfEmpty(value.MaximumRequiredStationLevel).Max()); } internal static void Patch_GetAvailableRecipesPrefix(ref Dictionary>? __state) { if (__state == null) { __state = new Dictionary>(); } Dictionary source; if (InventoryGui.instance.InCraftTab()) { source = hiddenCraftRecipes; } else { if (!InventoryGui.instance.InUpradeTab()) { return; } source = hiddenUpgradeRecipes; } List list = (from kv in source select kv.Key into r where r.m_enabled select r).ToList(); __state[Assembly.GetExecutingAssembly()] = list; foreach (Recipe item in list) { item.m_enabled = false; } } internal static void Patch_GetAvailableRecipesFinalizer(Dictionary> __state) { if (!__state.TryGetValue(Assembly.GetExecutingAssembly(), out List value)) { return; } foreach (Recipe item in value) { item.m_enabled = true; } } internal static IEnumerable Transpile_SetupRequirementList(IEnumerable instructionsEnumerable, ILGenerator ilg) { //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Expected O, but got Unknown //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Expected O, but got Unknown //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Expected O, but got Unknown //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Expected O, but got Unknown //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Expected O, but got Unknown //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Expected O, but got Unknown //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Expected O, but got Unknown //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Expected O, but got Unknown //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Expected O, but got Unknown //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Expected O, but got Unknown //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Expected O, but got Unknown List list = instructionsEnumerable.ToList(); MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(InventoryGui), "SetupRequirement", (Type[])null, (Type[])null); CodeInstruction val = null; CodeInstruction val2 = null; LocalBuilder localBuilder = ilg.DeclareLocal(typeof(int)); Dictionary dictionary = new Dictionary(); bool flag = false; int num = 0; int value = 0; Label? label = default(Label?); for (int i = 0; i < list.Count; i++) { if (CodeInstructionExtensions.Calls(list[i], methodInfo)) { val = list[i + 2]; val2 = list[i + 5]; flag = true; } if (flag) { if (CodeInstructionExtensions.Branches(list[i], ref label) && dictionary.TryGetValue(label.Value, out value)) { num = i; break; } continue; } foreach (Label label4 in list[i].labels) { dictionary[label4] = i; } } if (list[value - 3].opcode == OpCodes.Dup) { return list; } Label label2 = ilg.DefineLabel(); Label label3 = ilg.DefineLabel(); list[num + 1].labels.Add(label2); list.InsertRange(num + 1, (IEnumerable)(object)new CodeInstruction[11] { new CodeInstruction(OpCodes.Ldloc, (object)localBuilder), new CodeInstruction(OpCodes.Brfalse, (object)label2), val.Clone(), new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldfld, (object)AccessTools.DeclaredField(typeof(InventoryGui), "m_recipeRequirementList")), new CodeInstruction(OpCodes.Ldlen, (object)null), new CodeInstruction(OpCodes.Bgt, (object)label2), new CodeInstruction(OpCodes.Ldc_I4_0, (object)null), val2.Clone(), new CodeInstruction(OpCodes.Ldc_I4_0, (object)null), new CodeInstruction(OpCodes.Br, (object)label3) }); list.InsertRange(value - 2, (IEnumerable)(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Dup, (object)null) { labels = new List