Decompiled source of AdventureBackpacks v2.4.6

plugins/AdventureBackpacks.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using APIManager;
using AdventureBackpacks.API;
using AdventureBackpacks.Assets;
using AdventureBackpacks.Assets.Effects;
using AdventureBackpacks.Assets.Factories;
using AdventureBackpacks.Assets.Items;
using AdventureBackpacks.Assets.Items.BackpackItems;
using AdventureBackpacks.Compats;
using AdventureBackpacks.Components;
using AdventureBackpacks.Configuration;
using AdventureBackpacks.Extensions;
using AdventureBackpacks.Features;
using AdventureBackpacks.Patches;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Preloader;
using BepInEx.Preloader.Patching;
using HarmonyLib;
using ItemManager;
using JetBrains.Annotations;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Valheim.SettingsGui;
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.Splash;
using Vapok.Common.Managers.StatusEffects;
using Vapok.Common.Managers.Telemetry;
using Vapok.Common.Shared;
using Vapok.Common.Tools;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("AdventureBackpacks")]
[assembly: AssemblyDescription("A Valheim Mod for adding progression multiple backpacks as an item/utility gear addition.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Vapok Modding")]
[assembly: AssemblyProduct("AdventureBackpacks")]
[assembly: AssemblyCopyright("Copyright © Vapok Modding  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("997CB563-FCC7-44B7-8F71-069747D27CC5")]
[assembly: AssemblyFileVersion("2.4.6.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.4.6.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AdventureBackpacks
{
	[BepInPlugin("vapok.mods.adventurebackpacks", "Adventure Backpacks", "2.4.6")]
	[BepInIncompatibility("JotunnBackpacks")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class AdventureBackpacks : BaseUnityPlugin, IPluginInfo
	{
		public class Waiting
		{
			public event EventHandler StatusChanged;

			public void ValheimIsAwake(bool awakeFlag)
			{
				if (awakeFlag)
				{
					this.StatusChanged?.Invoke(this, EventArgs.Empty);
				}
			}
		}

		private const string _pluginId = "vapok.mods.adventurebackpacks";

		private const string _displayName = "Adventure Backpacks";

		private const string _version = "2.4.6";

		public static bool ValheimAwake;

		public static bool PerformYardSale;

		public static bool QuickDropping;

		private static bool _bypassMoveProtection;

		private static int _bypassMoveProtectionDepth;

		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 => "2.4.6";

		public BaseUnityPlugin Instance => (BaseUnityPlugin)(object)_instance;

		public static ILogIt Log => _log;

		public static bool BypassMoveProtection
		{
			get
			{
				if (!_bypassMoveProtection)
				{
					return _bypassMoveProtectionDepth > 0;
				}
				return true;
			}
			set
			{
				_bypassMoveProtection = value;
			}
		}

		public static ConfigSyncBase ActiveConfig => _config;

		public static void PushBypassMoveProtection()
		{
			Interlocked.Increment(ref _bypassMoveProtectionDepth);
		}

		public static void PopBypassMoveProtection()
		{
			if (_bypassMoveProtectionDepth > 0)
			{
				Interlocked.Decrement(ref _bypassMoveProtectionDepth);
			}
		}

		[UsedImplicitly]
		private void Awake()
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			_instance = this;
			Patcher.Patch(new string[1] { "AdventureBackpacks.API" });
			Waiter = new Waiting();
			CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
			LogManager.Init(PluginId, out _log);
			Initializer.LoadManagers(localization, enableCreatureManager: true, enableItemManager: true, enableLocationManager: true, enableMaterialReplacer: true, enablePieceManager: false, enableSkillManager: false, enableEffectManager: true);
			_config = new ConfigRegistry(_instance);
			ItemManager.PrefabManager.Initalized = true;
			_harmony = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
			if (Chainloader.PluginInfos.ContainsKey("com.chebgonaz.ChebsNecromancy"))
			{
				ChebsNecromancy.SetupNecromancyBackpackUsingApi();
			}
			if (Chainloader.PluginInfos.ContainsKey("com.maxsch.valheim.contentswithin"))
			{
				ContentsWithin.Awake(_harmony, "com.maxsch.valheim.contentswithin");
			}
			ModSplashManager.Register(new ModSplashDossier(_instance)
			{
				Tagline = "A feature-rich backpack progression system with custom models, effects, and inventory mechanics.",
				ShowOnStartup = ConfigSyncBase.ShowSplashOnStartup
			});
		}

		private void Start()
		{
			Localizer.Waiter.StatusChanged += InitializeBackpacks;
			if (PlayerExtensions.IsDedicatedOrHeadless())
			{
				InitializeBackpacks(null, EventArgs.Empty);
			}
			QuickTransfer.FeatureInitialized = true;
			CraftFromBackpack.FeatureInitialized = true;
			StoreToBackpack.FeatureInitialized = true;
			ContainerTabs.FeatureInitialized = true;
		}

		private void Update()
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			if (PlayerExtensions.IsDedicatedOrHeadless() || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			if (PerformYardSale)
			{
				BackpackComponent equippedBackpack = Player.m_localPlayer.GetEquippedBackpack();
				if (equippedBackpack != null)
				{
					Backpacks.PerformYardSale(Player.m_localPlayer, equippedBackpack.Item);
				}
			}
			if (ConfigRegistry.HotKeyDrop != null)
			{
				KeyboardShortcut value = ConfigRegistry.HotKeyDrop.Value;
				if ((int)((KeyboardShortcut)(ref value)).MainKey != 0 && ConfigRegistry.OutwardMode != null && ConfigRegistry.OutwardMode.Value && (ZInput.GetButton("Forward") || ZInput.GetButton("Backward") || ZInput.GetButton("Left") || ZInput.GetButton("Right")))
				{
					value = ConfigRegistry.HotKeyDrop.Value;
					if (ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey, true))
					{
						Player.m_localPlayer.QuickDropBackpack();
					}
				}
			}
			EffectsFactory.Instance?.ToggleEffects();
			InventoryPatches.ProcessItemsAddedQueue();
		}

		public void InitializeBackpacks(object send, EventArgs args)
		{
			if (ValheimAwake)
			{
				return;
			}
			new EffectsFactory(_log, _config).RegisterEffects();
			new BackpackFactory(_log, _config).CreateAssets();
			Backpacks.LoadBackpackTypes(BackpackFactory.BackpackTypes());
			if (!PlayerExtensions.IsDedicatedOrHeadless() && !BoneReorderAlreadyApplied())
			{
				try
				{
					BoneReorder.ApplyOnEquipmentChanged(((BaseUnityPlugin)this).Info.Metadata.GUID);
				}
				catch (Exception ex)
				{
					Log?.Warning("Could not apply bone reordering: " + ex.Message);
				}
			}
			ConfigRegistry.Waiter.ConfigurationComplete(configDone: true);
			ValheimAwake = true;
		}

		private static bool BoneReorderAlreadyApplied()
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(VisEquipment), "SetShoulderEquipped", (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					return false;
				}
				Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo);
				if (patchInfo?.Postfixes == null)
				{
					return false;
				}
				foreach (Patch postfix in patchInfo.Postfixes)
				{
					if (!(postfix.PatchMethod?.DeclaringType?.Name != "BoneReorder"))
					{
						Log?.Info("Bone reordering already installed by '" + postfix.owner + "'. Skipping ours.");
						return true;
					}
				}
				return false;
			}
			catch (Exception ex)
			{
				Log?.Warning("Could not inspect shoulder visual patches, applying bone reordering anyway: " + ex.Message);
				return false;
			}
		}

		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<RecipeIngredient> UpgraderIngredients = 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 int ArmorPerLevel = 1;

			public float SpeedMod;

			public bool ScaleSpeedModByQuality = true;

			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 IsBackpackOpen()
		{
			return InventoryGuiPatches.BackpackIsOpen;
		}

		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 Inventory GetEquippedBackpackInventory(Player player)
		{
			if ((Object)(object)player == (Object)null)
			{
				return null;
			}
			return player.GetEquippedBackpack()?.GetInventory();
		}

		public static bool TryGetEquippedBackpackInventory(Player player, out Inventory inventory)
		{
			inventory = GetEquippedBackpackInventory(player);
			return inventory != null;
		}

		public static Inventory GetBackpackInventory(ItemData itemData)
		{
			if (itemData == null)
			{
				return null;
			}
			return GetBackpack(itemData)?.Inventory;
		}

		public static bool TryGetBackpackInventory(ItemData itemData, out Inventory inventory)
		{
			inventory = GetBackpackInventory(itemData);
			return inventory != null;
		}

		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 OpenBackpack(Player player, InventoryGui gui, int activeGroup)
		{
			if ((Object)(object)player != (Object)null)
			{
				player.OpenBackpack(gui, activeGroup);
			}
		}

		public static void RegisterEffect(EffectDefinition effectDefinition)
		{
			EffectsFactory.RegisterExternalEffect(effectDefinition);
		}

		public static void RegisterBackpack(BackpackDefinition definition)
		{
			BackpackFactory.RegisterExternalBackpack(definition);
		}

		public static bool IsCraftFromBackpackEnabled()
		{
			return CraftFromBackpack.EnableCraftFromBackpack?.Value ?? false;
		}

		public static bool IsOpenWithCraftingStationEnabled()
		{
			return ConfigRegistry.OpenWithCraftingStation?.Value ?? false;
		}

		public static bool IsOpenWithInventoryEnabled()
		{
			return ConfigRegistry.OpenWithInventory?.Value ?? false;
		}

		public static bool IsEnableContainerTabsEnabled()
		{
			return ConfigRegistry.EnableContainerTabs?.Value ?? false;
		}

		public static bool HasActiveExternalContainer()
		{
			return ContainerTabs.HasActiveExternalContainer;
		}

		public static bool IsCraftingContextActive()
		{
			return CraftingContext.IsActive;
		}

		public static string GetConsumptionPriority()
		{
			return CraftFromBackpack.MaterialConsumptionPriority?.Value.ToString() ?? "PlayerInventoryFirst";
		}

		public static bool IsLeaveOneItemInBackpackEnabled()
		{
			return CraftFromBackpack.LeaveOneItemInBackpack?.Value ?? false;
		}

		public static bool IsDisplayTotalIngredientCountEnabled()
		{
			return CraftFromBackpack.DisplayTotalIngredientCount?.Value ?? false;
		}

		public static void SuppressNativeCrafting(string modIdentifier)
		{
			CraftingContext.Suppress(modIdentifier);
		}

		public static void UnsuppressNativeCrafting(string modIdentifier)
		{
			CraftingContext.Unsuppress(modIdentifier);
		}

		public static List<Inventory> GetAllBackpackInventories(Player player)
		{
			List<Inventory> list = new List<Inventory>();
			if ((Object)(object)player == (Object)null)
			{
				return list;
			}
			HashSet<Inventory> hashSet = new HashSet<Inventory>();
			Inventory equippedBackpackInventory = GetEquippedBackpackInventory(player);
			if (equippedBackpackInventory != null && hashSet.Add(equippedBackpackInventory))
			{
				list.Add(equippedBackpackInventory);
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory != null)
			{
				foreach (ItemData allItem in inventory.GetAllItems())
				{
					if (TryGetBackpackInventory(allItem, out var inventory2) && inventory2 != null && hashSet.Add(inventory2))
					{
						list.Add(inventory2);
					}
				}
			}
			return list;
		}

		public static bool TryGetAllBackpackInventories(Player player, out List<Inventory> inventories)
		{
			inventories = GetAllBackpackInventories(player);
			if (inventories != null)
			{
				return inventories.Count > 0;
			}
			return false;
		}

		public static bool WouldStorePickup(Player player, ItemData item)
		{
			Inventory backpackInventory;
			return StoreToBackpack.ShouldStoreToBackpack(player, item, out backpackInventory);
		}

		public static bool WouldStorePickup(Player player, ItemData item, out Inventory backpackInventory)
		{
			return StoreToBackpack.ShouldStoreToBackpack(player, item, out backpackInventory);
		}

		public static void RegisterVisualBundle(string packName, string backpackId, ModelStyle modelStyle, AssetBundle overrideBundle, bool isDefault = false)
		{
			VisualPackRegistry.Register(packName, backpackId, modelStyle, overrideBundle, isDefault);
		}

		public static void RegisterVisualBundle(string packName, BackpackName backpack, ModelStyle modelStyle, AssetBundle overrideBundle, bool isDefault = false)
		{
			RegisterVisualBundle(packName, backpack.ToBackpackId(), modelStyle, overrideBundle, isDefault);
		}

		public static void RegisterVisualBundle(string packName, string targetBundleName, AssetBundle overrideBundle)
		{
			RegisterVisualBundle(packName, targetBundleName, overrideBundle, isDefault: false);
		}

		public static void RegisterVisualBundle(string packName, string targetBundleName, AssetBundle overrideBundle, bool isDefault)
		{
			VisualPackRegistry.Register(packName, targetBundleName, overrideBundle, isDefault);
		}

		public static bool HasVisualBundle(string packName, string backpackId, ModelStyle modelStyle)
		{
			return VisualPackRegistry.HasOverride(packName, backpackId, modelStyle);
		}

		public static bool HasVisualBundle(string packName, BackpackName backpack, ModelStyle modelStyle)
		{
			return HasVisualBundle(packName, backpack.ToBackpackId(), modelStyle);
		}

		public static bool HasVisualBundle(string packName, string targetBundleName)
		{
			return VisualPackRegistry.HasOverride(packName, targetBundleName);
		}

		public static string[] GetAvailableVisualPacks(string backpackId, ModelStyle modelStyle)
		{
			return VisualPackRegistry.GetAvailablePacksFor(backpackId, modelStyle);
		}

		public static string[] GetAvailableVisualPacks(BackpackName backpack, ModelStyle modelStyle)
		{
			return GetAvailableVisualPacks(backpack.ToBackpackId(), modelStyle);
		}

		public static string[] GetAvailableVisualPacks(string targetBundleName)
		{
			return VisualPackRegistry.GetAvailablePacksFor(targetBundleName);
		}

		private static Backpack? ConvertBackpackItem(BackpackComponent component)
		{
			BackpackDefinition backPackDefinitionFromComponent = GetBackPackDefinitionFromComponent(component);
			if (backPackDefinitionFromComponent == null)
			{
				return null;
			}
			return new Backpack
			{
				Name = backPackDefinitionFromComponent.ItemName,
				ItemData = component.Item,
				Definition = backPackDefinitionFromComponent,
				Inventory = component.GetInventory()
			};
		}

		private static Backpack? ConvertBackpackItem(ItemData itemData)
		{
			if (!itemData.IsBackpack())
			{
				return null;
			}
			return ConvertBackpackItem(itemData.Data().GetOrCreate<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 == null || component.Item == null)
			{
				return null;
			}
			if (!component.Item.TryGetBackpackItem(out var backpack) || backpack == null)
			{
				return null;
			}
			return GetBackPackDefinition(backpack);
		}

		private static BackpackDefinition GetBackPackDefinition(BackpackItem backpack)
		{
			if (backpack == null)
			{
				return null;
			}
			return new BackpackDefinition
			{
				ItemName = backpack.ItemName,
				PrefabName = backpack.PrefabName,
				BackpackSizeByQuality = GetBackpackSizing(backpack),
				WeightMultiplier = ((backpack.WeightMultiplier != null) ? backpack.WeightMultiplier.Value : 0.5f),
				CarryBonus = ((backpack.CarryBonus != null) ? backpack.CarryBonus.Value : 0),
				ArmorPerLevel = ((backpack.ArmorPerLevel == null) ? 1 : backpack.ArmorPerLevel.Value),
				SpeedMod = ((backpack.SpeedMod != null) ? backpack.SpeedMod.Value : 0f),
				ScaleSpeedModByQuality = (backpack.ScaleSpeedModByQuality == null || backpack.ScaleSpeedModByQuality.Value),
				EnableFreezing = (backpack.EnableFreezing != null && backpack.EnableFreezing.Value),
				BackpackBiome = ((backpack.BackpackBiome != null) ? backpack.BackpackBiome.Value : BackpackBiomes.None)
			};
		}
	}
	public enum ModelStyle
	{
		Modern,
		Classic
	}
	public enum BackpackName
	{
		Meadows,
		BlackForest,
		Swamp,
		Mountains,
		Plains,
		Mistlands,
		Ashlands,
		DeepNorth
	}
	public static class BackpackExtensions
	{
		public static string ToBackpackId(this BackpackName backpack)
		{
			return backpack switch
			{
				BackpackName.Meadows => "backpack_meadows", 
				BackpackName.BlackForest => "backpack_black_forest", 
				BackpackName.Swamp => "backpack_swamp", 
				BackpackName.Mountains => "backpack_mountains", 
				BackpackName.Plains => "backpack_plains", 
				BackpackName.Mistlands => "backpack_mistlands", 
				BackpackName.Ashlands => "backpack_ashlands", 
				BackpackName.DeepNorth => "backpack_deepnorth", 
				_ => "backpack_meadows", 
			};
		}
	}
	[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_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: 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));
			try
			{
				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;
			}
			finally
			{
				val3.Unload(false);
			}
			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)
				},
				UpgraderIngredients = 
				{
					new ABAPI.RecipeIngredient("Upgrader1Armor", 1)
				},
				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_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			if (!PlayerExtensions.IsDedicatedOrHeadless() && 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 || !container.IsBackpackProxy())
			{
				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()
			{
				AdventureBackpacks.PushBypassMoveProtection();
			}

			private static void Finalizer()
			{
				AdventureBackpacks.PopBypassMoveProtection();
			}
		}

		[HarmonyPatch(typeof(ArmorStand), "UseItem")]
		private static class ArmorStandUseItemPatch
		{
			private static void Prefix()
			{
				AdventureBackpacks.PushBypassMoveProtection();
			}

			private static void Finalizer()
			{
				AdventureBackpacks.PopBypassMoveProtection();
			}
		}
	}
	public static class ContainerPatches
	{
		[HarmonyPatch(typeof(Container), "TakeAll")]
		private static class ContainerTakeAllPatch
		{
			private static bool Prefix(Container __instance, Humanoid character, ref bool __result)
			{
				AdventureBackpacks.PushBypassMoveProtection();
				if (__instance.IsBackpackProxy())
				{
					Player val = (Player)(object)((character is Player) ? character : null);
					if ((Object)(object)val == (Object)null)
					{
						val = Player.m_localPlayer;
					}
					if ((Object)(object)val != (Object)null && __instance.GetInventory() != null)
					{
						((Humanoid)val).GetInventory().MoveAll(__instance.GetInventory());
					}
					__result = true;
					return false;
				}
				return true;
			}

			private static void Finalizer()
			{
				AdventureBackpacks.PopBypassMoveProtection();
			}
		}

		[HarmonyPatch(typeof(Container), "RPC_TakeAllResponse")]
		private static class ContainerRpcTakeAllResponsePatch
		{
			private static void Prefix(bool granted)
			{
				if (granted)
				{
					AdventureBackpacks.PushBypassMoveProtection();
				}
			}

			private static void Finalizer(bool granted)
			{
				if (granted)
				{
					AdventureBackpacks.PopBypassMoveProtection();
				}
			}
		}

		[HarmonyPatch(typeof(Container), "Interact")]
		private static class ContainerInteractPatch
		{
			private static bool Prefix(Container __instance, ref bool __result)
			{
				if (__instance.IsBackpackProxy())
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Container), "Save")]
		private static class ContainerSavePatch
		{
			private static bool Prefix(Container __instance)
			{
				if ((Object)(object)__instance != (Object)null && __instance.IsBackpackProxy())
				{
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Container), "Load")]
		private static class ContainerLoadPatch
		{
			private static bool Prefix(Container __instance, ref bool __result)
			{
				if ((Object)(object)__instance != (Object)null && __instance.IsBackpackProxy())
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(ZNetView), "Awake")]
		private static class ZNetViewAwakePatch
		{
			private static bool Prefix(ZNetView __instance)
			{
				if ((Object)(object)__instance != (Object)null && (Object)(object)((Component)__instance).gameObject != (Object)null && ((Object)((Component)__instance).gameObject).name.StartsWith("AB_BackpackProxy"))
				{
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(ZNetView), "IsOwner")]
		private static class ZNetViewIsOwnerPatch
		{
			private static bool Prefix(ZNetView __instance, ref bool __result)
			{
				if ((Object)(object)__instance == (Object)null || __instance.GetZDO() != null)
				{
					return true;
				}
				if ((Object)(object)((Component)__instance).gameObject != (Object)null && ((Object)((Component)__instance).gameObject).name.StartsWith("AB_BackpackProxy"))
				{
					__result = true;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(ZNetView), "InvokeRPC", new Type[]
		{
			typeof(string),
			typeof(object[])
		})]
		private static class ZNetViewInvokeRpcPatch
		{
			private static bool Prefix(ZNetView __instance)
			{
				if ((Object)(object)__instance == (Object)null || __instance.GetZDO() != null)
				{
					return true;
				}
				if ((Object)(object)((Component)__instance).gameObject != (Object)null && ((Object)((Component)__instance).gameObject).name.StartsWith("AB_BackpackProxy"))
				{
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(ZNetView), "InvokeRPC", new Type[]
		{
			typeof(long),
			typeof(string),
			typeof(object[])
		})]
		private static class ZNetViewInvokeRpcWithTargetPatch
		{
			private static bool Prefix(ZNetView __instance)
			{
				if ((Object)(object)__instance == (Object)null || __instance.GetZDO() != null)
				{
					return true;
				}
				if ((Object)(object)((Component)__instance).gameObject != (Object)null && ((Object)((Component)__instance).gameObject).name.StartsWith("AB_BackpackProxy"))
				{
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Container), "Awake")]
		private static class ContainerAwakePatch
		{
			[HarmonyPriority(800)]
			private static bool Prefix(Container __instance)
			{
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Expected O, but got Unknown
				if ((Object)(object)__instance != (Object)null && __instance.IsBackpackProxy())
				{
					if ((Object)(object)__instance.m_nview == (Object)null)
					{
						__instance.m_nview = ((Component)__instance).GetComponent<ZNetView>();
					}
					if (__instance.m_inventory == null)
					{
						__instance.m_inventory = new Inventory("$vapok_mod_backpack", (Sprite)null, 1, 1);
					}
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Container), "IsOwner")]
		private static class ContainerIsOwnerPatch
		{
			private static bool Prefix(Container __instance, ref bool __result)
			{
				if ((Object)(object)__instance != (Object)null && __instance.IsBackpackProxy())
				{
					__result = true;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Container), "IsInUse")]
		private static class ContainerIsInUsePatch
		{
			private static bool Prefix(Container __instance, ref bool __result)
			{
				if ((Object)(object)__instance != (Object)null && __instance.IsBackpackProxy())
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Container), "SetInUse")]
		private static class ContainerSetInUsePatch
		{
			[HarmonyPriority(800)]
			private static bool Prefix(Container __instance)
			{
				if ((Object)(object)__instance != (Object)null && __instance.IsBackpackProxy())
				{
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Container), "CheckAccess")]
		private static class ContainerCheckAccessPatch
		{
			private static bool Prefix(Container __instance, ref bool __result)
			{
				if ((Object)(object)__instance != (Object)null && __instance.IsBackpackProxy())
				{
					__result = true;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Container), "StackAll")]
		private static class ContainerStackAllPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static bool Prefix(Container __instance)
			{
				if ((Object)(object)__instance != (Object)null && __instance.IsBackpackProxy())
				{
					if ((Object)(object)Player.m_localPlayer != (Object)null && ((Humanoid)Player.m_localPlayer).GetInventory() != null && __instance.GetInventory() != null)
					{
						__instance.GetInventory().StackAll(((Humanoid)Player.m_localPlayer).GetInventory(), false);
					}
					return false;
				}
				return true;
			}
		}

		public static bool IsBackpackProxy(this Container container)
		{
			if ((Object)(object)container == (Object)null || !Object.op_Implicit((Object)(object)container))
			{
				return false;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && (Object)(object)((Component)container).transform.parent != (Object)null && (Object)(object)((Component)container).transform.parent == (Object)(object)((Component)localPlayer).transform)
			{
				return true;
			}
			if ((Object)(object)((Component)container).gameObject == (Object)null)
			{
				return false;
			}
			if (!((Object)((Component)container).gameObject).name.StartsWith("AB_BackpackProxy") && !((Object)((Component)container).gameObject).name.Equals("Player(Clone)"))
			{
				return (Object)(object)((Component)container).GetComponentInParent<Player>() != (Object)null;
			}
			return true;
		}
	}
	public static class DoorPatches
	{
		[HarmonyPatch(typeof(Door), "HaveKey")]
		private static class HaveDoorKeyPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static void Postfix(Door __instance, Humanoid player, bool matchWorldLevel, ref bool __result)
			{
				if (((Object)(object)__instance == (Object)null) | __result)
				{
					return;
				}
				Player val = (Player)(((object)((player is Player) ? player : null)) ?? ((object)Player.m_localPlayer));
				if ((Object)(object)val == (Object)null || !val.IsBackpackEquipped())
				{
					return;
				}
				if ((Object)(object)__instance.m_keyItem == (Object)null)
				{
					__result = true;
					return;
				}
				string text = __instance.m_keyItem.m_itemData?.m_shared?.m_name;
				if (!string.IsNullOrEmpty(text))
				{
					Inventory val2 = val.GetEquippedBackpack()?.GetInventory();
					if (val2 != null && val2.HaveItem(text, matchWorldLevel))
					{
						__result = true;
					}
				}
			}
		}
	}
	public class EnvManPatches
	{
	}
	public class FejdStartupPatches
	{
		[HarmonyPatch(typeof(FejdStartup), "Start")]
		[HarmonyAfter(new string[] { "vapok.common.LocalizationManager", "org.bepinex.helpers.LocalizationManager" })]
		[HarmonyBefore(new string[] { "vapok.common.ItemManager", "org.bepinex.helpers.ItemManager" })]
		public static class FejdStartupAwakePatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			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";

			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			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;
			}
		}
	}
	internal static class HudPatches
	{
		[HarmonyPatch(typeof(Hud), "SetupPieceInfo")]
		private static class HudSetupPieceInfoPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[HarmonyPrefix]
			[HarmonyPriority(900)]
			private static void Prefix()
			{
				CraftingContext.Enter();
			}

			[HarmonyFinalizer]
			[HarmonyPriority(100)]
			private static void Finalizer()
			{
				CraftingContext.Exit();
			}
		}
	}
	public class HumanoidPatches
	{
		[HarmonyPatch(typeof(Humanoid), "UpdateEquipmentStatusEffects")]
		private static class HumanoidUpdateEquipmentStatusEffectsPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			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 (i > 0 && (instrs[i].opcode == OpCodes.Stloc_0 || instrs[i].opcode == OpCodes.Stloc_S || instrs[i].opcode == OpCodes.Stloc) && 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;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Humanoid __instance)
			{
				if ((Object)(object)__instance == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
				{
					return;
				}
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (val == null)
				{
					return;
				}
				SEMan sEMan = ((Character)val).GetSEMan();
				if (sEMan == null)
				{
					return;
				}
				if (val.IsBackpackEquipped())
				{
					EquipmentEffectCache.AddActiveBackpackEffects(__instance.m_equipmentStatusEffects, __instance);
					if (EquipmentEffectCache.ActiveEffects == null)
					{
						return;
					}
					HashSet<StatusEffect> registeredEffects = EffectsFactory.GetRegisteredEffects();
					if (registeredEffects != null)
					{
						foreach (StatusEffect item in registeredEffects)
						{
							if (!((Object)(object)item == (Object)null) && ((Object)item).name.StartsWith("SE_vapok_ab_") && !EquipmentEffectCache.ActiveEffects.Contains(item) && sEMan.HaveStatusEffect(item.NameHash()))
							{
								sEMan.RemoveStatusEffect(item.NameHash(), false);
								__instance.m_equipmentStatusEffects.Remove(item);
							}
						}
					}
					{
						foreach (StatusEffect activeEffect in EquipmentEffectCache.ActiveEffects)
						{
							if (!((Object)(object)activeEffect == (Object)null))
							{
								if (!__instance.m_equipmentStatusEffects.Contains(activeEffect))
								{
									__instance.m_equipmentStatusEffects.Add(activeEffect);
								}
								if (!sEMan.HaveStatusEffect(activeEffect.NameHash()))
								{
									sEMan.AddStatusEffect(activeEffect, false, 0, 0f, (short)(-1));
								}
							}
						}
						return;
					}
				}
				if (EquipmentEffectCache.ActiveEffects != null && EquipmentEffectCache.ActiveEffects.Count > 0)
				{
					EquipmentEffectCache.ActiveEffects.Clear();
				}
				HashSet<StatusEffect> registeredEffects2 = EffectsFactory.GetRegisteredEffects();
				if (registeredEffects2 == null)
				{
					return;
				}
				foreach (StatusEffect item2 in registeredEffects2)
				{
					if (!((Object)(object)item2 == (Object)null) && ((Object)item2).name.StartsWith("SE_vapok_ab_") && sEMan.HaveStatusEffect(item2.NameHash()))
					{
						sEMan.RemoveStatusEffect(item2.NameHash(), false);
						__instance.m_equipmentStatusEffects.Remove(item2);
					}
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "UnequipItem")]
		private static class HumanoidUnequipItemPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static void Prefix(ItemData __0)
			{
				//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)
				try
				{
					if (__0 == null || (Object)(object)Player.m_localPlayer == (Object)null)
					{
						return;
					}
					Scene activeScene = SceneManager.GetActiveScene();
					if (((Scene)(ref activeScene)).name == null || string.Equals(((Scene)(ref activeScene)).name, "start"))
					{
						return;
					}
					Player localPlayer = Player.m_localPlayer;
					if (!__0.IsBackpack() || ((Humanoid)localPlayer).m_shoulderItem != __0)
					{
						return;
					}
					BackpackComponent equippedBackpack = localPlayer.GetEquippedBackpack();
					if (equippedBackpack == null)
					{
						return;
					}
					equippedBackpack.Save();
					InventoryGui instance = InventoryGui.instance;
					if ((Object)(object)instance != (Object)null && instance.IsContainerOpen())
					{
						if (ContainerTabs.HasActiveExternalContainer)
						{
							if (ContainerTabs.IsViewingBackpack)
							{
								ContainerTabs.SwitchToChest(instance, localPlayer);
							}
							ContainerTabs.Reset(instance);
						}
						else if ((Object)(object)instance.m_currentContainer != (Object)null && instance.m_currentContainer.IsBackpackProxy())
						{
							instance.CloseContainer();
							InventoryGuiPatches.BackpackIsOpen = false;
						}
					}
					localPlayer.DestroyBackpackContainerProxy();
					InventoryGuiPatches.BackpackEquipped = false;
				}
				catch (Exception ex)
				{
					AdventureBackpacks.Log?.Warning("Error during Humanoid.UnequipItem: " + ex.Message);
				}
			}

			private static void Postfix(Humanoid __instance, ItemData __0)
			{
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0077: Invalid comparison between Unknown and I4
				try
				{
					if (__0 == null || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || !__0.IsBackpack())
					{
						return;
					}
					Player localPlayer = Player.m_localPlayer;
					if (((Humanoid)localPlayer).m_shoulderItem != null)
					{
						return;
					}
					Inventory inventory = ((Humanoid)localPlayer).GetInventory();
					List<ItemData> list = ((inventory != null) ? inventory.GetEquippedItems() : null);
					if (list == null)
					{
						return;
					}
					for (int i = 0; i < list.Count; i++)
					{
						ItemData val = list[i];
						if (val != null && val.m_equipped && (int)val.m_shared.m_itemType == 17 && !val.IsBackpack())
						{
							((Humanoid)localPlayer).m_shoulderItem = val;
							((Humanoid)localPlayer).SetupEquipment();
							break;
						}
					}
				}
				catch (Exception ex)
				{
					AdventureBackpacks.Log?.Warning("Error during Humanoid.UnequipItem Postfix: " + ex.Message);
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "EquipItem")]
		private static class HumanoidEquipItemPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static void Postfix(Humanoid __instance, ItemData __0, bool __result)
			{
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0042: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					AdventureBackpacks.Log.Debug("##########   EquipItem Start");
					if (__0 == null || !__result || (Object)(object)__instance == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
					{
						return;
					}
					Scene activeScene = SceneManager.GetActiveScene();
					if (((Scene)(ref activeScene)).name == null || string.Equals(((Scene)(ref activeScene)).name, "start"))
					{
						return;
					}
					Player localPlayer = Player.m_localPlayer;
					if (__0.IsBackpack() && __0.TryGetBackpackItem(out var backpack))
					{
						InventoryGuiPatches.BackpackEquipped = true;
						BackpackComponent orCreate = __0.Data().GetOrCreate<BackpackComponent>();
						if (!orCreate.IsEmptyingBackpack)
						{
							Vector2i inventorySize = backpack.GetInventorySize(orCreate.Item.m_quality);
							if (orCreate.InventoryNeedsValidating(inventorySize))
							{
								Backpacks.ValidateBackpackInventorySizing(localPlayer, orCreate.Item);
							}
							else
							{
								Container backpackContainer = localPlayer.GetBackpackContainerProxy(createIfMissing: false);
								if ((Object)(object)backpackContainer != (Object)null)
								{
									orCreate.UpdateContainerSizing(ref backpackContainer);
								}
							}
						}
					}
					AdventureBackpacks.Log.Debug("##########   EquipItem End");
				}
				catch (Exception ex)
				{
					AdventureBackpacks.Log?.Warning("Error during Humanoid.EquipItem: " + ex.Message);
				}
			}
		}
	}
	public static class InventoryPatches
	{
		[HarmonyPatch(typeof(Inventory), "Changed")]
		private static class InventoryChangedPatch
		{
			private static void Postfix(Inventory __instance)
			{
				if (__instance == null || (Object)(object)Player.m_localPlayer == (Object)null)
				{
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if (!__instance.IsBackPackInventory())
				{
					return;
				}
				AdventureBackpacks.Log.Debug($"#### Patch Inventory Changed: {__instance.m_name} (HashCode: {((object)__instance).GetHashCode()}, Slots: {__instance.m_inventory.Count})");
				if (!localPlayer.IsBackpackEquipped())
				{
					return;
				}
				BackpackComponent equippedBackpack = localPlayer.GetEquippedBackpack();
				if (equippedBackpack != null)
				{
					Inventory inventory = equippedBackpack.GetInventory();
					AdventureBackpacks.Log.Debug("########################################");
					AdventureBackpacks.Log.Debug("####       Inventory.Changed       #####");
					AdventureBackpacks.Log.Debug($"Changed Inventory: {__instance.m_name} (HashCode: {((object)__instance).GetHashCode()})");
					AdventureBackpacks.Log.Debug("Backpack Item: " + equippedBackpack.Item?.m_shared?.m_name);
					AdventureBackpacks.Log.Debug($"Backpack Inventory: {inventory?.m_name} (HashCode: {((object)inventory)?.GetHashCode()})");
					AdventureBackpacks.Log.Debug("########################################");
					if (inventory == __instance)
					{
						AdventureBackpacks.Log.Debug($"#### Before Save BackpackComponent Inventory Count: {inventory.m_inventory.Count}");
						if (equippedBackpack.IsLoadingInventory)
						{
							AdventureBackpacks.Log.Debug("Bypassing Save - Inventory Is Loading ----->");
						}
						else
						{
							equippedBackpack.Save(__instance);
						}
						AdventureBackpacks.Log.Debug($"#### After Save BackpackComponent Inventory Count: {inventory.m_inventory.Count}");
						return;
					}
					Container backpackContainerProxy = localPlayer.GetBackpackContainerProxy(createIfMissing: false);
					if ((Object)(object)backpackContainerProxy != (Object)null && backpackContainerProxy.m_inventory == __instance)
					{
						equippedBackpack.SetInventory(__instance);
						return;
					}
					Inventory inventory2 = ((Humanoid)localPlayer).GetInventory();
					ItemData val = ((inventory2 != null) ? inventory2.GetAllItems() : null)?.FirstOrDefault((Func<ItemData, bool>)((ItemData i) => i.IsBackpack() && i.Data().Get<BackpackComponent>()?.GetInventory() == __instance));
					if (val != null)
					{
						BackpackComponent backpackComponent = val.Data().Get<BackpackComponent>();
						if (backpackComponent != null && !backpackComponent.IsLoadingInventory)
						{
							backpackComponent.Save(__instance);
						}
					}
				}
				else
				{
					AdventureBackpacks.Log.Warning("#### Player.IsBackpackEquipped() was true, but GetEquippedBackpack() returned null!");
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "OnDropOutside")]
		[HarmonyPriority(800)]
		private static class OnDropOutsideItemPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static void Prefix(InventoryGui __instance)
			{
				if (!((Object)(object)__instance == (Object)null) && __instance.m_dragItem != null)
				{
					if (__instance.m_dragItem.IsBackpack() && __instance.m_dragItem.m_stack == 0)
					{
						__instance.m_dragItem.m_stack = 1;
					}
					_droppingOutside = true;
				}
			}

			private static void Postfix()
			{
				_droppingOutside = false;
			}
		}

		[HarmonyPatch(typeof(Humanoid), "DropItem", new Type[]
		{
			typeof(Inventory),
			typeof(ItemData),
			typeof(int)
		})]
		[HarmonyPriority(800)]
		private static class HumanoidDropItemPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static void Prefix(ItemData item)
			{
				_droppingOutside = true;
			}

			private static void Postfix()
			{
				_droppingOutside = false;
			}
		}

		[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(ItemData) })]
		[HarmonyPriority(800)]
		private static class RemoveItem1Patch
		{
			private static bool Prefix(Inventory __instance, ItemData item, ref bool __result)
			{
				if (item == null || __instance == null)
				{
					return true;
				}
				if (!RemoveItemPrefix(__instance, item))
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
		{
			typeof(ItemData),
			typeof(int)
		})]
		[HarmonyPriority(800)]
		private static class RemoveItem2Patch
		{
			private static bool Prefix(Inventory __instance, ItemData item, ref bool __result)
			{
				if (item == null || __instance == null)
				{
					return true;
				}
				if (!RemoveItemPrefix(__instance, item))
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Inventory), "RemoveOneItem", new Type[] { typeof(ItemData) })]
		[HarmonyPriority(800)]
		private static class RemoveItem3Patch
		{
			private static bool Prefix(Inventory __instance, ItemData item, ref bool __result)
			{
				if (item == null || __instance == null)
				{
					return true;
				}
				if (!RemoveItemPrefix(__instance, item))
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Inventory), "CanAddItem", new Type[]
		{
			typeof(ItemData),
			typeof(int)
		})]
		[HarmonyPriority(800)]
		private static class CanAddItemPatch
		{
			private static bool _evaluatingCanAddItem;

			private static bool Prefix(Inventory __instance, ItemData item, int stack, ref bool __result)
			{
				if (_evaluatingCanAddItem)
				{
					return true;
				}
				if (item == null || (Object)(object)Player.m_localPlayer == (Object)null || __instance != ((Humanoid)Player.m_localPlayer).GetInventory())
				{
					return true;
				}
				if (_movingItemBetweenContainers)
				{
					return true;
				}
				_evaluatingCanAddItem = true;
				try
				{
					if (StoreToBackpack.CanInventoryAccept(__instance, item, stack))
					{
						return true;
					}
					if (CraftingContext.IsActive && !item.IsBackpack() && !item.TryGetBackpackItem(out var _) && CraftFromBackpack.CanCraftOutputToBackpack(Player.m_localPlayer, out var backpackInventory) && StoreToBackpack.CanInventoryAccept(backpackInventory, item, stack))
					{
						__result = true;
						return false;
					}
					if (StoreToBackpack.ShouldStoreToBackpack(Player.m_localPlayer, item, out var _))
					{
						__result = true;
						return false;
					}
					return true;
				}
				finally
				{
					_evaluatingCanAddItem = false;
				}
			}
		}

		[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;
				}
				if ((Object)(object)Player.m_localPlayer != (Object)null && __instance == ((Humanoid)Player.m_localPlayer).GetInventory() && !_movingItemBetweenContainers)
				{
					if (CraftingContext.IsActive && !item.IsBackpack() && !item.TryGetBackpackItem(out var _) && CraftFromBackpack.CanCraftOutputToBackpack(Player.m_localPlayer, out var backpackInventory) && !StoreToBackpack.CanInventoryAccept(__instance, item, item.m_stack) && StoreToBackpack.TryStoreItem(Player.m_localPlayer, item, backpackInventory))
					{
						__result = true;
						return false;
					}
					if (StoreToBackpack.ShouldStoreToBackpack(Player.m_localPlayer, item, out var backpackInventory2) && StoreToBackpack.TryStoreItem(Player.m_localPlayer, item, backpackInventory2))
					{
						__result = true;
						return false;
					}
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Inventory), "AddItem", new Type[]
		{
			typeof(string),
			typeof(int),
			typeof(int),
			typeof(int),
			typeof(long),
			typeof(string),
			typeof(Vector2i),
			typeof(bool),
			typeof(bool),
			typeof(bool)
		})]
		[HarmonyPriority(800)]
		private static class AddItemCraftPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static bool Prefix(Inventory __instance, string name, int stack, int quality, int variant, long crafterID, string crafterName, Vector2i position, bool cheated, bool pickedUp, bool dropIfFullInv, ref ItemData __result)
			{
				//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
				if (!CraftingContext.IsActive || (Object)(object)Player.m_localPlayer == (Object)null || ((Humanoid)Player.m_localPlayer).GetInventory() == null || __instance == null || __instance != ((Humanoid)Player.m_localPlayer).GetInventory())
				{
					return true;
				}
				if (_movingItemBetweenContainers || (Object)(object)ObjectDB.instance == (Object)null)
				{
					return true;
				}
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(name);
				if ((Object)(object)itemPrefab == (Object)null)
				{
					return true;
				}
				ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component == (Object)null || component.m_itemData == null)
				{
					return true;
				}
				ItemData itemData = component.m_itemData;
				if (itemData.IsBackpack() || itemData.TryGetBackpackItem(out var _))
				{
					return true;
				}
				if (StoreToBackpack.CanInventoryAccept(__instance, itemData, stack))
				{
					return true;
				}
				if (CraftFromBackpack.CanCraftOutputToBackpack(Player.m_localPlayer, out var backpackInventory) && StoreToBackpack.CanInventoryAccept(backpackInventory, itemData, stack))
				{
					ItemData val = backpackInventory.AddItem(name, stack, quality, variant, crafterID, crafterName, new Vector2i(-1, -1), cheated, pickedUp, dropIfFullInv);
					if (val != null)
					{
						__result = val;
						return false;
					}
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
		{
			typeof(string),
			typeof(int),
			typeof(int),
			typeof(bool)
		})]
		[HarmonyPriority(600)]
		private static class RemoveItemByNamePatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static bool Prefix(Inventory __instance, string name, ref int amount, int itemQuality)
			{
				if (!CraftingContext.IsActive || (Object)(object)Player.m_localPlayer == (Object)null || __instance != ((Humanoid)Player.m_localPlayer).GetInventory())
				{
					return true;
				}
				if (amount <= 0 || string.IsNullOrEmpty(name))
				{
					return true;
				}
				if (CraftFromBackpack.CanCraftFromBackpack(Player.m_localPlayer, out var backpackInventory))
				{
					CraftFromBackpack.ProtectEquippedItems(__instance, name);
					int num = CraftFromBackpack.DeductBackpackCraftingItem(Player.m_localPlayer, backpackInventory, name, amount, itemQuality);
					if (num <= 0)
					{
						return false;
					}
					amount = num;
					return true;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Inventory), "CountItems", new Type[]
		{
			typeof(string),
			typeof(int),
			typeof(bool)
		})]
		[HarmonyPriority(600)]
		private static class CountItemsPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static void Postfix(Inventory __instance, string name, int quality, ref int __result)
			{
				if (__instance == null || !CraftingContext.IsActive || (Object)(object)Player.m_localPlayer == (Object)null || ((Humanoid)Player.m_localPlayer).GetInventory() == null || __instance != ((Humanoid)Player.m_localPlayer).GetInventory())
				{
					return;
				}
				List<ItemData> allItems = __instance.GetAllItems();
				if (allItems != null)
				{
					int num = 0;
					for (int i = 0; i < allItems.Count; i++)
					{
						ItemData val = allItems[i];
						if (val != null && val.m_equipped && val.m_shared != null && string.Equals(val.m_shared.m_name, name) && (quality <= 0 || val.m_quality == quality))
						{
							num += val.m_stack;
						}
					}
					if (num > 0)
					{
						__result = Mathf.Max(0, __result - num);
					}
				}
				if (CraftingContext.CanCraftFromBackpack && CraftingContext.ActiveBackpackInventory != null)
				{
					int num2 = ((quality > 0) ? CraftingContext.ActiveBackpackInventory.CountItems(name, quality, true) : CraftingContext.ActiveBackpackInventory.CountItems(name, -1, true));
					if (CraftFromBackpack.LeaveOneItemInBackpack != null && CraftFromBackpack.LeaveOneItemInBackpack.Value && num2 > 0)
					{
						num2 = Mathf.Max(0, num2 - 1);
					}
					__result += num2;
				}
			}
		}

		[HarmonyPatch(typeof(Inventory), "HaveItem", new Type[]
		{
			typeof(string),
			typeof(bool)
		})]
		[HarmonyPriority(600)]
		private static class HaveItemPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static void Postfix(Inventory __instance, string name, ref bool __result)
			{
				if (__result || !CraftingContext.IsActive || (Object)(object)Player.m_localPlayer == (Object)null || ((Humanoid)Player.m_localPlayer).GetInventory() == null || __instance != ((Humanoid)Player.m_localPlayer).GetInventory() || !CraftingContext.CanCraftFromBackpack || CraftingContext.ActiveBackpackInventory == null)
				{
					return;
				}
				int num = CraftingContext.ActiveBackpackInventory.CountItems(name, -1, true);
				if (CraftFromBackpack.LeaveOneItemInBackpack != null && CraftFromBackpack.LeaveOneItemInBackpack.Value)
				{
					if (num > 1)
					{
						__result = true;
					}
				}
				else if (num > 0)
				{
					__result = true;
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGrid), "DropItem", new Type[]
		{
			typeof(Inventory),
			typeof(ItemData),
			typeof(int),
			typeof(Vector2i)
		})]
		[HarmonyPriority(800)]
		private static class InventoryGridDropItemPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static bool Prefix(InventoryGrid __instance, Inventory fromInventory, ItemData item, int amount, Vector2i pos)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				ItemData itemAt = __instance.m_inventory.GetItemAt(pos.x, pos.y);
				if (itemAt == item)
				{
					return true;
				}
				if (itemAt == null || (!(itemAt.m_shared.m_name != item.m_shared.m_name) && (item.m_shared.m_maxQuality <= 1 || itemAt.m_quality == item.m_quality) && itemAt.m_shared.m_maxStackSize != 1) || item.m_stack != amount)
				{
					return true;
				}
				if (AdventureBackpacks.PerformYardSale)
				{
					return true;
				}
				if (itemAt.IsBackpack() && fromInventory.IsBackPackInventory())
				{
					return Backpacks.CheckForInception(fromInventory, itemAt);
				}
				if (item.IsBackpack() && __instance.m_inventory.IsBackPackInventory())
				{
					return Backpacks.CheckForInception(__instance.m_inventory, item);
				}
				_movingItemBetweenContainers = true;
				return true;
			}
		}

		[HarmonyPatch(typeof(Inventory), "MoveAll", new Type[] { typeof(Inventory) })]
		[HarmonyPriority(800)]
		private static class MoveAllPatch
		{
			private static void Prefix(Inventory fromInventory, Inventory __instance)
			{
				AdventureBackpacks.PushBypassMoveProtection();
				if (fromInventory != null && !__instance.IsBackPackInventory())
				{
					_movingItemBetweenContainers = true;
				}
			}

			private static void Finalizer()
			{
				_movingItemBetweenContainers = false;
				AdventureBackpacks.PopBypassMoveProtection();
			}
		}

		[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
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			private static void Postfix(Inventory __instance)
			{
				if (__instance == null || (Object)(object)Player.m_localPlayer == (Object)null)
				{
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if (!__instance.IsBackPackInventory() || !localPlayer.IsBackpackEquipped())
				{
					return;
				}
				BackpackComponent equippedBackpack = localPlayer.GetEquippedBackpack();
				if (equippedBackpack != null && equippedBackpack.GetInventory() == __instance)
				{
					Inventory inventory = ((Humanoid)localPlayer).GetInventory();
					if (inventory != null)
					{
						inventory.UpdateTotalWeight();
					}
				}
			}
		}

		[HarmonyPatch(typeof(Inventory), "IsTeleportable")]
		internal static class IsTeleportablePatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			internal static bool IsBackpackTeleportable(BackpackComponent backpack, bool allowAllItems)
			{
				if (backpack == null)
				{
					return true;
				}
				backpack.UpdateTeleportableStatus();
				Inventory inventory = backpack.GetInventory();
				if (inventory == null)
				{
					return true;
				}
				return inventory.IsTeleportable(allowAllItems);
			}

			private static void Postfix(Inventory __instance, bool allowAllItems, ref bool __result)
			{
				if (!__result || __instance == null || (Object)(object)Player.m_localPlayer == (Object)null || __instance != ((Humanoid)Player.m_localPlayer).GetInventory())
				{
					return;
				}
				if (Player.m_localPlayer.IsBackpackEquipped())
				{
					BackpackComponent equippedBackpack = Player.m_localPlayer.GetEquippedBackpack();
					if (equippedBackpack != null && !IsBackpackTeleportable(equippedBackpack, allowAllItems))
					{
						__result = false;
						return;
					}
				}
				List<ItemData> allItems = __instance.GetAllItems();
				if (allItems == null)
				{
					return;
				}
				foreach (ItemData item in allItems)
				{
					if (item != null && item.IsBackpack())
					{
						BackpackComponent backpackComponent = item.Data()?.GetOrCreate<BackpackComponent>();
						if (backpackComponent != null && !IsBackpackTeleportable(backpackComponent, allowAllItems))
						{
							__result = false;
							break;
						}
					}
				}
			}
		}

		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 bool RemoveItemPrefix(Inventory __instance, ItemData item)
		{
			if (__instance == null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return true;
			}
			if (_movingItemBetweenContainers || _droppingOutside)
			{
				return true;
			}
			if (CraftingContext.IsActive)
			{
				return true;
			}
			if (AdventureBackpacks.PerformYardSale || AdventureBackpacks.QuickDropping || AdventureBackpacks.BypassMoveProtection)
			{
				return true;
			}
			if (((Character)Player.m_localPlayer).IsDead())
			{
				return true;
			}
			if (__instance != ((Humanoid)Player.m_localPlayer).GetInventory())
			{
				return true;
			}
			if ((Object)(object)InventoryGui.instance != (Object)null && (Object)(object)InventoryGui.instance.m_currentContainer != (Object)null && !InventoryGui.instance.m_currentContainer.IsBackpackProxy() && __instance == InventoryGui.instance.m_currentContainer.GetInventory())
			{
				return true;
			}
			if (!item.TryGetBackpackItem(out var _))
			{
				return true;
			}
			AdventureBackpacks.Log.Debug("Checking for Backpack " + item.m_shared.m_name);
			if (item.IsItemFromQueue())
			{
				AdventureBackpacks.Log.Debug("Exiting RemoveItem for " + item.m_shared.m_name);
				return true;
			}
			BackpackComponent backpackComponent = item.Data().Get<BackpackComponent>();
			if (backpackComponent == null)
			{
				return true;
			}
			Inventory inventory = backpackComponent.GetInventory();
			if (inventory == null || inventory.m_inventory.Count == 0)
			{
				return true;
			}
			if (!Backpacks.PerformYardSale(Player.m_localPlayer, item, backpackOnly: true))
			{
				((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_yard_sale_blocked", 0, (Sprite)null, false);
				return false;
			}
			return true;
		}
	}
	internal static class InventoryGuiPatches
	{
		[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
		private static class InventoryGuiDoCraftingPatch
		{
			private class CraftUpgradeState
			{
				public ItemData UpgradeItem;

				public BackpackComponent Backpack;

				public Vector2i GridPos;

				public string ItemName;
			}

			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[HarmonyPrefix]
			[HarmonyPriority(900)]
			private static void Prefix(InventoryGui __instance, out CraftUpgradeState __state)
			{
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				CraftingContext.Enter();
				if ((Object)(object)__instance != (Object)null && __instance.m_craftUpgradeItem != null && __instance.m_craftUpgradeItem.IsBackpack())
				{
					ItemData craftUpgradeItem = __instance.m_craftUpgradeItem;
					BackpackComponent backpack = craftUpgradeItem.Data().Get<BackpackComponent>();
					__state = new CraftUpgradeState
					{
						UpgradeItem = craftUpgradeItem,
						Backpack = backpack,
						GridPos = craftUpgradeItem.m_gridPos,
						ItemName = (craftUpgradeItem.m_shared?.m_name ?? string.Empty)
					};
				}
				else
				{
					__state = null;
				}
			}

			[HarmonyFinalizer]
			[HarmonyPriority(100)]
			private static void Finalizer()
			{
				CraftingContext.Exit();
			}

			[HarmonyPostfix]
			private static void Postfix(InventoryGui __instance, CraftUpgradeState __state)
			{
				if ((Object)(object)Player.m_localPlayer == (Object)null)
				{
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if (__state == null || __state.Backpack == null)
				{
					return;
				}
				BackpackComponent backpack = __state.Backpack;
				ItemData upgradeItem = __state.UpgradeItem;
				Inventory inventory = ((Humanoid)localPlayer).GetInventory();
				ItemData val = null;
				bool flag = false;
				if (inventory != null)
				{
					if (backpack.Item != null && inventory.ContainsItem(backpack.Item))
					{
						flag = true;
						val = backpack.Item;
					}
					else
					{
						ItemData itemAt = inventory.GetItemAt(__state.GridPos.x, __state.GridPos.y);
						if (itemAt != null && itemAt.IsBackpack() && itemAt.m_shared != null && itemAt.m_shared.m_name == __state.ItemName)
						{
							flag = true;
							val = itemAt;
						}
						else
						{
							CraftingStation currentCraftingStation = localPlayer.GetCurrentCraftingStation();
							if (!((Object)(object)currentCraftingStation != (Object)null) || !currentCraftingStation.m_upgrader)
							{
								ItemData val2 = ((IEnumerable<ItemData>)inventory.GetAllItems()).FirstOrDefault((Func<ItemData, bool>)((ItemData i) => i.IsBackpack() && i.m_shared != null && i.m_shared.m_name == __state.ItemName));
								if (val2 != null)
								{
									flag = true;
									val = val2;
								}
							}
						}
					}
				}
				if (!flag)
				{
					Inventory inventory2 = backpack.GetInventory();
					if (inventory2 != null && inventory2.m_inventory.Count > 0)
					{
						Backpacks.PerformYardSale(localPlayer, upgradeItem, backpackOnly: true, 0, skipInventoryCheck: true);
					}
					return;
				}
				if (val != null)
				{
					BackpackComponent orCreate = val.Data().GetOrCreate<BackpackComponent>();
					orCreate.Load();
					Backpacks.ValidateBackpackInventorySizing(localPlayer, val);
					if (localPlayer.IsThisBackpackEquipped(val))
					{
						Container backpackContainer = localPlayer.GetBackpackContainerProxy();
						orCreate.UpdateContainerSizing(ref backpackContainer);
					}
				}
				((Humanoid)localPlayer).UpdateEquipmentStatusEffects();
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "OnSelectedItem")]
		private static class InventoryGuiOnSelectedItem
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[UsedImplicitly]
			private static Exception Finalizer(Exception __exception, InventoryGrid grid, ItemData item, Vector2i pos, Modifier mod, InventoryGui __instance)
			{
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0070: Invalid comparison between Unknown and I4
				if (__exception != null)
				{
					if (__exception is NullReferenceException && (Object)(object)__instance != (Object)null && (Object)(object)__instance.m_currentContainer == (Object)null && (Object)(object)grid != (Object)null && grid.GetInventory() != null && (Object)(object)Player.m_localPlayer != (Object)null && item != null && item.m_shared != null && Backpacks.BackpackTypes.Contains(item.m_shared.m_name) && (int)mod == 3)
					{
						((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, false);
						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
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[UsedImplicitly]
			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator ilGenerator)
			{
				List<CodeInstruction> instrs = instructions.ToList();
				int counter = 0;
				MethodInfo resetButtonStatus = AccessTools.DeclaredMethod(typeof(ZInput), "ResetButtonStatus", (Type[])null, (Type[])null);
				AccessTools.DeclaredMethod(typeof(Menu), "IsVisible", (Type[])null, (Type[])null);
				MethodInfo hideMethod = AccessTools.DeclaredMethod(typeof(InventoryGui), "Hide", (Type[])null, (Type[])null);
				MethodInfo showMethod = AccessTools.DeclaredMethod(typeof(InventoryGui), "Show", (Type[])null, (Type[])null);
				MethodInfo tutorialMethod = AccessTools.DeclaredMethod(typeof(Player), "ShowTutorial", (Type[])null, (Type[])null);
				MethodInfo zInputKeyDown = AccessTools.DeclaredMethod(typeof(ZInput), "GetKeyDown", new Type[2]
				{
					typeof(KeyCode),
					typeof(bool)
				}, (Type[])null);
				MethodInfo zInputButtonDown = AccessTools.DeclaredMethod(typeof(ZInput), "GetButtonDown", new Type[1] { typeof(string) }, (Type[])null);
				FieldInfo hiddenFramesField = AccessTools.DeclaredField(typeof(InventoryGui), "m_hiddenFrames");
				bool patchedHideBackpackMethod = false;
				bool patchedShowBackpackMethod = false;
				bool patchedDetectInputHideMethod = false;
				bool patchedDetectInputShowMethod = false;
				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);
						CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction);
						yield return LogMessage(instrs[i]);
						counter++;
						yield return LogMessage(ldArgInstruction);
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(InventoryGuiPatches), "HideBackpack", (Type[])null, (Type[])null)));
						counter++;
						patchedHideBackpackMethod = true;
					}
					else if (i > 6 && ((instrs[i].opcode == OpCodes.Call && instrs[i].operand.Equals(showMethod) && instrs[i - 1].opcode == OpCodes.Ldc_I4_1 && instrs[i - 2].opcode == OpCodes.Ldnull && instrs[i - 3].opcode == OpCodes.Ldarg_0) || (instrs[i - 4].opcode == OpCodes.Callvirt && instrs[i - 4].operand.Equals(tutorialMethod))))
					{
						CodeInstruction ldArgInstruction = new CodeInstruction(OpCodes.Ldloc_1, (object)null);
						if (instrs[i].labels.Count > 0)
						{
							CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction);
						}
						yield return LogMessage(instrs[i]);
						counter++;
						yield return LogMessage(ldArgInstruction);
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(InventoryGuiPatches), "ShowBackpack", (Type[])null, (Type[])null)));
						counter++;
						patchedShowBackpackMethod = true;
					}
					else if (i > 6 && i + 3 < instrs.Count && 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 + 3].opcode == OpCodes.Call && instrs[i + 3].operand.Equals(zInputButtonDown))
					{
						yield return LogMessage(instrs[i]);
						counter++;
						yield return LogMessage(instrs[i + 1]);
						counter++;
						Label label = (Label)instrs[i + 1].operand;
						CodeInstruction val = FindInstructionWithLabel(instrs, i + 2, label);
						if (val == null)
						{
							AdventureBackpacks.Log.Error($"Can't Find Instruction with Label {label}");
						}
						else
						{
							i++;
							Label detectHideLabel = ilGenerator.DefineLabel();
							val.labels.Add(detectHideLabel);
							yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_1, (object)null));
							counter++;
							yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
							counter++;
							yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(InventoryGuiPatches), "DetectInputToHide", (Type[])null, (Type[])null)));
							counter++;
							yield return LogMessage(new CodeInstruction(OpCodes.Brtrue, (object)detectHideLabel));
							counter++;
							patchedDetectInputHideMethod = true;
						}
					}
					else if (i > 6 && (instrs[i].opcode == OpCodes.Stloc_3 || instrs[i].opcode == OpCodes.Stloc_S || instrs[i].opcode == OpCodes.Stloc || instrs[i].opcode == OpCodes.Stloc_0 || instrs[i].opcode == OpCodes.Stloc_1 || instrs[i].opcode == OpCodes.Stloc_2) && instrs[i + 1].opcode == OpCodes.Ldarg_0 && instrs[i + 2].opcode == OpCodes.Ldfld && instrs[i + 2].operand.Equals(hiddenFramesField) && instrs.GetRange(Math.Max(0, i - 10), Math.Min(10, i)).Any((CodeInstruction inst) => inst.opcode == OpCodes.Ldstr && "JoyButtonY".Equals(inst.operand)))
					{
						yield return LogMessage(instrs[i]);
						counter++;
						Label detectHideLabel = ilGenerator.DefineLabel();
						yield return LogMessage(CreateLdlocFromStloc(instrs[i]));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Brtrue, (object)detectHideLabel));
						counter++;
						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(CreateStlocFromStloc(instrs[i]));
						counter++;
						instrs[i + 1].labels.Add(detectHideLabel);
						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 CreateLdlocFromStloc(CodeInstruction stloc)
				{
					//IL_0018: Unknown result type (might be due to invalid IL or missing references)
					//IL_001e: Expected O, but got Unknown
					//IL_0036: Unknown result type (might be due to invalid IL or missing references)
					//IL_003c: Expected O, but got Unknown
					//IL_0054: Unknown result type (might be due to invalid IL or missing references)
					//IL_005a: Expected O, but got Unknown
					//IL_0072: Unknown result type (might be due to invalid IL or missing references)
					//IL_0078: Expected O, but got Unknown
					//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
					//IL_00ac: Expected O, but got Unknown
					//IL_0095: Unknown result type (might be due to invalid IL or missing references)
					//IL_009b: Expected O, but got Unknown
					if (!(stloc.opcode == OpCodes.Stloc_0))
					{
						if (!(stloc.opcode == OpCodes.Stloc_1))
						{
							if (!(stloc.opcode == OpCodes.Stloc_2))
							{
								if (!(stloc.opcode == OpCodes.Stloc_3))
								{
									if (!(stloc.opcode == OpCodes.Stloc_S))
									{
										return new CodeInstruction(OpCodes.Ldloc, stloc.operand);
									}
									return new CodeInstruction(OpCodes.Ldloc_S, stloc.operand);
								}
								return new CodeInstruction(OpCodes.Ldloc_3, (object)null);
							}
							return new CodeInstruction(OpCodes.Ldloc_2, (object)null);
						}
						return new CodeInstruction(OpCodes.Ldloc_1, (object)null);
					}
					return new CodeInstruction(OpCodes.Ldloc_0, (object)null);
				}
				static CodeInstruction CreateStlocFromStloc(CodeInstruction stloc)
				{
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0012: Expected O, but got Unknown
					return new CodeInstruction(stloc.opcode, stloc.operand);
				}
				static CodeInstruction FindInstructionWithLabel(List<CodeInstruction> codeInstructions, int index, Label label2)
				{
					if (index >= codeInstructions.Count)
					{
						return null;
					}
					if (codeInstructions[index].labels.Contains(label2))
					{
						return codeInstructions[index];
					}
					return FindInstructionWithLabel(codeInstructions, index + 1, label2);
				}
				CodeInstruction LogMessage(CodeInstruction instruction)
				{
					AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}");
					return instruction;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(InventoryGui __instance)
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null && ContainerTabs.HasActiveExternalContainer && ConfigRegistry.EnableContainerTabs.Value)
				{
					ContainerTabs.Update(__instance, localPlayer);
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
		private static class InventoryGuiSetupRequirementPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[HarmonyPrefix]
			[HarmonyPriority(900)]
			private static void Prefix(Player player)
			{
				if ((Object)(object)player != (Object)null && (Object)(object)player == (Object)(object)Player.m_localPlayer)
				{
					CraftingContext.Enter();
				}
			}

			[HarmonyPostfix]
			[HarmonyPriority(0)]
			private static void Postfix(Transform elementRoot, Requirement req, Player player, bool craft, int quality, int craftMultiplier, ref bool __result)
			{
				//IL_0104: Unknown result type (might be due to invalid IL or missing references)
				//IL_0109: Unknown result type (might be due to invalid IL or missing references)
				//IL_011d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0147: Unknown result type (might be due to invalid IL or missing references)
				//IL_0140: Unknown result type (might be due to invalid IL or missing references)
				if (!__result || (Object)(object)elementRoot == (Object)null || req == null || (Object)(object)req.m_resItem == (Object)null || req.m_resItem.m_itemData == null || (Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || (CraftFromBackpack.DisplayTotalIngredientCount != null && !CraftFromBackpack.DisplayTotalIngredientCount.Value) || !CraftingContext.CanCraftFromBackpack)
				{
					return;
				}
				Transform val = elementRoot.Find("res_amount");
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				TMP_Text component = ((Component)val).GetComponent<TMP_Text>();
				if ((Object)(object)component == (Object)null || string.IsNullOrEmpty(component.text))
				{
					return;
				}
				string text = component.text.Trim();
				Regex ingredientRegex = CraftFromBackpack.IngredientRegex;
				if ((ingredientRegex != null && ingredientRegex.IsMatch(text)) || !int.TryParse(text, out var result))
				{
					return;
				}
				string name = req.m_resItem.m_itemData.m_shared.m_name;
				int num = ((Humanoid)player).GetInventory().CountItems(name, -1, true);
				component.text = $"{num}/{result}";
				if (!(((Graphic)component).color == Color.white))
				{
					if (num >= result)
					{
						((Graphic)component).color = Color.white;
					}
					else
					{
						((Graphic)component).color = ((Mathf.Sin(Time.time * 10f) > 0f) ? Color.red : Color.white);
					}
				}
			}

			[HarmonyFinalizer]
			[HarmonyPriority(100)]
			private static void Finalizer(Player player)
			{
				if ((Object)(object)player != (Object)null && (Object)(object)player == (Object)(object)Player.m_localPlayer)
				{
					CraftingContext.Exit();
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "UpdateRecipeList")]
		private static class InventoryGuiUpdateRecipeListPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[HarmonyPrefix]
			[HarmonyPriority(900)]
			private static void Prefix()
			{
				CraftingContext.Enter();
			}

			[HarmonyFinalizer]
			[HarmonyPriority(100)]
			private static void Finalizer()
			{
				CraftingContext.Exit();
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "UpdateRecipe")]
		private static class InventoryGuiUpdateRecipePatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[HarmonyPrefix]
			[HarmonyPriority(900)]
			private static void Prefix(Player player)
			{
				if ((Object)(object)player != (Object)null && (Object)(object)player == (Object)(object)Player.m_localPlayer)
				{
					CraftingContext.Enter();
				}
			}

			[HarmonyFinalizer]
			[HarmonyPriority(100)]
			private static void Finalizer(Player player)
			{
				if ((Object)(object)player != (Object)null && (Object)(object)player == (Object)(object)Player.m_localPlayer)
				{
					CraftingContext.Exit();
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "OnCraftPressed")]
		private static class InventoryGuiOnCraftPressedPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[HarmonyPrefix]
			[HarmonyPriority(900)]
			private static void Prefix()
			{
				CraftingContext.Enter();
			}

			[HarmonyFinalizer]
			[HarmonyPriority(100)]
			private static void Finalizer()
			{
				CraftingContext.Exit();
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "Hide")]
		private static class InventoryGuiHidePatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[HarmonyPostfix]
			private static void Postfix(InventoryGui __instance)
			{
				BackpackIsOpen = false;
				CraftingContext.Reset();
				ContainerTabs.Reset(__instance);
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "CloseContainer")]
		private static class InventoryGuiCloseContainerPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[HarmonyPostfix]
			private static void Postfix(InventoryGui __instance)
			{
				ContainerTabs.Reset(__instance);
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "Show", new Type[]
		{
			typeof(Container),
			typeof(int)
		})]
		private static class InventoryGuiShowPatch
		{
			private static bool _isOpening;

			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[HarmonyPrefix]
			private static void Prefix(InventoryGui __instance, ref Container container, ref int activeGroup)
			{
				if (!((Object)(object)container == (Object)null) || activeGroup != 3 || ConfigRegistry.OpenWithCraftingStation == null || !ConfigRegistry.OpenWithCraftingStation.Value || (ConfigRegistry.OpenWithHoverInteract != null && ConfigRegistry.OpenWithHoverInteract.Value))
				{
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer == (Object)null || (Object)(object)localPlayer.GetCurrentCraftingStation() == (Object)null || BackpackIsOpen || !localPlayer.CanOpenBackpack())
				{
					return;
				}
				BackpackComponent equippedBackpack = localPlayer.GetEquippedBackpack();
				if (equippedBackpack != null)
				{
					Container backpackContainer = localPlayer.GetBackpackContainerProxy();
					if (!((Object)(object)backpackContainer == (Object)null))
					{
						equippedBackpack.UpdateContainerSizing(ref backpackContainer);
						BackpackIsOpen = true;
						container = backpackContainer;
					}
				}
			}

			[HarmonyPostfix]
			private static void Postfix(InventoryGui __instance, Container container, int activeGroup)
			{
				if (_isOpening)
				{
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer == (Object)null)
				{
					return;
				}
				if ((Object)(object)container != (Object)null && !container.IsBackpackProxy())
				{
					if (ConfigRegistry.EnableContainerTabs != null && ConfigRegistry.EnableContainerTabs.Value && localPlayer.CanOpenBackpack())
					{
						ContainerTabs.InitializeWithContainer(container, __instance, localPlayer);
					}
					else
					{
						ContainerTabs.Reset(__instance);
					}
				}
				else if ((Object)(object)container != (Object)null && container.IsBackpackProxy())
				{
					if (!ContainerTabs.IsViewingBackpack)
					{
						ContainerTabs.ClearExternalContainer(__instance);
					}
				}
				else if ((Object)(object)container == (Object)null && activeGroup == 3)
				{
					if (ConfigRegistry.OpenWithCraftingStation != null && ConfigRegistry.OpenWithCraftingStation.Value && (ConfigRegistry.OpenWithHoverInteract == null || !ConfigRegistry.OpenWithHoverInteract.Value) && !((Object)(object)localPlayer.GetCurrentCraftingStation() == (Object)null) && !BackpackIsOpen && localPlayer.CanOpenBackpack())
					{
						_isOpening = true;
						try
						{
							localPlayer.OpenBackpack(__instance, activeGroup);
						}
						finally
						{
							_isOpening = false;
						}
					}
				}
				else if ((Object)(object)container == (Object)null)
				{
					ContainerTabs.Reset(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "OnTakeAll")]
		private static class InventoryGuiOnTakeAllPatch
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				return !PlayerExtensions.IsDedicatedOrHeadless();
			}

			[HarmonyPrefix]
			private static void Prefix()
			{
				AdventureBackpacks.PushBypassMoveProtection();
			}

			[HarmonyFinalizer]
			private static void Finalizer()
			{
				AdventureBackpacks.PopBypassMoveProtection();
			}
		}

		public static bool BackpackIsOpen;

		public static bool BackpackEquipped;

		private static bool _showBackpack;

		private static bool _hasLoggedTextInputError;

		public static bool CheckForTextInput()
		{
			try
			{
				return TextInput.IsVisible();
			}
			catch (Exception arg)
			{
				if (!_hasLoggedTextInputError)
				{
					_hasLoggedTextInputError = true;
					AdventureBackpacks.Log.Error($"Exception in CheckForTextInput: {arg}");
				}
				return false;
			}
		}

		public static void ShowBackpack(Player player, InventoryGui instance)
		{
			if ((Object)(object)player == (Object)null || (Object)(object)instance == (Object)null)
			{
				return;
			}
			if (ConfigRegistry.OpenWithInventory != null && 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)
		{
			try
			{
				if (!BackpackIsOpen)
				{
					return;
				}
				if ((Object)(object)instance != (Object)null)
				{
					instance.CloseContainer();
					BackpackIsOpen = false;
					if (ConfigRegistry.CloseInventory != null && ConfigRegistry.CloseInventory.Value && (ConfigRegistry.OpenWithHoverInteract == null || !ConfigRegistry.OpenWithHoverInteract.Value))
					{
						instance.Hide();
					}
				}
				else
				{
					BackpackIsOpen = false;
				}
			}
			catch (Exception ex)
			{
				BackpackIsOpen = false;
				AdventureBackpacks.Log?.Warning("Error hiding backpack: " + ex.Message);
			}
		}

		public static bool DetectInputToHide(Player player, InventoryGui instance)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: 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)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: 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_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: 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_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null || (Object)(object)instance == (Object)null || PlayerExtensions.IsDedicatedOrHeadless() || ZInput.instance == null)
			{
				return false;
			}
			KeyboardShortcut value = ConfigRegistry.HotKeyOpen.Value;
			KeyCode mainKey = ((KeyboardShortcut)(ref value)).MainKey;
			value = ConfigRegistry.HotKeyDrop.Value;
			KeyCode mainKey2 = ((KeyboardShortcut)(ref value)).MainKey;
			int num;
			if (ZInput.instance == null || !ZInput.GetKeyDown(mainKey, true))
			{
				value = ConfigRegistry.HotKeyOpen.Value;
				if (!((KeyboardShortcut)(ref value)).IsDown())
				{
					num = (Input.GetKeyDown(mainKey) ? 1 : 0);
					goto IL_0075;
				}
			}
			num = 1;
			goto IL_0075;
			IL_0075:
			if (ConfigRegistry.OutwardMode.Value)
			{
				if (ZInput.instance == null || !ZInput.GetKeyDown(mainKey2, true))
				{
					value = ConfigRegistry.HotKeyDrop.Value;
					if (!((KeyboardShortcut)