Decompiled source of AdventureBackpacks v1.7.9
plugins/AdventureBackpacks.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; 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 Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using ServerSync; 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; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: AssemblyFileVersion("1.7.9.0")] [assembly: Guid("997CB563-FCC7-44B7-8F71-069747D27CC5")] [assembly: ComVisible(false)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCopyright("Copyright © 2024")] [assembly: AssemblyProduct("AdventureBackpacks")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyDescription("A Valheim Mod for adding progression multiple backpacks as an item/utility gear addition.")] [assembly: AssemblyTitle("AdventureBackpacks")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("Vapok Gaming")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.7.9.0")] [module: <bb952182-7c3e-455d-9c92-a673e1671bfa>RefSafetyRules(11)] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<5ad991da-451b-49b6-b495-a1909d96c371>Embedded] internal sealed class <5ad991da-451b-49b6-b495-a1909d96c371>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [<5ad991da-451b-49b6-b495-a1909d96c371>Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class <bb952182-7c3e-455d-9c92-a673e1671bfa>RefSafetyRulesAttribute : Attribute { public readonly int Version; public <bb952182-7c3e-455d-9c92-a673e1671bfa>RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace AdventureBackpacks { [BepInPlugin("vapok.mods.adventurebackpacks", "Adventure Backpacks", "1.7.9")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInIncompatibility("JotunnBackpacks")] 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.7.9"; 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.7.9"; public BaseUnityPlugin Instance => (BaseUnityPlugin)(object)_instance; public static ILogIt Log => _log; public static ConfigSyncBase ActiveConfig => _config; [UsedImplicitly] private void Awake() { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown _instance = this; Patcher.Patch(new string[1] { "AdventureBackpacks.API" }); Waiter = new Waiting(); Initializer.LoadManagers(enableCreatureManager: false, enableItemManager: true, enableLocationManager: true, enableMaterialReplacer: true, enablePieceManager: false, enableSkillManager: false, enableEffectManager: true, enableLocalizationManager: true); _config = new ConfigRegistry(_instance); LogManager.Init(PluginId, out _log); 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_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007c: 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(); } } InventoryPatches.ProcessItemsAddedQueue(); } public void InitializeBackpacks(object send, EventArgs args) { if (!ValheimAwake) { new EffectsFactory(_log, _config).RegisterEffects(); new BackpackFactory(_log, _config).CreateAssets(); 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<RecipeIngredient> RecipeIngredients = new List<RecipeIngredient>(); public readonly List<RecipeIngredient> UpgradeIngredients = new List<RecipeIngredient>(); public readonly List<DropTarget> DropsFrom = new List<DropTarget>(); public readonly Dictionary<BackpackBiomes, KeyValuePair<StatusEffect, int>> EffectsToApply = new Dictionary<BackpackBiomes, KeyValuePair<StatusEffect, int>>(); public Dictionary<int, Vector2> BackpackSizeByQuality = new Dictionary<int, Vector2>(); 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<StatusEffect> GetActiveBackpackStatusEffects() { return EquipmentEffectCache.ActiveEffects; } public static HashSet<StatusEffect> 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; } Backpack value = default(Backpack); value.Name = backPackDefinitionFromComponent.ItemName; value.ItemData = component.Item; value.Definition = backPackDefinitionFromComponent; value.Inventory = component.GetInventory(); return value; } private static Backpack? ConvertBackpackItem(ItemData itemData) { if (!itemData.IsBackpack()) { return null; } return ConvertBackpackItem(itemData.Data().GetOrCreate<BackpackComponent>()); } private static Dictionary<int, Vector2> GetBackpackSizing(BackpackItem backpack) { return backpack.BackpackSize.ToDictionary((KeyValuePair<int, ConfigEntry<Vector2>> entry) => entry.Key, (KeyValuePair<int, ConfigEntry<Vector2>> 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<SE_Stats>(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", "Assets.Bundles"); 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<StatusEffect, int>(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(ArmorStand __instance) { AdventureBackpacks.BypassMoveProtection = true; } private static void Postfix(ArmorStand __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<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator ilGenerator) { bool patchedSuccess = false; List<CodeInstruction> 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 { [HarmonyPriority(800)] [UsedImplicitly] 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 { [HarmonyPriority(800)] [UsedImplicitly] 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 { [HarmonyBefore(new string[] { "org.bepinex.helpers.ItemManager" })] [HarmonyAfter(new string[] { "org.bepinex.helpers.LocalizationManager" })] [HarmonyPatch(typeof(FejdStartup), "Start")] public static class FejdStartupAwakePatch { private static void Postfix() { AdventureBackpacks.Waiter.ValheimIsAwake(awakeFlag: true); } } } 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<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { bool patchedSuccess = false; List<CodeInstruction> 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 (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_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0090: 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 (instance.IsContainerOpen()) { instance.CloseContainer(); InventoryGuiPatches.BackpackIsOpen = false; } ((Component)localPlayer).gameObject.GetComponent<Container>().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_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (__0 == null || ((Object)(object)Player.m_localPlayer == (Object)null && !__result)) { return; } Scene activeScene = SceneManager.GetActiveScene(); if (!((Scene)(ref activeScene)).name.Equals("start")) { Player localPlayer = Player.m_localPlayer; if (__0.IsBackpack()) { InventoryGuiPatches.BackpackEquipped = true; Container component = ((Component)localPlayer).gameObject.GetComponent<Container>(); __0.Data().GetOrCreate<BackpackComponent>().UpdateContainerSizing(component); } } } } } 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) && __instance.IsBackPackInventory()) { Player.m_localPlayer.GetEquippedBackpack()?.Save(); } } } [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; } } [HarmonyPriority(800)] [HarmonyPatch(typeof(Humanoid), "DropItem", new Type[] { typeof(Inventory), typeof(ItemData), typeof(int) })] 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 void Prefix(Inventory __instance, ItemData item) { if (item != null && __instance != null) { RemoveItemPrefix(__instance, item); } } } [HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(ItemData), typeof(int) })] [HarmonyPriority(800)] private static class RemoveItem2Patch { private static void Prefix(Inventory __instance, ItemData item) { if (item != null && __instance != null) { RemoveItemPrefix(__instance, item); } } } [HarmonyPatch(typeof(Inventory), "RemoveOneItem", new Type[] { typeof(ItemData) })] [HarmonyPriority(800)] private static class RemoveItem3Patch { private static void Prefix(Inventory __instance, ItemData item) { if (item != null && __instance != null) { RemoveItemPrefix(__instance, item); } } } [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<ItemData, DateTime>(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; } } [HarmonyPriority(800)] [HarmonyPatch(typeof(Inventory), "MoveAll", new Type[] { typeof(Inventory) })] 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<ItemData> 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<BackpackComponent>().GetInventory() .IsTeleportable()) { __result = false; break; } } } } private static void Postfix(Inventory __instance) { if (__instance != null && !((Object)(object)Player.m_localPlayer == (Object)null)) { Player localPlayer = Player.m_localPlayer; if (__instance.IsBackPackInventory() && Object.op_Implicit((Object)(object)localPlayer)) { ((Humanoid)localPlayer).GetInventory().UpdateTotalWeight(); } } } } private static bool _movingItemBetweenContainers; private static bool _droppingOutside; private static readonly Queue<KeyValuePair<ItemData, DateTime>> ItemsAddedQueue = new Queue<KeyValuePair<ItemData, DateTime>>(); private static bool IsItemFromQueue(this ItemData item) { if (ItemsAddedQueue.Any((KeyValuePair<ItemData, DateTime> 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 void RemoveItemPrefix(Inventory __instance, ItemData item) { if (__instance == null || (Object)(object)Player.m_localPlayer == (Object)null || _movingItemBetweenContainers || _droppingOutside || AdventureBackpacks.PerformYardSale || AdventureBackpacks.QuickDropping || AdventureBackpacks.BypassMoveProtection || !item.TryGetBackpackItem(out var _)) { return; } 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; } BackpackComponent backpackComponent = item.Data().Get<BackpackComponent>(); if (backpackComponent != null) { Inventory inventory = backpackComponent.GetInventory(); if (inventory != null && inventory.m_inventory.Count > 0) { Backpacks.PerformYardSale(Player.m_localPlayer, item, backpackOnly: true); } } } } internal static class InventoryGuiPatches { [HarmonyPatch(typeof(InventoryGui), "DoCrafting")] private static class InventoryGuiDoCraftingPrefix { [UsedImplicitly] private static void Postfix(InventoryGui __instance) { if ((Object)(object)Player.m_localPlayer == (Object)null) { return; } Player localPlayer = Player.m_localPlayer; if (__instance.m_craftUpgradeItem == null || !__instance.m_craftUpgradeItem.IsBackpack()) { return; } BackpackComponent backpackComponent = __instance.m_craftUpgradeItem.Data().Get<BackpackComponent>(); if (backpackComponent != null) { Container component = ((Component)localPlayer).gameObject.GetComponent<Container>(); backpackComponent?.Load(); if (localPlayer.IsThisBackpackEquipped(backpackComponent.Item)) { backpackComponent?.UpdateContainerSizing(component); } ((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 && grid.GetInventory() != null && (Object)(object)Player.m_localPlayer != (Object)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<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator ilGenerator) { List<CodeInstruction> 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 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) { 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 label2 = (Label)instrs[i + 1].operand; CodeInstruction val = FindInstructionWithLabel(instrs, i + 2, label2); if (val == null) { AdventureBackpacks.Log.Error($"Can't Find Instruction with Label {label2}"); } else { i++; Label detectHideLabel2 = ilGenerator.DefineLabel(); val.labels.Add(detectHideLabel2); 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)detectHideLabel2)); 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 label3 = (Label)instrs[i + 1].operand; CodeInstruction val2 = FindInstructionWithLabel(instrs, i + 2, label3); if (val2 == null) { AdventureBackpacks.Log.Error($"Can't Find Instruction with Label {label3}"); } else { i++; Label detectHideLabel2 = ilGenerator.DefineLabel(); val2.labels.Add(detectHideLabel2); 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)detectHideLabel2)); 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<CodeInstruction> codeInstructions, int index, Label label) { if (index >= codeInstructions.Count) { return null; } if (codeInstructions[index].labels.Contains(label)) { return codeInstructions[index]; } return FindInstructionWithLabel(codeInstructions, index + 1, label); } 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<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { bool patchedSuccess = false; List<CodeInstruction> 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<InventoryGrid> list = new List<InventoryGrid>(); list.AddRange(((Component)instance.m_player).GetComponentsInChildren<InventoryGrid>()); 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) { float num = originalWeight; if (!string.IsNullOrEmpty(item.m_shared.m_name) && item.TryGetBackpackItem(out var backpack)) { Inventory inventory = item.Data().GetOrCreate<BackpackComponent>().GetInventory(); float num2 = ((inventory != null) ? inventory.GetTotalWeight() : 0f); num += num2 * backpack.WeightMultiplier.Value; } return num; } public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { bool patchedSuccess = false; List<CodeInstruction> 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; } } } } public class PlayerPatches { [HarmonyPatch(typeof(Player), "Awake")] private static class PlayerAwakePatch { private static void Postfix(Player __instance) { ((Component)__instance).gameObject.AddComponent<Container>(); } } [HarmonyPatch(typeof(Player), "HaveRequirementItems")] private static class PlayerHaveRequirementItemsPatch { public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator ilGenerator) { bool patchedSuccess = false; List<CodeInstruction> 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<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { bool patchedSuccess = false; List<CodeInstruction> 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; } string itemName = resource.m_resItem.m_itemData.m_shared.m_name; if (((Humanoid)player).GetInventory().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<ItemData> 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 i = 0; i < amount; i++) { 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; } } } } namespace AdventureBackpacks.Features { public static class EquipmentEffectCache { public static HashSet<StatusEffect> ActiveEffects = new HashSet<StatusEffect>(); public static HashSet<StatusEffect> AddActiveBackpackEffects(HashSet<StatusEffect> other, Humanoid instance) { if (other == null) { AdventureBackpacks.Log.Debug("other HashSet argument is null. Expecting initialized object."); other = new HashSet<StatusEffect>(); } Player val = (Player)(object)((instance is Player) ? instance : null); if (val != null && (Object)(object)val == (Object)(object)Player.m_localPlayer) { ActiveEffects = new HashSet<StatusEffect>(); foreach (KeyValuePair<BackpackEffect, EffectsBase> 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 { [HarmonyPriority(800)] [HarmonyPatch(typeof(InventoryGui), "OnRightClickItem")] 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; } } [HarmonyPriority(800)] [HarmonyPatch(typeof(Humanoid), "UseItem")] private static class UseItemPatch { private static bool Prefix(ItemData item) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (!_processingRightClick) { 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; private static InventoryGui _inventoryGuiInstance; private static Inventory _fromInventory; private static Inventory _toInventory; private static bool _processingRightClick; public static ConfigEntry<bool> EnableQuickTransfer { get; private set; } static QuickTransfer() { ConfigRegistry.Waiter.StatusChanged += delegate { RegisterConfiguraitonFile(); }; } private static void RegisterConfiguraitonFile() { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown EnableQuickTransfer = 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] { new Vapok.Common.Shared.ConfigurationManagerAttributes { Order = 5 } })); } } public static class Utilities { public static AssetBundle LoadAssetBundle(string filename, string folderName) { return ItemManager.PrefabManager.RegisterAssetBundle(filename, folderName); } } } namespace AdventureBackpacks.Extensions { public static class InventoryExtensions { public static bool IsBackPackInventory(this Inventory inventory) { return inventory.m_name.Contains("$vapok_mod_level"); } 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<BackpackComponent>(); } 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 component = ((Component)player).gameObject.GetComponent<Container>(); InventoryGuiPatches.BackpackIsOpen = true; instance.Show(component, 1); } } public static void QuickDropBackpack(this Player player) { //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_0119: 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); ((Humanoid)player).m_inventory.RemoveItem(equippedBackpack.Item); ItemDrop obj = ItemDrop.DropItem(equippedBackpack.Item, 1, ((Component)player).transform.position - ((Component)player).transform.forward + ((Component)player).transform.up, ((Component)player).transform.rotation); ((Component)obj).GetComponent<Rigidbody>().velocity = (Vector3.up - ((Component)player).transform.forward) * 5f; ((Humanoid)player).m_dropEffects.Create(((Component)player).transform.position, Quaternion.identity, (Transform)null, 1f, -1); obj.Save(); if (flag) { inventory.AddItem(val); } InventoryGuiPatches.BackpackIsOpen = false; AdventureBackpacks.QuickDropping = false; } } } namespace AdventureBackpacks.Configuration { public class ConfigRegistry : ConfigSyncBase { public static Waiting Waiter; internal static ConfigEntry<KeyboardShortcut> HotKeyOpen { get; private set; } internal static ConfigEntry<KeyboardShortcut> HotKeyDrop { get; private set; } internal static ConfigEntry<bool> OpenWithInventory { get; private set; } internal static ConfigEntry<bool> OpenWithHoverInteract { get; private set; } internal static ConfigEntry<bool> CloseInventory { get; private set; } internal static ConfigEntry<bool> OutwardMode { get; private set; } public ConfigRegistry(IPluginInfo mod) : base(mod) { Waiter = new Waiting(); InitializeConfigurationSettings(); } public sealed override void InitializeConfigurationSettings() { //IL_001e: 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) //IL_004d: Expected O, but got Unknown //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Expected O, but got Unknown //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Expected O, but got Unknown //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Expected O, but got Unknown //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Expected O, but got Unknown //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Expected O, but got Unknown if (ConfigSyncBase._config != null) { HotKeyOpen = ConfigSyncBase._config.Bind<KeyboardShortcut>("Local Config", "Open Backpack", new KeyboardShortcut((KeyCode)105, Array.Empty<KeyCode>()), new ConfigDescription("Hotkey to open backpack.", (AcceptableValueBase)null, new object[1] { new Vapok.Common.Shared.ConfigurationManagerAttributes { Order = 3 } })); HotKeyDrop = ConfigSyncBase._config.Bind<KeyboardShortcut>("Local Config", "Quickdrop Backpack", new KeyboardShortcut((KeyCode)121, Array.Empty<KeyCode>()), new ConfigDescription("Hotkey to quickly drop backpack while on the run.", (AcceptableValueBase)null, new object[1] { new Vapok.Common.Shared.ConfigurationManagerAttributes { Order = 1 } })); OpenWithInventory = ConfigSyncBase._config.Bind<bool>("Local Config", "Open with Inventory", false, new ConfigDescription("If enabled, both backpack and inventory will open when Inventory is opened.", (AcceptableValueBase)null, new object[1] { new Vapok.Common.Shared.ConfigurationManagerAttributes { Order = 3 } })); OpenWithHoverInteract = ConfigSyncBase._config.Bind<bool>("Local Config", "Open with Interactive Hover", 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] { new Vapok.Common.Shared.ConfigurationManagerAttributes { Order = 3 } })); CloseInventory = ConfigSyncBase._config.Bind<bool>("Local Config", "Close Inventory", 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] { new Vapok.Common.Shared.ConfigurationManagerAttributes { Order = 2 } })); OutwardMode = ConfigSyncBase._config.Bind<bool>("Local Config", "Outward Mode", 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] { new Vapok.Common.Shared.ConfigurationManagerAttributes { Order = 1 } })); } } } 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; private ILogIt _log = AdventureBackpacks.Log; public void SetInventory(Inventory inventoryInstance) { _backpackInventory = inventoryInstance; Save(_backpackInventory); } public Inventory GetInventory() { return _backpackInventory; } public void UpdateContainerSizing(Container backpackContainer) { Inventory val = (backpackContainer.m_inventory = GetInventory()); backpackContainer.m_width = val.m_width; backpackContainer.m_height = val.m_height; backpackContainer.m_bkg = base.Item.m_shared.m_icons[0]; } public string Serialize() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown _log.Debug("[Serialize()] 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()] Value = " + base.Value); return result; } public void Deserialize(string data) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown _log.Debug("[Deserialize()] Starting.."); try { string name = base.Item.m_shared.m_name; _backpackInventory = Backpacks.NewInventoryInstance(name, base.Item.m_quality); base.Value = data; _log.Debug("[Deserialize()] Value = " + base.Value); ZPackage val = new ZPackage(data); _backpackInventory.Load(val); _statusEffects = Backpacks.UpdateStatusEffects(base.Item); } catch (Exception arg) { _log.Error($"Backpack info is corrupt!\n{arg}"); } } public override void FirstLoad() { string name = base.Item.m_shared.m_name; _log.Debug("[FirstLoad] " + 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] Backpack null, creating..."); Serialize(); } } else if (string.IsNullOrEmpty(base.Value)) { Serialize(); } } public override void Load() { _log.Debug("[Load] Starting"); if (!string.IsNullOrEmpty(base.Value)) { _log.Debug("[Load] Value = " + base.Value); Deserialize(base.Value); return; } if (_backpackInventory == null) { _log.Debug("[Load] Backpack null, creating..."); string name = base.Item.m_shared.m_name; _backpackInventory = Backpacks.NewInventoryInstance(name, base.Item.m_quality); } Serialize(); } public override void Save() { _log.Debug("[Save()] Starting Value = " + base.Value); base.Value = Serialize(); } public void Save(Inventory backpack) { _log.Debug($"[Save(Inventory)] 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<string> _backpackTypes = new List<string>(); public static List<string> BackpackTypes => _backpackTypes; public static void LoadBackpackTypes(List<string> 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) { if (!((Object)(object)Player.m_localPlayer == (Object)null) && ((Humanoid)Player.m_localPlayer).GetInventory() != null) { InventoryGui.instance.Hide(); Inventory inventory2 = ((Humanoid)Player.m_localPlayer).GetInventory(); if (inventory2 != null) { SearchInventory(inventory2.m_inventory); } List<ItemData> equippedItems = ((Humanoid)Player.m_localPlayer).GetInventory().GetEquippedItems(); if (equippedItems != null) { SearchInventory(equippedItems); } ((Humanoid)Player.m_localPlayer).UpdateEquipmentStatusEffects(); } static void SearchInventory(List<ItemData> inventory) { if (inventory == null) { return; } foreach (ItemData item in inventory) { if (item != null && item.IsBackpack()) { item.Data().GetOrCreate<BackpackComponent>().Load(); } } } } 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 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 void PerformYardSale(Player mLocalPlayer, ItemData itemData, bool backpackOnly = false) { if (!itemData.IsBackpack()) { return; } BackpackComponent backpackComponent = itemData.Data().Get<BackpackComponent>(); if (backpackComponent != null) { EmtpyInventory(backpackComponent.GetInventory()); if (!backpackOnly) { Inventory inventory2 = ((Humanoid)mLocalPlayer).GetInventory(); EmtpyInventory(inventory2); ((Humanoid)mLocalPlayer).UnequipAllItems(); EmtpyInventory(inventory2); ((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); } } void EmtpyInventory(Inventory inventory) { _ = inventory.m_inventory.Count; while (inventory.m_inventory.Count > 0) { ItemData val = inventory.m_inventory[0]; int num = inventory.CountItems(val.m_shared.m_name, -1, true); ((Humanoid)mLocalPlayer).DropItem(inventory, val, num); } } } 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<DamageModPair> list = new List<DamageModPair>(); 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 string AssetName = "vapokbackpacks"; private string AssetFolderName = "Assets.Bundles"; private string _prefabName; private string _itemName; private Item _item; public string PrefabName => _prefabName; public string ItemName => _itemName; 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 prefabName, string itemName) { _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<ItemManager.CraftingTable>(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<ItemDrop>(); } internal void RegisterShaderSwap(MaterialReplacer.ShaderType shaderType = MaterialReplacer.ShaderType.PieceShader) { MaterialReplacer.RegisterGameObjectForShaderSwap(_item.Prefab, shaderType); } internal void SetPersistence() { _item.Prefab.GetComponent<ZNetView>().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 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; private Localization _english; public System.Timers.Timer InceptionTimer; public System.Timers.Timer YardSaleTimer; private int _inceptionCounter; private Localization english => _english ?? (_english = ItemManager.LocalizationCache.ForLanguage("English")); public int InceptionCounter { get { return _inceptionCounter; } set { _inceptionCounter = value; if (value > 0) { InceptionTimer.Stop(); InceptionTimer.Start(); } } } internal Dictionary<int, ConfigEntry<Vector2>> BackpackSize { get; private set; } internal ConfigEntry<float> WeightMultiplier { get; private set; } internal ConfigEntry<int> CarryBonus { get; private set; } internal ConfigEntry<float> SpeedMod { get; private set; } internal ConfigEntry<bool> EnableFreezing { get; private set; } internal ConfigEntry<bool> ShowBackpackStatusEffect { get; private set; } internal ConfigEntry<string> CustomStatusEffectName { get; private set; } internal ConfigEntry<BackpackBiomes> BackpackBiome { get; private set; } 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 prefabName, string itemName, string configSection = "", bool externalLocalize = false) : base(prefabName, itemName) { _configSection = (string.IsNullOrEmpty(configSection) ? ("Backpack: " + itemName) : configSection); _englishSection = english.Localize(_configSection); if (externalLocalize) { _localizedCategory = Localization.m_instance.Localize(_configSection); } else { _localizedCategory = Localization.instance.Localize(_configSection); } SetupBackpackDef(); } internal void SetupLocalization() { _englishSection = english.Localize(_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<int, ConfigEntry<Vector2>>(); 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_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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, 8), (int)BackpackSize[quality].Value.y); } internal abstract void UpdateStatusEffects(int quality, CustomSE statusEffects, List<DamageModPair> modifierList, ItemData itemData); internal virtual void RegisterBackpackSize(int quality = 1, int x = 6, int y = 3) { //IL_0021: 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_005d: Expected O, but got Unknown BackpackSize.Add(quality, ConfigSyncBase.SyncedConfig<Vector2>(_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] { new Vapok.Common.Shared.ConfigurationManagerAttributes { Category = _localizedCategory, Order = 3 } }))); BackpackSize[quality].SettingChanged += Backpacks.UpdateItemDataConfigValues; } internal virtual void RegisterWeightMultiplier(float defaultValue = 0.5f) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown WeightMultiplier = ConfigSyncBase.SyncedConfig(_englishSection, "Weight Multiplier", defaultValue, new ConfigDescription("The weight of items stored in the backpack gets multiplied by this value.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[1] { new Vapok.Common.Shared.ConfigurationManagerAttributes { Category = _localizedCategory, Order = 4 } })); WeightMultiplier.SettingChanged += Backpacks.UpdateItemDataConfigValues; } internal virtual void RegisterBackpackBiome(BackpackBiomes defaultValue = BackpackBiomes.None) { //IL_0039: Unknown result type (might be due to inval