Decompiled source of Chest Stacks v2.0.0

plugins/ChestStacks.dll

Decompiled 12 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("BenjSammy")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0")]
[assembly: AssemblyProduct("Chest Stacks by BenjSammy")]
[assembly: AssemblyTitle("ChestStacks")]
[assembly: AssemblyVersion("2.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[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 BenjSammy.ChestStacks
{
	[BepInPlugin("benjsammy.cheststacks", "Chest Stacks by BenjSammy", "2.0.0")]
	public sealed class ChestStacksPlugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		private ConfigEntry<int> _stackLimit;

		private ServerStackSync _sync;

		private bool _french;

		private float _nextError;

		private void Awake()
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			bool flag = (_french = UsesFrench());
			_stackLimit = ((BaseUnityPlugin)this).Config.Bind<int>("Stacks", "Stack limit", 0, new ConfigDescription(flag ? "Nombre maximal d’objets empilables par case de coffre. 0 = illimité. Les piles existantes sont conservées si tu réduis la limite. En multijoueur, le serveur impose sa valeur aux joueurs." : "Maximum stackable items per chest slot. 0 = unlimited. Existing stacks are preserved when lowering the limit. In multiplayer, the server enforces its value on player clients.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, int.MaxValue), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Category = (flag ? "Piles" : "Stacks"),
					DispName = (flag ? "Limite par pile (0 = illimité)" : "Stack limit (0 = unlimited)"),
					CustomDrawer = delegate(ConfigEntryBase entry)
					{
						DrawLimit((ConfigEntry<int>)(object)entry);
					}
				}
			}));
			_harmony = new Harmony("benjsammy.cheststacks");
			try
			{
				_sync = new ServerStackSync(new StackNetwork(), () => _stackLimit.Value);
				GameInventory gameInventory = new GameInventory(!Application.isBatchMode);
				if (!Application.isBatchMode && !gameInventory.CanFormatAmounts)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"Chest amount labels could not be resolved. Chest storage remains active.");
				}
				int num = ChestPatches.Install(_harmony, gameInventory, () => _sync.EffectiveLimit);
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"Chest Stacks loaded. {num} native stack limit reads patched.");
			}
			catch (Exception ex)
			{
				_harmony.UnpatchSelf();
				_harmony = null;
				ChestPatches.Reset();
				((BaseUnityPlugin)this).Logger.LogError((object)("Chest Stacks could not start with this Valheim API. " + ex));
			}
		}

		private void DrawLimit(ConfigEntry<int> entry)
		{
			int result;
			if (_sync != null && _sync.Locked)
			{
				int effectiveLimit = _sync.EffectiveLimit;
				string text = ((effectiveLimit >= 0) ? ((effectiveLimit != 0) ? effectiveLimit.ToString(CultureInfo.InvariantCulture) : (_french ? "Illimité" : "Unlimited")) : (_french ? "Connexion…" : "Connecting…"));
				GUILayout.Label((_french ? "Imposé par le serveur : " : "Enforced by server: ") + text, Array.Empty<GUILayoutOption>());
			}
			else if (int.TryParse(GUILayout.TextField(entry.Value.ToString(CultureInfo.InvariantCulture), Array.Empty<GUILayoutOption>()), NumberStyles.Integer, CultureInfo.InvariantCulture, out result))
			{
				entry.Value = Math.Max(0, result);
			}
		}

		private static bool UsesFrench()
		{
			string text = PlayerPrefs.GetString("language", "English");
			Type type = AccessTools.TypeByName("Localization");
			if (type != null)
			{
				try
				{
					MethodInfo methodInfo = AccessTools.Method(type, "GetSelectedLanguage", Type.EmptyTypes, (Type[])null);
					object obj = (((object)methodInfo == null || methodInfo.IsStatic) ? null : AccessTools.PropertyGetter(type, "instance")?.Invoke(null, null));
					if (methodInfo != null && (methodInfo.IsStatic || obj != null))
					{
						text = (methodInfo.Invoke(obj, null) as string) ?? text;
					}
				}
				catch (Exception)
				{
				}
			}
			if (!string.Equals(text, "French", StringComparison.OrdinalIgnoreCase) && !string.Equals(text, "Français", StringComparison.OrdinalIgnoreCase) && !string.Equals(text, "fr", StringComparison.OrdinalIgnoreCase))
			{
				return text.StartsWith("fr-", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		private void Update()
		{
			if (_sync == null || _harmony == null)
			{
				return;
			}
			try
			{
				_sync.Tick(Time.realtimeSinceStartup);
			}
			catch (Exception ex)
			{
				if (!(Time.realtimeSinceStartup < _nextError))
				{
					_nextError = Time.realtimeSinceStartup + 30f;
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Chest Stacks setting synchronization failed. " + ex));
				}
			}
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			ChestPatches.Reset();
		}
	}
	internal sealed class ConfigurationManagerAttributes
	{
		public string DispName;

		public string Category;

		public Action<ConfigEntryBase> CustomDrawer;
	}
	internal static class ChestPatches
	{
		private static class ReadingScope
		{
			internal static void Enter(object __instance, out object __state)
			{
				__state = _readingInventory;
				_readingInventory = __instance;
			}

			internal static void Exit(object __state)
			{
				_readingInventory = __state;
			}
		}

		private static class LoadScope
		{
			internal readonly struct State
			{
				internal readonly object Inventory;

				internal readonly int Count;

				internal State(object inventory, int count)
				{
					Inventory = inventory;
					Count = count;
				}
			}

			internal static void Enter(object __instance, out State __state)
			{
				__state = new State(_loadingInventory, _savedCount);
				_loadingInventory = __instance;
				_savedCount = 0;
			}

			internal static void Exit(State __state)
			{
				_loadingInventory = __state.Inventory;
				_savedCount = __state.Count;
			}
		}

		private static class SavedStackScope
		{
			internal static void Enter(object __instance, int __1, out int __state)
			{
				__state = _savedCount;
				_savedCount = ((__instance == _loadingInventory) ? __1 : 0);
			}

			internal static void Exit(int __state)
			{
				_savedCount = __state;
			}
		}

		private static class SlotTransfer
		{
			internal static bool Before(object __instance, object __1, ref int __2, int __3, int __4, ref bool __result, out bool __state)
			{
				__state = false;
				if (__1 == null)
				{
					return true;
				}
				int num = ItemLimit(__1, __instance);
				if (Math.Min(_game.Stack(__1), __2) <= num)
				{
					return true;
				}
				int num2 = SlotRoom(__instance, __1, _game.Slot(__instance, __3, __4), num);
				if (num2 == 0)
				{
					__result = false;
					return false;
				}
				__2 = num2;
				__state = true;
				return true;
			}

			internal static void After(ref bool __result, bool __state)
			{
				if (__state)
				{
					__result = false;
				}
			}
		}

		private static Func<int> _stackLimit;

		private static readonly object ChestTag = new object();

		private static ConditionalWeakTable<object, object> _chests = new ConditionalWeakTable<object, object>();

		private static GameInventory _game;

		[ThreadStatic]
		private static object _readingInventory;

		[ThreadStatic]
		private static object _loadingInventory;

		[ThreadStatic]
		private static int _savedCount;

		private static int ChestCapacity
		{
			get
			{
				int num = _stackLimit?.Invoke() ?? 0;
				if (num != 0)
				{
					return num;
				}
				return int.MaxValue;
			}
		}

		internal static int Install(Harmony harmony, GameInventory game, Func<int> stackLimit = null)
		{
			_game = game;
			_stackLimit = stackLimit;
			MethodInfo[] source = (from method in game.InventoryType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
				where !method.IsStatic && !method.ContainsGenericParameters
				select method).ToArray();
			MethodInfo[] array = source.Where(ReadsMaximum).ToArray();
			if (!array.Any((MethodInfo method) => method.Name == "AddItem"))
			{
				throw new MissingMemberException("Inventory.AddItem no longer reads the native stack limit.");
			}
			MethodInfo[] array2 = array;
			foreach (MethodInfo methodInfo in array2)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, Hook("InventoryLimits"), (HarmonyMethod)null, (HarmonyMethod)null);
			}
			int num2 = 0;
			HashSet<MethodInfo> hashSet = new HashSet<MethodInfo>();
			Type[] nestedTypes = game.InventoryType.GetNestedTypes(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			for (int num = 0; num < nestedTypes.Length; num++)
			{
				array2 = nestedTypes[num].GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo2 in array2)
				{
					if (!methodInfo2.Name.StartsWith("<", StringComparison.Ordinal) || !ReadsMaximum(methodInfo2))
					{
						continue;
					}
					int num4 = methodInfo2.Name.IndexOf('>');
					if (num4 < 2)
					{
						continue;
					}
					string name = methodInfo2.Name.Substring(1, num4 - 1);
					MethodInfo[] array3 = source.Where((MethodInfo method) => method.Name == name).ToArray();
					if (array3.Length == 0)
					{
						continue;
					}
					MethodInfo[] array4 = array3;
					foreach (MethodInfo methodInfo3 in array4)
					{
						if (hashSet.Add(methodInfo3))
						{
							harmony.Patch((MethodBase)methodInfo3, Hook(typeof(ReadingScope), "Enter"), (HarmonyMethod)null, (HarmonyMethod)null, Hook(typeof(ReadingScope), "Exit"), (HarmonyMethod)null);
						}
					}
					harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, (HarmonyMethod)null, Hook("ClosureLimits"), (HarmonyMethod)null, (HarmonyMethod)null);
					num2++;
				}
			}
			harmony.Patch((MethodBase)game.ContainerLoad, Hook("RegisterChest"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)game.ContainerAwake, (HarmonyMethod)null, Hook("RegisterChest"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			if (game.AddDefaultItems != null)
			{
				harmony.Patch((MethodBase)game.AddDefaultItems, Hook("RegisterChest"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			harmony.Patch((MethodBase)game.LoadInventory, Hook(typeof(LoadScope), "Enter"), (HarmonyMethod)null, (HarmonyMethod)null, Hook(typeof(LoadScope), "Exit"), (HarmonyMethod)null);
			foreach (MethodInfo item in source.Where(IsSavedStackLoader))
			{
				harmony.Patch((MethodBase)item, Hook(typeof(SavedStackScope), "Enter"), (HarmonyMethod)null, (HarmonyMethod)null, Hook(typeof(SavedStackScope), "Exit"), (HarmonyMethod)null);
			}
			harmony.Patch((MethodBase)game.AddItem, Hook("AddOversized"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)game.MoveItem, Hook("MoveOversized"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)game.MoveAll, Hook("MoveAllOversized"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)game.MoveAt, Hook(typeof(SlotTransfer), "Before"), Hook(typeof(SlotTransfer), "After"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)game.DropItem, Hook("DropOversized"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			if (game.GridDrop != null)
			{
				harmony.Patch((MethodBase)game.GridDrop, Hook("PreventOversizedSwap"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (game.GridUpdate != null)
			{
				harmony.Patch((MethodBase)game.GridUpdate, (HarmonyMethod)null, Hook("ChestAmountLabels"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (game.CanCheckDrag)
			{
				harmony.Patch((MethodBase)game.CanDropDrag, Hook("ChestTargetHighlight"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			return array.Length + num2;
		}

		private static bool IsSavedStackLoader(MethodInfo method)
		{
			if (method.Name != "AddItem" || method.ReturnType != typeof(bool))
			{
				return false;
			}
			ParameterInfo[] parameters = method.GetParameters();
			if (parameters.Length >= 9 && (parameters[0].ParameterType == typeof(int) || parameters[0].ParameterType == typeof(string)) && parameters[1].ParameterType == typeof(int))
			{
				return parameters[2].ParameterType == typeof(float);
			}
			return false;
		}

		private static HarmonyMethod Hook(string method)
		{
			return Hook(typeof(ChestPatches), method);
		}

		private static HarmonyMethod Hook(Type type, string method)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			return new HarmonyMethod(type.GetMethod(method, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
		}

		private static bool ReadsMaximum(MethodInfo method)
		{
			if (!method.ContainsGenericParameters && method.GetMethodBody() != null)
			{
				return PatchProcessor.GetOriginalInstructions((MethodBase)method, (ILGenerator)null).Any(IsMaximumRead);
			}
			return false;
		}

		private static bool IsMaximumRead(CodeInstruction instruction)
		{
			if (instruction.opcode == OpCodes.Ldfld)
			{
				return object.Equals(instruction.operand, _game.MaximumField);
			}
			return false;
		}

		private static IEnumerable<CodeInstruction> InventoryLimits(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo limit = typeof(ChestPatches).GetMethod("Limit", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (CodeInstruction instruction in instructions)
			{
				yield return instruction;
				if (IsMaximumRead(instruction))
				{
					yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
					yield return new CodeInstruction(OpCodes.Call, (object)limit);
				}
			}
		}

		private static IEnumerable<CodeInstruction> ClosureLimits(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo limit = typeof(ChestPatches).GetMethod("CurrentLimit", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (CodeInstruction instruction in instructions)
			{
				yield return instruction;
				if (IsMaximumRead(instruction))
				{
					yield return new CodeInstruction(OpCodes.Call, (object)limit);
				}
			}
		}

		private static void ChestAmountLabels(object __instance)
		{
			if (IsChest(_game.GridInventory.GetValue(__instance)))
			{
				_game.ShowChestAmounts(__instance, _stackLimit?.Invoke() ?? 0);
			}
		}

		private static void RegisterChest(object __instance)
		{
			if (!_game.IsChest(__instance))
			{
				return;
			}
			object obj = _game.ContainerInventory(__instance);
			if (obj != null)
			{
				_chests.GetValue(obj, (object _) => ChestTag);
			}
		}

		private static bool IsChest(object inventory)
		{
			object value;
			if (inventory != null)
			{
				return _chests.TryGetValue(inventory, out value);
			}
			return false;
		}

		private static int Limit(int normal, object inventory)
		{
			if (normal <= 1 || !IsChest(inventory))
			{
				return normal;
			}
			int num = ChestCapacity;
			if (num < 0)
			{
				num = normal;
			}
			if (inventory != _loadingInventory)
			{
				return num;
			}
			return Math.Max(num, _savedCount);
		}

		private static int CurrentLimit(int normal)
		{
			return Limit(normal, _readingInventory);
		}

		private static int ItemLimit(object item, object inventory)
		{
			return Math.Max(1, Limit(_game.NormalLimit(item), inventory));
		}

		private static bool AddOversized(object __instance, object __0, ref bool __result)
		{
			if (__0 == null)
			{
				return true;
			}
			int num = ItemLimit(__0, __instance);
			int num2 = _game.Stack(__0);
			if (num2 <= num || _game.Contains(__instance, __0))
			{
				return true;
			}
			__result = TransferPieces(__instance, null, __0, num2, num);
			return false;
		}

		private static bool MoveOversized(object __instance, object __0, object __1)
		{
			if (__0 == null || __1 == null || __0 == __instance || !_game.Contains(__0, __1))
			{
				return true;
			}
			int num = ItemLimit(__1, __instance);
			int num2 = _game.Stack(__1);
			if (num2 <= num)
			{
				return true;
			}
			TransferPieces(__instance, __0, __1, num2, num);
			return false;
		}

		private static bool MoveAllOversized(object __instance, object __0)
		{
			if (__0 == null || __instance == __0 || (!IsChest(__0) && !IsChest(__instance)))
			{
				return true;
			}
			object[] array = _game.Items(__0);
			if (!array.Any((object item2) => _game.Stack(item2) > ItemLimit(item2, __instance)))
			{
				return true;
			}
			object[] array2 = array;
			foreach (object item in array2)
			{
				if (_game.Contains(__0, item))
				{
					_game.Move(__instance, __0, item);
				}
			}
			return false;
		}

		private static bool TransferPieces(object to, object from, object item, int remaining, int maximum)
		{
			while (remaining > 0)
			{
				int num = Math.Min(maximum, remaining);
				object item2 = _game.Piece(item, num);
				bool flag = false;
				int num2 = 0;
				try
				{
					flag = _game.Add(to, item2);
				}
				finally
				{
					num2 = ((flag || _game.Contains(to, item2)) ? num : Math.Max(0, Math.Min(num, num - _game.Stack(item2))));
					if (num2 > 0)
					{
						if (from == null)
						{
							_game.SetStack(item, remaining - num2);
						}
						else
						{
							_game.Remove(from, item, num2);
						}
					}
				}
				remaining -= num2;
				if (num2 < num)
				{
					return false;
				}
			}
			return true;
		}

		private static int SlotRoom(object inventory, object item, object target, int limit)
		{
			if (target == null)
			{
				return limit;
			}
			if (target == item || !_game.SameType(item, target))
			{
				return 0;
			}
			return Math.Max(0, Math.Min(limit, ItemLimit(target, inventory) - _game.Stack(target)));
		}

		private static bool PreventOversizedSwap(object __instance, object __0, object __1, int __2, object __3, ref bool __result)
		{
			object value = _game.GridInventory.GetValue(__instance);
			if (value == null || __0 == null || __1 == null || __2 <= 0 || (!IsChest(value) && !IsChest(__0)) || !_game.Contains(__0, __1))
			{
				return true;
			}
			int x = _game.X(__3);
			int y = _game.Y(__3);
			object obj = _game.Slot(value, x, y);
			if (obj == __1)
			{
				return true;
			}
			int num = _game.Stack(__1);
			int num2 = Math.Min(num, __2);
			int num3 = ItemLimit(__1, value);
			bool flag = obj != null && _game.Stack(obj) > ItemLimit(obj, __0);
			if (num2 <= num3 && !flag)
			{
				return true;
			}
			int num4 = Math.Min(num2, SlotRoom(value, __1, obj, num3));
			if (num4 > 0)
			{
				_game.MoveSlot(value, __0, __1, num4, x, y);
			}
			int num5 = (_game.Contains(__0, __1) ? _game.Stack(__1) : 0);
			__result = num - num5 >= num2;
			return false;
		}

		private static bool ChestTargetHighlight(object __instance, object __0, ref bool __result)
		{
			if (__0 == null)
			{
				return true;
			}
			object inventory = _game.CurrentChest(__instance);
			if (!IsChest(inventory) || !_game.Contains(inventory, __0))
			{
				return true;
			}
			object value = _game.DragItem.GetValue(__instance);
			if (value == null || value == __0 || !_game.SameType(__0, value))
			{
				return true;
			}
			__result = _game.Stack(__0) < ItemLimit(__0, inventory);
			return false;
		}

		private static bool DropOversized(object __0, int __1, Vector3 __2, Quaternion __3, ref object __result)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			if (__0 == null)
			{
				return true;
			}
			int num = _game.NormalLimit(__0);
			int num2 = ((__1 > 0) ? __1 : _game.Stack(__0));
			if (num <= 1 || num2 <= num)
			{
				return true;
			}
			List<object> list = new List<object>();
			try
			{
				int num3 = num2;
				while (num3 > 0)
				{
					int num4 = Math.Min(num3, num);
					object item = _game.Piece(__0, num4);
					object obj = _game.Spawn(item, num4, __2, __3);
					if (obj == null)
					{
						throw new InvalidOperationException("Valheim did not create the item drop.");
					}
					list.Add(obj);
					num3 -= num4;
				}
			}
			catch
			{
				foreach (object item2 in list)
				{
					_game.UndoDrop(item2);
				}
				throw;
			}
			__result = list[0];
			return false;
		}

		internal static void Reset()
		{
			_game = null;
			_stackLimit = null;
			_chests = new ConditionalWeakTable<object, object>();
			_readingInventory = null;
			_loadingInventory = null;
			_savedCount = 0;
		}
	}
	internal sealed class GameInventory
	{
		internal const BindingFlags Members = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		internal readonly Type InventoryType;

		internal readonly Type ContainerType;

		internal readonly Type GridType;

		internal readonly Type GuiType;

		internal readonly FieldInfo MaximumField;

		internal readonly FieldInfo GridInventory;

		internal readonly FieldInfo DragItem;

		internal readonly FieldInfo OpenContainer;

		internal readonly MethodInfo AddItem;

		internal readonly MethodInfo MoveItem;

		internal readonly MethodInfo MoveAt;

		internal readonly MethodInfo MoveAll;

		internal readonly MethodInfo LoadInventory;

		internal readonly MethodInfo ContainerAwake;

		internal readonly MethodInfo ContainerLoad;

		internal readonly MethodInfo AddDefaultItems;

		internal readonly MethodInfo GridDrop;

		internal readonly MethodInfo GridUpdate;

		internal readonly MethodInfo CanDropDrag;

		internal readonly MethodInfo DropItem;

		private readonly FieldInfo _gridElements;

		private readonly FieldInfo _elementAmount;

		private readonly PropertyInfo _amountText;

		private readonly FieldInfo _containerInventory;

		private readonly FieldInfo _rootOverride;

		private readonly FieldInfo _view;

		private readonly FieldInfo _stack;

		private readonly FieldInfo _shared;

		private readonly FieldInfo _x;

		private readonly FieldInfo _y;

		private readonly FieldInfo _itemName;

		private readonly FieldInfo _quality;

		private readonly FieldInfo _worldLevel;

		private readonly FieldInfo _variant;

		private readonly MethodInfo _clone;

		private readonly MethodInfo _contains;

		private readonly MethodInfo _removeAmount;

		private readonly MethodInfo _all;

		private readonly MethodInfo _at;

		private readonly MethodInfo _sameType;

		private readonly PropertyInfo _sceneInstance;

		private readonly MethodInfo _destroy;

		internal bool CanFormatAmounts
		{
			get
			{
				if (_gridElements != null && _elementAmount != null && _amountText != null && _amountText.CanRead)
				{
					return _amountText.CanWrite;
				}
				return false;
			}
		}

		internal bool CanCheckDrag
		{
			get
			{
				if (CanDropDrag != null && DragItem != null)
				{
					return OpenContainer != null;
				}
				return false;
			}
		}

		internal GameInventory(bool client)
		{
			InventoryType = FindType("Inventory");
			ContainerType = FindType("Container");
			Type type = FindType("ItemDrop");
			Type type2 = type.GetNestedType("ItemData", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new TypeLoadException("ItemDrop.ItemData");
			_shared = Field(type2, "m_shared");
			MaximumField = Field(_shared.FieldType, "m_maxStackSize");
			_stack = Field(type2, "m_stack");
			_clone = Method(type2, "Clone");
			_sameType = type2.GetMethod("IsSameType", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { type2 }, null);
			if (_sameType == null)
			{
				_itemName = Field(_shared.FieldType, "m_name");
				_quality = Field(type2, "m_quality");
				_worldLevel = type2.GetField("m_worldLevel", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				_variant = type2.GetField("m_variant", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			}
			_containerInventory = Field(ContainerType, "m_inventory");
			_rootOverride = ContainerType.GetField("m_rootObjectOverride", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			_view = ContainerType.GetField("m_nview", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			ContainerAwake = Method(ContainerType, "Awake");
			ContainerLoad = Method(ContainerType, "Load");
			AddDefaultItems = ContainerType.GetMethod("AddDefaultItems", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
			AddItem = Method(InventoryType, "AddItem", type2);
			MoveItem = Method(InventoryType, "MoveItemToThis", InventoryType, type2);
			MoveAt = Method(InventoryType, "MoveItemToThis", InventoryType, type2, typeof(int), typeof(int), typeof(int));
			MoveAll = Method(InventoryType, "MoveAll", InventoryType);
			LoadInventory = Method(InventoryType, "Load", FindType("ZPackage"));
			_contains = Method(InventoryType, "ContainsItem", type2);
			_removeAmount = Method(InventoryType, "RemoveItem", type2, typeof(int));
			_all = Method(InventoryType, "GetAllItems");
			_at = Method(InventoryType, "GetItemAt", typeof(int), typeof(int));
			DropItem = Method(type, "DropItem", type2, typeof(int), typeof(Vector3), typeof(Quaternion));
			Type type3 = FindType("ZNetScene");
			_sceneInstance = type3.GetProperty("instance", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			_destroy = type3.GetMethod("Destroy", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(GameObject) }, null);
			if (client)
			{
				GridType = FindType("InventoryGrid");
				GuiType = FindType("InventoryGui");
				GridInventory = Field(GridType, "m_inventory");
				_gridElements = GridType.GetField("m_elements", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				_elementAmount = (_gridElements?.FieldType.GetGenericArguments().FirstOrDefault())?.GetField("m_amount", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				_amountText = _elementAmount?.FieldType.GetProperty("text", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				Type type4 = FindType("Vector2i");
				_x = Field(type4, "x");
				_y = Field(type4, "y");
				GridDrop = Method(GridType, "DropItem", InventoryType, type2, typeof(int), type4);
				GridUpdate = GridType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo m) => m.Name == "UpdateGui");
				DragItem = GuiType.GetField("m_dragItem", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				OpenContainer = GuiType.GetField("m_currentContainer", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				CanDropDrag = GuiType.GetMethod("CanDropDragOntoItem", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { type2 }, null);
			}
		}

		internal void ShowChestAmounts(object grid, int configuredLimit)
		{
			if (!CanFormatAmounts || configuredLimit < 0 || !(_gridElements.GetValue(grid) is IEnumerable enumerable))
			{
				return;
			}
			foreach (object item in enumerable)
			{
				if (item == null)
				{
					continue;
				}
				object value = _elementAmount.GetValue(item);
				if (value != null)
				{
					string text = _amountText.GetValue(value, null) as string;
					int num = text?.IndexOf('/') ?? (-1);
					string text2 = ((num > 0) ? text.Substring(0, num).TrimEnd(Array.Empty<char>()) : text);
					if (!string.IsNullOrWhiteSpace(text2))
					{
						string value2 = ((configuredLimit == 0) ? text2 : (text2 + " / " + configuredLimit.ToString(CultureInfo.InvariantCulture)));
						_amountText.SetValue(value, value2, null);
					}
				}
			}
		}

		internal object ContainerInventory(object container)
		{
			if (container != null)
			{
				return _containerInventory.GetValue(container);
			}
			return null;
		}

		internal object CurrentChest(object gui)
		{
			return ContainerInventory(OpenContainer?.GetValue(gui));
		}

		internal bool SameType(object item, object other)
		{
			if (_sameType != null)
			{
				return (bool)_sameType.Invoke(item, new object[1] { other });
			}
			object value = _shared.GetValue(item);
			object value2 = _shared.GetValue(other);
			if (value != null && value2 != null && object.Equals(_itemName.GetValue(value), _itemName.GetValue(value2)) && object.Equals(_quality.GetValue(item), _quality.GetValue(other)) && object.Equals(_worldLevel?.GetValue(item), _worldLevel?.GetValue(other)))
			{
				return object.Equals(_variant?.GetValue(item), _variant?.GetValue(other));
			}
			return false;
		}

		internal bool IsChest(object instance)
		{
			Component val = (Component)((instance is Component) ? instance : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return false;
			}
			object? obj = _rootOverride?.GetValue(instance);
			Component val2 = (Component)((obj is Component) ? obj : null);
			if (Object.op_Implicit((Object)(object)val2))
			{
				return IsChestName(((Object)val2.gameObject).name);
			}
			if (IsChestName(((Object)val.gameObject).name))
			{
				return true;
			}
			object? obj2 = _view?.GetValue(instance);
			Component val3 = (Component)((obj2 is Component) ? obj2 : null);
			if (Object.op_Implicit((Object)(object)val3))
			{
				return IsChestName(((Object)val3.gameObject).name);
			}
			return false;
		}

		private static bool IsChestName(string name)
		{
			if (name.EndsWith("(Clone)", StringComparison.Ordinal))
			{
				name = name.Substring(0, name.Length - "(Clone)".Length).TrimEnd(Array.Empty<char>());
			}
			if (!name.Equals("piece_chest", StringComparison.OrdinalIgnoreCase) && !name.StartsWith("piece_chest_", StringComparison.OrdinalIgnoreCase))
			{
				return name.StartsWith("TreasureChest_", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		internal int Stack(object item)
		{
			return (int)_stack.GetValue(item);
		}

		internal void SetStack(object item, int amount)
		{
			_stack.SetValue(item, amount);
		}

		internal int NormalLimit(object item)
		{
			object value = _shared.GetValue(item);
			if (value != null)
			{
				return (int)MaximumField.GetValue(value);
			}
			return 1;
		}

		internal object Piece(object item, int amount)
		{
			object obj = _clone.Invoke(item, null);
			SetStack(obj, amount);
			return obj;
		}

		internal bool Contains(object inventory, object item)
		{
			return (bool)_contains.Invoke(inventory, new object[1] { item });
		}

		internal bool Add(object inventory, object item)
		{
			return (bool)AddItem.Invoke(inventory, new object[1] { item });
		}

		internal object[] Items(object inventory)
		{
			return ((IEnumerable)_all.Invoke(inventory, null)).Cast<object>().ToArray();
		}

		internal void Remove(object inventory, object item, int amount)
		{
			_removeAmount.Invoke(inventory, new object[2] { item, amount });
		}

		internal void Move(object to, object from, object item)
		{
			MoveItem.Invoke(to, new object[2] { from, item });
		}

		internal void MoveSlot(object to, object from, object item, int count, int x, int y)
		{
			MoveAt.Invoke(to, new object[5] { from, item, count, x, y });
		}

		internal object Slot(object inventory, int x, int y)
		{
			return _at.Invoke(inventory, new object[2] { x, y });
		}

		internal int X(object position)
		{
			return (int)_x.GetValue(position);
		}

		internal int Y(object position)
		{
			return (int)_y.GetValue(position);
		}

		internal object Spawn(object item, int amount, Vector3 position, Quaternion rotation)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			return DropItem.Invoke(null, new object[4] { item, amount, position, rotation });
		}

		internal void UndoDrop(object drop)
		{
			Component val = (Component)((drop is Component) ? drop : null);
			if (val != null && Object.op_Implicit((Object)(object)val))
			{
				object obj = _sceneInstance?.GetValue(null, null);
				if (obj != null && _destroy != null)
				{
					_destroy.Invoke(obj, new object[1] { val.gameObject });
				}
				else
				{
					Object.Destroy((Object)(object)val.gameObject);
				}
			}
		}

		private static Type FindType(string name)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				Type type = assemblies[i].GetType(name, throwOnError: false);
				if (type != null)
				{
					return type;
				}
			}
			throw new TypeLoadException(name);
		}

		private static FieldInfo Field(Type type, string name)
		{
			return type.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new MissingFieldException(type.Name, name);
		}

		private static MethodInfo Method(Type type, string name, params Type[] arguments)
		{
			return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, arguments, null) ?? throw new MissingMethodException(type.Name, name);
		}
	}
	internal interface IStackNetwork
	{
		object Token { get; }

		bool IsServer { get; }

		long ServerPeerId { get; }

		void Register(string method, Action<long, int> handler);

		void Send(long destination, string method, int value);
	}
	internal sealed class ServerStackSync
	{
		internal const string Request = "BenjSammy_ChestStacks_Request_v2";

		internal const string Settings = "BenjSammy_ChestStacks_Settings_v2";

		private readonly IStackNetwork _network;

		private readonly Func<int> _local;

		private readonly HashSet<long> _subscribers = new HashSet<long>();

		private object _token;

		private int? _remote;

		private int _lastLocal;

		private double _nextRequest;

		internal bool Locked
		{
			get
			{
				if (_network.Token != null)
				{
					return !_network.IsServer;
				}
				return false;
			}
		}

		internal int EffectiveLimit
		{
			get
			{
				if (Locked)
				{
					if (_token != _network.Token)
					{
						return -1;
					}
					return _remote ?? (-1);
				}
				return Math.Max(0, _local());
			}
		}

		internal ServerStackSync(IStackNetwork network, Func<int> local)
		{
			_network = network;
			_local = local;
		}

		internal void Tick(double now)
		{
			object token = _network.Token;
			if (token != _token)
			{
				_token = token;
				_remote = null;
				_subscribers.Clear();
				_nextRequest = 0.0;
				_lastLocal = Math.Max(0, _local());
				if (token != null)
				{
					_network.Register("BenjSammy_ChestStacks_Request_v2", OnRequest);
					_network.Register("BenjSammy_ChestStacks_Settings_v2", OnSettings);
				}
			}
			if (token == null)
			{
				return;
			}
			if (_network.IsServer)
			{
				int num = Math.Max(0, _local());
				if (num == _lastLocal)
				{
					return;
				}
				_lastLocal = num;
				{
					foreach (long subscriber in _subscribers)
					{
						_network.Send(subscriber, "BenjSammy_ChestStacks_Settings_v2", num);
					}
					return;
				}
			}
			if (!_remote.HasValue && now >= _nextRequest)
			{
				_nextRequest = now + 2.0;
				long serverPeerId = _network.ServerPeerId;
				if (serverPeerId != 0L)
				{
					_network.Send(serverPeerId, "BenjSammy_ChestStacks_Request_v2", 0);
				}
			}
		}

		private void OnRequest(long sender, int ignored)
		{
			if (_network.IsServer && sender != 0L)
			{
				_subscribers.Add(sender);
				_network.Send(sender, "BenjSammy_ChestStacks_Settings_v2", Math.Max(0, _local()));
			}
		}

		private void OnSettings(long sender, int value)
		{
			if (Locked && sender != 0L && sender == _network.ServerPeerId && value >= 0)
			{
				_remote = value;
			}
		}
	}
	internal sealed class StackNetwork : IStackNetwork
	{
		private const BindingFlags All = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private readonly MemberInfo _netInstance;

		private readonly MemberInfo _rpcInstance;

		private readonly MethodInfo _isServer;

		private readonly MethodInfo _serverPeerId;

		private readonly MethodInfo _getServerPeer;

		private readonly MethodInfo _register;

		private readonly MethodInfo _send;

		private readonly FieldInfo _peerId;

		private object Net => Read(_netInstance, null);

		private object Router => Read(_rpcInstance, null);

		public object Token
		{
			get
			{
				if (Net != null)
				{
					return Router;
				}
				return null;
			}
		}

		public bool IsServer
		{
			get
			{
				if (Net != null)
				{
					return (bool)_isServer.Invoke(Net, null);
				}
				return false;
			}
		}

		public long ServerPeerId
		{
			get
			{
				if (Token == null)
				{
					return 0L;
				}
				object obj = _getServerPeer.Invoke(Net, null);
				if (obj != null)
				{
					return (long)_peerId.GetValue(obj);
				}
				return (long)_serverPeerId.Invoke(Router, null);
			}
		}

		internal StackNetwork()
		{
			Type type = RequireType("ZNet");
			Type type2 = RequireType("ZRoutedRpc");
			_netInstance = RequireMember(type, "instance");
			_rpcInstance = RequireMember(type2, "instance");
			_isServer = RequireMethod(type, "IsServer", Type.EmptyTypes, typeof(bool));
			_getServerPeer = RequireMethod(type, "GetServerPeer", Type.EmptyTypes);
			_peerId = RequireField(RequireType("ZNetPeer"), "m_uid", typeof(long));
			_serverPeerId = RequireMethod(type2, "GetServerPeerID", Type.EmptyTypes, typeof(long));
			_send = RequireMethod(type2, "InvokeRoutedRPC", new Type[3]
			{
				typeof(long),
				typeof(string),
				typeof(object[])
			});
			_register = (from m in type2.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
				where m.Name == "Register" && m.IsGenericMethodDefinition && m.GetGenericArguments().Length == 1
				select m.MakeGenericMethod(typeof(int))).FirstOrDefault(delegate(MethodInfo m)
			{
				ParameterInfo[] parameters = m.GetParameters();
				return parameters.Length == 2 && parameters[0].ParameterType == typeof(string) && parameters[1].ParameterType == typeof(Action<long, int>);
			}) ?? throw new MissingMethodException("ZRoutedRpc.Register<int>");
		}

		public void Register(string method, Action<long, int> handler)
		{
			_register.Invoke(Router, new object[2] { method, handler });
		}

		public void Send(long destination, string method, int value)
		{
			_send.Invoke(Router, new object[3]
			{
				destination,
				method,
				new object[1] { value }
			});
		}

		private static Type RequireType(string name)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				Type type = assemblies[i].GetType(name, throwOnError: false);
				if (type != null)
				{
					return type;
				}
			}
			throw new TypeLoadException("Valheim type was not found: " + name);
		}

		private static MemberInfo RequireMember(Type type, string name)
		{
			object obj = ((object)type.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) ?? ((object)type.GetProperty(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
			if (obj == null)
			{
				throw new MissingMemberException(type.FullName, name);
			}
			return (MemberInfo)obj;
		}

		private static FieldInfo RequireField(Type type, string name, Type expected)
		{
			FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (field == null || field.FieldType != expected)
			{
				throw new MissingFieldException(type.FullName, name);
			}
			return field;
		}

		private static MethodInfo RequireMethod(Type type, string name, Type[] parameters, Type expected = null)
		{
			MethodInfo method = type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameters, null);
			if (method == null || (expected != null && method.ReturnType != expected))
			{
				throw new MissingMethodException(type.FullName, name);
			}
			return method;
		}

		private static object Read(MemberInfo member, object instance)
		{
			FieldInfo fieldInfo = member as FieldInfo;
			if (!(fieldInfo != null))
			{
				return ((PropertyInfo)member).GetValue(instance, null);
			}
			return fieldInfo.GetValue(instance);
		}
	}
}