Decompiled source of Inventory and QoL v1.0.39

DigiQoL.dll

Decompiled 5 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using AchievementKeeper;
using AutoCloseDoors;
using BackpackAtStations;
using BackpackQuickOpen;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using CameraClipFix;
using ChestFillOrder;
using ChestSorter;
using ChestWindowFit;
using CompactStatusEffects;
using DigiCore;
using DigiStorage;
using EffectDetails;
using HarmonyLib;
using HudGrid;
using ItemPickupFix;
using KeepRested;
using LighterInventory;
using Microsoft.CodeAnalysis;
using SafeItemMove;
using SellToHaldor;
using SkillXp;
using StoreInBackpacks;
using StoreNearby;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[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: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: AssemblyCompany("DigiQoL")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+bb5c579629a6483bea15cf829c8b42672cab1008")]
[assembly: AssemblyProduct("DigiQoL")]
[assembly: AssemblyTitle("DigiQoL")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.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;
		}
	}
}
internal static class SettingOrder
{
	internal sealed class ConfigurationManagerAttributes
	{
		public int? Order;
	}

	internal static void Apply(ConfigFile config)
	{
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Expected O, but got Unknown
		FieldInfo fieldInfo = AccessTools.Field(typeof(ConfigEntryBase), "<Description>k__BackingField");
		if (fieldInfo == null)
		{
			return;
		}
		int num = 1000;
		foreach (ConfigDefinition item in config.Keys.ToList())
		{
			ConfigEntryBase val = config[item];
			ConfigDescription description = val.Description;
			object[] array = ((description != null) ? description.Tags : null) ?? new object[0];
			object obj = array.FirstOrDefault((object t) => t != null && t.GetType().Name == "ConfigurationManagerAttributes");
			if (obj != null)
			{
				FieldInfo fieldInfo2 = AccessTools.Field(obj.GetType(), "Order");
				if (fieldInfo2 != null && fieldInfo2.GetValue(obj) == null)
				{
					fieldInfo2.SetValue(obj, num);
				}
			}
			else
			{
				fieldInfo.SetValue(val, (object?)new ConfigDescription(((description != null) ? description.Description : null) ?? "", (description != null) ? description.AcceptableValues : null, array.Concat(new object[1]
				{
					new ConfigurationManagerAttributes
					{
						Order = num
					}
				}).ToArray()));
			}
			num--;
		}
	}
}
internal static class StoreRules
{
	private sealed class Box
	{
		public Vector3 At;

		public Bounds Bounds;
	}

	private sealed class InputSet
	{
		public int Count;

		public HashSet<string> Names;
	}

	private static ConfigEntry<bool> _leaveOne;

	private static ConfigEntry<bool> _onlyMatching;

	private static int _holdSaves;

	private static readonly HashSet<Container> HeldSaves = new HashSet<Container>();

	private static MethodInfo _save;

	private static bool _savePatched;

	private static readonly Dictionary<GameObject, string> Names = new Dictionary<GameObject, string>();

	private static readonly Dictionary<Container, bool> Mobile = new Dictionary<Container, bool>();

	private static int _mobilePruneAt = 512;

	private static readonly Dictionary<Component, Box> Boxes = new Dictionary<Component, Box>();

	private static int _boxPruneAt = 512;

	private static readonly Dictionary<IList, InputSet> InputSets = new Dictionary<IList, InputSet>();

	internal static bool LeaveOne
	{
		get
		{
			if (_leaveOne != null)
			{
				return _leaveOne.Value;
			}
			return false;
		}
	}

	internal static bool OnlyMatching
	{
		get
		{
			if (_onlyMatching != null)
			{
				return _onlyMatching.Value;
			}
			return false;
		}
	}

	internal static bool CanDeposit(Inventory inv)
	{
		return true;
	}

	internal static bool CanWithdraw(Inventory inv)
	{
		return true;
	}

	internal static bool CanWithdraw(Container chest)
	{
		return !ChestFlags.TakeBlocked(chest);
	}

	internal static bool IsProtected(Inventory inv, ItemData item)
	{
		return false;
	}

	internal static bool IsProtectedSlot(Inventory inv, int x, int y)
	{
		return false;
	}

	internal static Func<int, int, bool> ProtectedSlots(Inventory inv)
	{
		return null;
	}

	internal static void BindRules(ModuleConfig config)
	{
		ConfigFile file = config.File;
		string text = (config.Standalone ? "Chest rules" : "Craft From Chests - Chest rules");
		_leaveOne = file.Bind<bool>(text, "Leave 1 in each chest", false, "Crafting, building, filling by hand and the automated stations never take the last one of an item from a chest: a chest kept for one item (wood, iron, a mead) keeps one, so it stays that item's chest. Off: all of it can be used.");
		_onlyMatching = file.Bind<bool>(text, "Only store into chests that already have it", false, "The automated stations put what they make only into a chest that already holds that item. Off: when no chest has it, it goes into the nearest chest with room. With no chest for it, fermenters, ovens, cooking stations, beehives and sap extractors keep it (food only drops just before it burns); smelters, kilns and the like drop it as in the game.");
	}

	internal static bool KeepsLast(Inventory inv, ItemData item)
	{
		if (LeaveOne && item?.m_shared != null)
		{
			return inv.CountItems(item.m_shared.m_name, -1, false) <= 1;
		}
		return false;
	}

	internal static Container PickOutputChest(List<Container> nearestFirst, GameObject prefab, int amount)
	{
		string shared = prefab.GetComponent<ItemDrop>()?.m_itemData.m_shared.m_name;
		List<Container> source = nearestFirst.Where((Container c) => c.GetInventory().CanAddItem(prefab, amount)).ToList();
		object obj = ((IEnumerable<Container>)source).FirstOrDefault((Func<Container, bool>)((Container c) => c.GetInventory().GetAllItems().Any((ItemData i) => i?.m_shared != null && i.m_shared.m_name == shared)));
		if (obj == null)
		{
			if (!OnlyMatching)
			{
				return source.FirstOrDefault();
			}
			obj = null;
		}
		return (Container)obj;
	}

	internal static void HoldSaves()
	{
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Expected O, but got Unknown
		if (!_savePatched)
		{
			_savePatched = true;
			_save = AccessTools.Method(typeof(Container), "Save", (Type[])null, (Type[])null);
			if (_save != null)
			{
				new Harmony("digi.storerules.saves." + typeof(StoreRules).Assembly.GetName().Name).Patch((MethodBase)_save, new HarmonyMethod(typeof(StoreRules), "SaveLater", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}
		_holdSaves++;
	}

	internal static void SaveHeld()
	{
		if (--_holdSaves > 0)
		{
			return;
		}
		_holdSaves = 0;
		if (HeldSaves.Count == 0)
		{
			return;
		}
		List<Container> list = HeldSaves.ToList();
		HeldSaves.Clear();
		foreach (Container item in list)
		{
			if (!((Object)(object)item == (Object)null) && !(_save == null))
			{
				try
				{
					_save.Invoke(item, null);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)("[Digi] chest save failed: " + (ex.InnerException ?? ex).Message));
				}
			}
		}
	}

	private static bool SaveLater(Container __instance)
	{
		if (_holdSaves <= 0 || (Object)(object)__instance == (Object)null)
		{
			return true;
		}
		HeldSaves.Add(__instance);
		return false;
	}

	internal static string NameOf(GameObject prefab)
	{
		if ((Object)(object)prefab == (Object)null)
		{
			return null;
		}
		if (!Names.TryGetValue(prefab, out var value))
		{
			if (Names.Count > 20000)
			{
				Names.Clear();
			}
			value = (Names[prefab] = ((Object)prefab).name);
		}
		return value;
	}

	internal static string NameOf(Component prefab)
	{
		if (!((Object)(object)prefab == (Object)null))
		{
			return NameOf(prefab.gameObject);
		}
		return null;
	}

	internal static bool CartShipOrGrave(Container chest)
	{
		if (Mobile.TryGetValue(chest, out var value))
		{
			return value;
		}
		if (Mobile.Count >= _mobilePruneAt)
		{
			foreach (Container item in Mobile.Keys.Where((Container c) => (Object)(object)c == (Object)null).ToList())
			{
				Mobile.Remove(item);
			}
			_mobilePruneAt = Math.Max(512, Mobile.Count * 2);
		}
		value = (Object)(object)chest.m_wagon != (Object)null || (Object)(object)((Component)chest).GetComponentInParent<Ship>() != (Object)null || (Object)(object)((Component)chest).GetComponent<TombStone>() != (Object)null;
		Mobile[chest] = value;
		return value;
	}

	internal static Bounds SolidBounds(Component owner, Func<Component, Bounds> measure)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: 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_00ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		Vector3 position = owner.transform.position;
		if (Boxes.TryGetValue(owner, out var value) && value.At == position)
		{
			return value.Bounds;
		}
		if (value == null && Boxes.Count >= _boxPruneAt)
		{
			foreach (Component item in Boxes.Keys.Where((Component c) => (Object)(object)c == (Object)null).ToList())
			{
				Boxes.Remove(item);
			}
			_boxPruneAt = Math.Max(512, Boxes.Count * 2);
		}
		Bounds val = measure(owner);
		Boxes[owner] = new Box
		{
			At = position,
			Bounds = val
		};
		return val;
	}

	internal static HashSet<string> InputNames<T>(List<T> conversions, Func<T, Component> from)
	{
		if (conversions == null)
		{
			return new HashSet<string>();
		}
		if (!InputSets.TryGetValue(conversions, out var value) || value.Count != conversions.Count)
		{
			if (InputSets.Count > 2000)
			{
				InputSets.Clear();
			}
			HashSet<string> hashSet = new HashSet<string>();
			foreach (T conversion in conversions)
			{
				Component val = ((conversion != null) ? from(conversion) : null);
				if ((Object)(object)val != (Object)null)
				{
					hashSet.Add(NameOf(val));
				}
			}
			value = (InputSets[conversions] = new InputSet
			{
				Count = conversions.Count,
				Names = hashSet
			});
		}
		return value.Names;
	}

	internal static bool TakeOne(List<Container> nearestFirst, Func<ItemData, bool> match, out ItemData taken)
	{
		foreach (Container item in nearestFirst)
		{
			if (CanWithdraw(item))
			{
				Inventory inv = item.GetInventory();
				ItemData val = ((IEnumerable<ItemData>)inv.GetAllItems()).FirstOrDefault((Func<ItemData, bool>)((ItemData i) => match(i) && !KeepsLast(inv, i)));
				if (val != null)
				{
					taken = val.Clone();
					inv.RemoveOneItem(val);
					return true;
				}
			}
		}
		taken = null;
		return false;
	}
}
namespace DigiStorage
{
	public sealed class ChestCheckbox
	{
		public const string StoreName = "DigiStoreNearbyCheckbox";

		public const string TakeName = "DigiTakeFromCheckbox";

		private const string TitleHidden = "DigiChestTitleHidden";

		private static readonly string[] Order = new string[2] { "DigiTakeFromCheckbox", "DigiStoreNearbyCheckbox" };

		private const float LabelGap = 7f;

		private const float Between = 26f;

		private const float Margin = 12f;

		private const float LabelSize = 18f;

		private static readonly Color Off = new Color(0.55f, 0.53f, 0.5f, 1f);

		private readonly string _name;

		private readonly string _flag;

		private readonly string _label;

		private readonly string _title;

		private readonly string _tooltip;

		private RectTransform _box;

		private Toggle _toggle;

		private TMP_Text _text;

		private RectTransform _labelRect;

		private Color _on = new Color(1f, 0.63f, 0.24f, 1f);

		private bool _updating;

		private Container _shownFor;

		private static Sprite _tick;

		public float Size = 26f;

		public bool Visible
		{
			get
			{
				if ((Object)(object)_box != (Object)null)
				{
					return ((Component)_box).gameObject.activeSelf;
				}
				return false;
			}
		}

		public ChestCheckbox(string name, string flag, string label, string title, string tooltip)
		{
			//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)
			_name = name;
			_flag = flag;
			_label = label;
			_title = title;
			_tooltip = tooltip;
		}

		public void Destroy()
		{
			if ((Object)(object)_box != (Object)null)
			{
				((Component)_box).gameObject.SetActive(false);
				Object.Destroy((Object)(object)((Component)_box).gameObject);
			}
			_box = null;
			_toggle = null;
			_text = null;
			_labelRect = null;
			_shownFor = null;
			if ((Object)(object)InventoryGui.instance != (Object)null)
			{
				SyncTitle(InventoryGui.instance);
			}
		}

		public void Refresh(InventoryGui gui, bool show)
		{
			Container val = (_shownFor = gui.m_currentContainer);
			if (!show || (Object)(object)val == (Object)null || !IsBuiltChest(val))
			{
				if ((Object)(object)_box != (Object)null)
				{
					((Component)_box).gameObject.SetActive(false);
				}
				if ((Object)(object)val != (Object)null || !show)
				{
					SyncTitle(gui);
				}
				return;
			}
			if ((Object)(object)_box == (Object)null)
			{
				Create(gui);
			}
			if (!((Object)(object)_box == (Object)null))
			{
				((Component)_box).gameObject.SetActive(true);
				Layout(gui);
				_updating = true;
				_toggle.isOn = !Blocked(val);
				_updating = false;
				Tint();
				SyncTitle(gui);
			}
		}

		public static bool Closing(InventoryGui gui)
		{
			if (gui.m_hiddenFrames <= 0)
			{
				return gui.m_shownFrames == 0;
			}
			return true;
		}

		public void Update(InventoryGui gui, bool show)
		{
			if (Closing(gui))
			{
				return;
			}
			if ((Object)(object)gui.m_currentContainer != (Object)(object)_shownFor)
			{
				Refresh(gui, show);
				return;
			}
			if (Visible)
			{
				Layout(gui);
			}
			if ((Object)(object)gui.m_currentContainer != (Object)null)
			{
				SyncTitle(gui);
			}
		}

		public static bool IsBuiltChest(Container chest)
		{
			if ((Object)(object)((Component)chest).GetComponent<Piece>() != (Object)null && (Object)(object)chest.m_wagon == (Object)null && (Object)(object)((Component)chest).GetComponentInParent<Ship>() == (Object)null)
			{
				return (Object)(object)((Component)chest).GetComponent<TombStone>() == (Object)null;
			}
			return false;
		}

		private bool Blocked(Container chest)
		{
			ZNetView nview = chest.m_nview;
			if ((Object)(object)nview != (Object)null && nview.IsValid())
			{
				return nview.GetZDO().GetBool(_flag, false);
			}
			return false;
		}

		private void Changed(bool allowed)
		{
			Tint();
			if (_updating || (Object)(object)InventoryGui.instance == (Object)null)
			{
				return;
			}
			Container currentContainer = InventoryGui.instance.m_currentContainer;
			ZNetView val = (((Object)(object)currentContainer != (Object)null) ? currentContainer.m_nview : null);
			if (!((Object)(object)val == (Object)null) && val.IsValid())
			{
				if (!val.IsOwner())
				{
					val.ClaimOwnership();
				}
				val.GetZDO().Set(_flag, !allowed);
			}
		}

		private void Tint()
		{
			//IL_0037: 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)
			if ((Object)(object)_text != (Object)null && (Object)(object)_toggle != (Object)null)
			{
				((Graphic)_text).color = (_toggle.isOn ? _on : Off);
			}
		}

		private void Create(InventoryGui gui)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: 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_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: 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_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Expected O, but got Unknown
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Expected O, but got Unknown
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_0338: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0370: Unknown result type (might be due to invalid IL or missing references)
			//IL_042b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0431: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)gui.m_stackAllButton == (Object)null))
			{
				Transform parent = ((Component)gui.m_stackAllButton).transform.parent;
				Transform val = parent.Find(_name);
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)val).gameObject);
				}
				GameObject val2 = new GameObject(_name, new Type[1] { typeof(RectTransform) });
				val2.transform.SetParent(parent, false);
				_box = (RectTransform)val2.transform;
				((Graphic)val2.AddComponent<Image>()).color = new Color(0f, 0f, 0f, 0f);
				GameObject val3 = new GameObject("Background", new Type[1] { typeof(RectTransform) });
				val3.transform.SetParent((Transform)(object)_box, false);
				RectTransform val4 = (RectTransform)val3.transform;
				Vector2 val5 = default(Vector2);
				((Vector2)(ref val5))..ctor(0f, 0.5f);
				val4.anchorMax = val5;
				val4.anchorMin = val5;
				val4.pivot = new Vector2(0f, 0.5f);
				val4.anchoredPosition = Vector2.zero;
				val4.sizeDelta = new Vector2(Size, Size);
				Image val6 = val3.AddComponent<Image>();
				Sprite val7 = SlotSprite(gui);
				if ((Object)(object)val7 != (Object)null)
				{
					val6.sprite = val7;
					val6.type = (Type)1;
				}
				((Graphic)val6).color = new Color(0f, 0f, 0f, 0.5f);
				GameObject val8 = new GameObject("Checkmark", new Type[1] { typeof(RectTransform) });
				val8.transform.SetParent((Transform)(object)val4, false);
				RectTransform val9 = (RectTransform)val8.transform;
				val9.anchorMin = Vector2.zero;
				val9.anchorMax = Vector2.one;
				val9.offsetMin = new Vector2(-4f, -4f);
				val9.offsetMax = new Vector2(4f, 4f);
				Image val10 = val8.AddComponent<Image>();
				val10.sprite = TickSprite();
				TMP_Text componentInChildren = ((Component)gui.m_stackAllButton).GetComponentInChildren<TMP_Text>(true);
				if ((Object)(object)componentInChildren != (Object)null)
				{
					_on = ((Graphic)componentInChildren).color;
				}
				((Graphic)val10).color = _on;
				((Graphic)val10).raycastTarget = false;
				GameObject val11 = new GameObject("Label", new Type[1] { typeof(RectTransform) });
				val11.transform.SetParent((Transform)(object)_box, false);
				_labelRect = (RectTransform)val11.transform;
				_text = (TMP_Text)(object)val11.AddComponent<TextMeshProUGUI>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					_text.font = componentInChildren.font;
					_text.fontSharedMaterial = componentInChildren.fontSharedMaterial;
				}
				_text.fontSize = 18f;
				_text.enableAutoSizing = false;
				_text.enableWordWrapping = false;
				_text.alignment = (TextAlignmentOptions)4097;
				((Graphic)_text).raycastTarget = false;
				_text.text = _label;
				RectTransform labelRect = _labelRect;
				RectTransform labelRect2 = _labelRect;
				((Vector2)(ref val5))..ctor(0f, 0.5f);
				labelRect2.anchorMax = val5;
				labelRect.anchorMin = val5;
				_labelRect.pivot = new Vector2(0f, 0.5f);
				_labelRect.anchoredPosition = new Vector2(Size + 7f, 0f);
				FitLabel((float)_label.Length * 18f * 0.55f);
				_toggle = val2.AddComponent<Toggle>();
				((Selectable)_toggle).targetGraphic = (Graphic)(object)val6;
				_toggle.graphic = (Graphic)(object)val10;
				_toggle.isOn = true;
				((UnityEvent<bool>)(object)_toggle.onValueChanged).AddListener((UnityAction<bool>)Changed);
				UITooltip obj = val2.AddComponent<UITooltip>();
				InventoryGrid playerGrid = gui.m_playerGrid;
				object tooltipPrefab;
				if (playerGrid == null)
				{
					tooltipPrefab = null;
				}
				else
				{
					GameObject elementPrefab = playerGrid.m_elementPrefab;
					tooltipPrefab = ((elementPrefab == null) ? null : elementPrefab.GetComponent<UITooltip>()?.m_tooltipPrefab);
				}
				obj.m_tooltipPrefab = (GameObject)tooltipPrefab;
				string title = _title;
				string tooltip = _tooltip;
				val5 = default(Vector2);
				obj.Set(title, tooltip, (RectTransform)null, val5);
			}
		}

		public void Layout(InventoryGui gui)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_box == (Object)null || (Object)(object)gui.m_stackAllButton == (Object)null)
			{
				return;
			}
			if ((Object)(object)_text != (Object)null)
			{
				float preferredWidth = _text.preferredWidth;
				if (preferredWidth > 18f)
				{
					FitLabel(preferredWidth);
				}
			}
			RectTransform val = (RectTransform)((Transform)_box).parent;
			float num = 0f;
			float num2 = 0f;
			int num3 = 0;
			string[] order = Order;
			foreach (string text in order)
			{
				Transform obj = ((Transform)val).Find(text);
				RectTransform val2 = (RectTransform)(object)((obj is RectTransform) ? obj : null);
				if (!((Object)(object)val2 == (Object)null) && ((Component)val2).gameObject.activeSelf)
				{
					if (num3++ > 0)
					{
						num += 26f;
					}
					if ((Object)(object)val2 == (Object)(object)_box)
					{
						num2 = num;
					}
					num += val2.sizeDelta.x;
				}
			}
			Vector3 val3 = Edge((RectTransform)((Component)gui.m_stackAllButton).transform, val, rightEdge: false);
			RectTransform val4 = ((!((Object)(object)gui.m_takeAllButton != (Object)null) || !((Component)gui.m_takeAllButton).gameObject.activeInHierarchy) ? ((RectTransform)null) : ((RectTransform)((Component)gui.m_takeAllButton).transform));
			float num4 = (((Object)(object)val4 != (Object)null) ? Edge(val4, val, rightEdge: true).x : (val3.x - num - 24f));
			float num5 = val3.x - num4 - 24f;
			float num6 = ((num > num5 && num5 > 0f) ? (num5 / num) : 1f);
			float num7 = (num4 + val3.x) * 0.5f - num * num6 * 0.5f + (num2 + _box.sizeDelta.x * 0.5f) * num6;
			RectTransform box = _box;
			RectTransform box2 = _box;
			RectTransform box3 = _box;
			Vector2 val5 = default(Vector2);
			((Vector2)(ref val5))..ctor(0.5f, 0.5f);
			box3.pivot = val5;
			Vector2 anchorMin = (box2.anchorMax = val5);
			box.anchorMin = anchorMin;
			if (Mathf.Abs(((Transform)_box).localScale.x - num6) > 0.001f)
			{
				((Transform)_box).localScale = new Vector3(num6, num6, 1f);
			}
			Vector3 val7 = default(Vector3);
			((Vector3)(ref val7))..ctor(num7, val3.y, 0f);
			Vector3 val8 = ((Transform)_box).localPosition - val7;
			if (((Vector3)(ref val8)).sqrMagnitude > 0.01f)
			{
				((Transform)_box).localPosition = val7;
			}
		}

		private void FitLabel(float textWidth)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Ceil(textWidth) + 2f;
			if (!(Mathf.Abs(_labelRect.sizeDelta.x - num) < 0.5f))
			{
				_labelRect.sizeDelta = new Vector2(num, Size);
				_box.sizeDelta = new Vector2(Size + 7f + num, Size);
			}
		}

		private static Vector3 Edge(RectTransform rect, RectTransform parent, bool rightEdge)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			rect.GetWorldCorners(array);
			return ((Transform)parent).InverseTransformPoint(rightEdge ? ((array[2] + array[3]) * 0.5f) : ((array[0] + array[1]) * 0.5f));
		}

		private static void SyncTitle(InventoryGui gui)
		{
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			TMP_Text containerName = gui.m_containerName;
			if ((Object)(object)containerName == (Object)null || (Object)(object)gui.m_stackAllButton == (Object)null)
			{
				return;
			}
			Transform parent = ((Component)gui.m_stackAllButton).transform.parent;
			bool flag = false;
			string[] order = Order;
			foreach (string text in order)
			{
				Transform val = parent.Find(text);
				if ((Object)(object)val != (Object)null && ((Component)val).gameObject.activeSelf)
				{
					flag = true;
				}
			}
			Transform val2 = containerName.transform.Find("DigiChestTitleHidden");
			if (flag && (Object)(object)val2 == (Object)null && ((Behaviour)containerName).enabled)
			{
				((Behaviour)containerName).enabled = false;
				new GameObject("DigiChestTitleHidden").transform.SetParent(containerName.transform, false);
			}
			else if (!flag && (Object)(object)val2 != (Object)null)
			{
				val2.SetParent((Transform)null);
				Object.Destroy((Object)(object)((Component)val2).gameObject);
				((Behaviour)containerName).enabled = true;
			}
		}

		private static Sprite SlotSprite(InventoryGui gui)
		{
			GameObject val = gui.m_playerGrid?.m_elementPrefab;
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			Image[] componentsInChildren = val.GetComponentsInChildren<Image>(true);
			foreach (Image val2 in componentsInChildren)
			{
				if ((Object)(object)val2.sprite != (Object)null && ((Object)val2.sprite).name == "item_background")
				{
					return val2.sprite;
				}
			}
			return null;
		}

		private static Sprite TickSprite()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: 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_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_tick != (Object)null)
			{
				return _tick;
			}
			Texture2D val = new Texture2D(32, 32, (TextureFormat)4, false)
			{
				name = "DigiChestTick",
				filterMode = (FilterMode)1
			};
			Vector2 a = default(Vector2);
			((Vector2)(ref a))..ctor(6f, 16f);
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(13f, 8.5f);
			Vector2 b = default(Vector2);
			((Vector2)(ref b))..ctor(26.5f, 25f);
			Color32[] array = (Color32[])(object)new Color32[1024];
			Vector2 p = default(Vector2);
			for (int i = 0; i < 32; i++)
			{
				for (int j = 0; j < 32; j++)
				{
					((Vector2)(ref p))..ctor((float)j + 0.5f, (float)i + 0.5f);
					float num = Mathf.Min(SegmentDistance(p, a, val2), SegmentDistance(p, val2, b));
					float num2 = Mathf.Clamp01(2.6f - num);
					array[i * 32 + j] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, (byte)(num2 * 255f));
				}
			}
			val.SetPixels32(array);
			val.Apply();
			_tick = Sprite.Create(val, new Rect(0f, 0f, 32f, 32f), new Vector2(0.5f, 0.5f));
			return _tick;
		}

		private static float SegmentDistance(Vector2 p, Vector2 a, Vector2 b)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//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)
			Vector2 val = b - a;
			float num = Mathf.Clamp01(Vector2.Dot(p - a, val) / ((Vector2)(ref val)).sqrMagnitude);
			return Vector2.Distance(p, a + val * num);
		}
	}
	public sealed class ChestRules
	{
		public float Range = 50f;

		public bool Personal;

		public bool CartsShips;

		public string BlockFlag;
	}
	public static class Chests
	{
		private sealed class Facts
		{
			public ZNetView View;

			public Piece Piece;

			public bool Cart;

			public bool Ship;

			public bool Built;
		}

		public sealed class Area
		{
			public readonly ChestRules Rules;

			internal readonly List<Container> List = new List<Container>();

			internal Vector3 Origin;

			internal float Time = -100f;

			internal int Version = -1;

			internal float Range = -1f;

			internal bool Personal;

			internal bool CartsShips;

			internal readonly Dictionary<Container, uint> Read = new Dictionary<Container, uint>();

			internal readonly Dictionary<string, List<Stack>> Sums = new Dictionary<string, List<Stack>>();

			internal int SumsFrame = -1;

			internal bool Dirty = true;

			internal readonly Dictionary<string, int> ReadyMemo = new Dictionary<string, int>();

			internal int ReadyFrame = -1;

			internal bool LeaveOne;

			public Area(ChestRules rules)
			{
				Rules = rules;
			}
		}

		internal sealed class Stack
		{
			public int Quality;

			public int WorldLevel;

			public int Amount;
		}

		private static readonly string[] Forbidden = new string[7] { "Player_tombstone", "piece_chest_treasure", "piece_gift1", "piece_gift2", "piece_gift3", "incinerator", "Trailership" };

		private static readonly List<Container> Loaded = new List<Container>();

		private static readonly Dictionary<Container, Facts> Known = new Dictionary<Container, Facts>();

		private static Harmony _harmony;

		private static int _users;

		private static int _version;

		private static readonly HashSet<string> Kept = new HashSet<string>();

		private static readonly Dictionary<Container, float> Pending = new Dictionary<Container, float>();

		private static readonly Dictionary<Container, float> Refused = new Dictionary<Container, float>();

		private const float AnswerTime = 2f;

		public static void Use()
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			if (_users++ <= 0)
			{
				_harmony = new Harmony("digi.storage." + typeof(Chests).Assembly.GetName().Name + "." + Guid.NewGuid().ToString("N"));
				_harmony.Patch((MethodBase)AccessTools.Method(typeof(Container), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Chests), "Awoke", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_harmony.Patch((MethodBase)AccessTools.Method(typeof(Container), "RPC_OpenResponse", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Chests), "OpenResponse", (Type[])null)
				{
					priority = 800
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Container[] array = Object.FindObjectsByType<Container>((FindObjectsSortMode)0);
				for (int i = 0; i < array.Length; i++)
				{
					Add(array[i]);
				}
			}
		}

		public static void Release()
		{
			if (_users > 0 && --_users <= 0)
			{
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
				_harmony = null;
				Loaded.Clear();
				Known.Clear();
				Pending.Clear();
				Refused.Clear();
				_version++;
			}
		}

		private static void Awoke(Container __instance)
		{
			Add(__instance);
		}

		private static void Add(Container chest)
		{
			if (!((Object)(object)chest == (Object)null) && !((Object)(object)chest.m_nview == (Object)null) && chest.m_nview.GetZDO() != null && !Known.ContainsKey(chest))
			{
				Piece componentInParent = ((Component)chest).GetComponentInParent<Piece>();
				string prefabName = Utils.GetPrefabName(((Object)(object)chest.m_rootObjectOverride != (Object)null) ? ((Component)chest.m_rootObjectOverride).gameObject : ((Component)chest).gameObject);
				bool built = (Object)(object)componentInParent != (Object)null && (Object)(object)((Component)chest).GetComponent<TombStone>() == (Object)null && Array.IndexOf(Forbidden, prefabName) < 0 && !prefabName.StartsWith("TreasureChest_", StringComparison.OrdinalIgnoreCase) && !prefabName.StartsWith("shipwreck_", StringComparison.OrdinalIgnoreCase);
				Known[chest] = new Facts
				{
					View = chest.m_nview,
					Piece = componentInParent,
					Built = built,
					Cart = ((Object)(object)chest.m_wagon != (Object)null),
					Ship = ((Object)(object)((Component)chest).GetComponentInParent<Ship>() != (Object)null)
				};
				Loaded.Add(chest);
				_version++;
			}
		}

		private static bool Allowed(Container chest, Facts facts, ChestRules rules, long playerId)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Invalid comparison between Unknown and I4
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			if (!facts.Built || (Object)(object)facts.View == (Object)null || !facts.View.IsValid())
			{
				return false;
			}
			ZDO zDO = facts.View.GetZDO();
			if (facts.Piece.GetCreator() == 0L)
			{
				return false;
			}
			if ((facts.Cart || facts.Ship) && !rules.CartsShips)
			{
				return false;
			}
			if ((int)chest.m_privacy == 0 && (!rules.Personal || !chest.CheckAccess(playerId)))
			{
				return false;
			}
			if ((int)chest.m_privacy == 1)
			{
				return false;
			}
			if (!string.IsNullOrEmpty(rules.BlockFlag) && zDO.GetBool(rules.BlockFlag, false))
			{
				return false;
			}
			if (chest.m_checkGuardStone && !PrivateArea.CheckAccess(((Component)chest).transform.position, 0f, false, false))
			{
				return false;
			}
			return true;
		}

		public static bool OpenByOthers(Container chest)
		{
			ZNetView val = (((Object)(object)chest != (Object)null) ? chest.m_nview : null);
			if ((Object)(object)val != (Object)null && val.IsValid() && !val.IsOwner())
			{
				return val.GetZDO().GetInt(ZDOVars.s_inUse, 0) == 1;
			}
			return false;
		}

		public static List<Container> Near(Area area, Vector3 origin)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			float unscaledTime = Time.unscaledTime;
			ChestRules rules = area.Rules;
			Vector3 val;
			if (area.Version == _version && unscaledTime - area.Time < 1f)
			{
				val = origin - area.Origin;
				if (((Vector3)(ref val)).sqrMagnitude < 1f && area.Range == rules.Range && area.Personal == rules.Personal && area.CartsShips == rules.CartsShips)
				{
					return area.List;
				}
			}
			area.Version = _version;
			area.Time = unscaledTime;
			area.Origin = origin;
			area.Range = rules.Range;
			area.Personal = rules.Personal;
			area.CartsShips = rules.CartsShips;
			area.List.Clear();
			long playerId = (((Object)(object)Game.instance != (Object)null) ? Game.instance.GetPlayerProfile().GetPlayerID() : 0);
			float num = rules.Range * rules.Range;
			for (int num2 = Loaded.Count - 1; num2 >= 0; num2--)
			{
				Container val2 = Loaded[num2];
				if ((Object)(object)val2 == (Object)null)
				{
					Loaded.RemoveAt(num2);
					_version++;
				}
				else
				{
					val = ((Component)val2).transform.position - origin;
					if (!(((Vector3)(ref val)).sqrMagnitude > num) && Known.TryGetValue(val2, out var value) && Allowed(val2, value, rules, playerId))
					{
						area.List.Add(val2);
					}
				}
			}
			if (Known.Count > Loaded.Count + 64)
			{
				List<Container> list = new List<Container>();
				foreach (Container key in Known.Keys)
				{
					if ((Object)(object)key == (Object)null)
					{
						list.Add(key);
					}
				}
				foreach (Container item in list)
				{
					Known.Remove(item);
				}
			}
			area.List.Sort(delegate(Container a, Container b)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val3 = ((Component)a).transform.position - origin;
				float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
				val3 = ((Component)b).transform.position - origin;
				return sqrMagnitude.CompareTo(((Vector3)(ref val3)).sqrMagnitude);
			});
			area.Dirty = true;
			area.Version = _version;
			return area.List;
		}

		public static void Fresh(Container chest)
		{
			if (!((Object)(object)chest == (Object)null) && !chest.m_inUse && !((Object)(object)chest.m_nview == (Object)null) && chest.m_nview.IsValid() && chest.m_nview.GetZDO().DataRevision != chest.m_lastRevision)
			{
				chest.Load();
			}
		}

		private static void UpdateSums(Area area)
		{
			if (area.SumsFrame == Time.frameCount)
			{
				return;
			}
			area.SumsFrame = Time.frameCount;
			bool flag = area.Dirty || area.LeaveOne != StoreRules.LeaveOne;
			area.LeaveOne = StoreRules.LeaveOne;
			foreach (Container item in area.List)
			{
				if (!((Object)(object)item == (Object)null) && !((Object)(object)item.m_nview == (Object)null) && item.m_nview.IsValid())
				{
					uint dataRevision = item.m_nview.GetZDO().DataRevision;
					if (!area.Read.TryGetValue(item, out var value) || value != dataRevision)
					{
						Fresh(item);
						area.Read[item] = item.m_nview.GetZDO().DataRevision;
						flag = true;
					}
				}
			}
			if (!flag)
			{
				return;
			}
			area.Dirty = false;
			if (area.Read.Count > area.List.Count)
			{
				HashSet<Container> hashSet = new HashSet<Container>(area.List);
				List<Container> list = new List<Container>();
				foreach (Container key in area.Read.Keys)
				{
					if ((Object)(object)key == (Object)null || !hashSet.Contains(key))
					{
						list.Add(key);
					}
				}
				foreach (Container item2 in list)
				{
					area.Read.Remove(item2);
				}
			}
			foreach (List<Stack> value3 in area.Sums.Values)
			{
				value3.Clear();
			}
			foreach (Container item3 in area.List)
			{
				if ((Object)(object)item3 == (Object)null || OpenByOthers(item3))
				{
					continue;
				}
				Kept.Clear();
				foreach (ItemData allItem in item3.GetInventory().GetAllItems())
				{
					if (allItem?.m_shared == null)
					{
						continue;
					}
					int num = ((area.LeaveOne && Kept.Add(allItem.m_shared.m_name)) ? (allItem.m_stack - 1) : allItem.m_stack);
					if (!area.Sums.TryGetValue(allItem.m_shared.m_name, out var value2))
					{
						value2 = (area.Sums[allItem.m_shared.m_name] = new List<Stack>(2));
					}
					Stack stack = null;
					foreach (Stack item4 in value2)
					{
						if (item4.Quality == allItem.m_quality && item4.WorldLevel == allItem.m_worldLevel)
						{
							stack = item4;
							break;
						}
					}
					if (stack == null)
					{
						List<Stack> list3 = value2;
						Stack obj = new Stack
						{
							Quality = allItem.m_quality,
							WorldLevel = allItem.m_worldLevel
						};
						stack = obj;
						list3.Add(obj);
					}
					stack.Amount += num;
				}
			}
		}

		private static int Usable(Inventory inventory, string name, int quality, bool matchWorldLevel)
		{
			int num = inventory.CountItems(name, quality, matchWorldLevel);
			if (num <= 0 || !StoreRules.LeaveOne)
			{
				return num;
			}
			return Mathf.Max(0, Mathf.Min(num, inventory.CountItems(name, -1, false) - 1));
		}

		public static int Count(Area area, string name, int quality = -1, bool matchWorldLevel = true)
		{
			UpdateSums(area);
			if (name == null || !area.Sums.TryGetValue(name, out var value))
			{
				return 0;
			}
			int num = 0;
			foreach (Stack item in value)
			{
				if ((quality < 0 || item.Quality == quality) && (!matchWorldLevel || item.WorldLevel >= Game.m_worldLevel))
				{
					num += item.Amount;
				}
			}
			return num;
		}

		public static int CountReady(Area area, string name, int quality = -1, bool matchWorldLevel = true)
		{
			if (name == null)
			{
				return 0;
			}
			if (area.ReadyFrame != Time.frameCount)
			{
				area.ReadyFrame = Time.frameCount;
				area.ReadyMemo.Clear();
			}
			string key = name + "|" + quality + (matchWorldLevel ? "|w" : "|a");
			if (area.ReadyMemo.TryGetValue(key, out var value))
			{
				return value;
			}
			int num = 0;
			foreach (Container item in area.List)
			{
				if (Ready(item))
				{
					Fresh(item);
					num += Usable(item.GetInventory(), name, quality, matchWorldLevel);
				}
			}
			area.ReadyMemo[key] = num;
			return num;
		}

		public static int Take(Area area, string name, int amount, int quality = -1, bool matchWorldLevel = true)
		{
			int num = 0;
			foreach (Container item in area.List)
			{
				if (amount <= 0)
				{
					break;
				}
				if (Ready(item))
				{
					Fresh(item);
					Inventory inventory = item.GetInventory();
					int num2 = Usable(inventory, name, quality, matchWorldLevel);
					if (num2 > 0)
					{
						int num3 = Mathf.Min(num2, amount);
						inventory.RemoveItem(name, num3, quality, matchWorldLevel);
						amount -= num3;
						num += num3;
					}
				}
			}
			if (num > 0)
			{
				area.Dirty = true;
				area.ReadyMemo.Clear();
			}
			return num;
		}

		public static bool Ask(Area area, string name, int missing, int quality = -1, bool matchWorldLevel = true)
		{
			missing -= CountReady(area, name, quality, matchWorldLevel);
			foreach (Container item in area.List)
			{
				if (missing <= 0)
				{
					break;
				}
				if (!((Object)(object)item == (Object)null) && !Ready(item) && !OpenByOthers(item))
				{
					int num = Usable(item.GetInventory(), name, quality, matchWorldLevel);
					if (num > 0)
					{
						Request(item);
						missing -= num;
					}
				}
			}
			return Waiting();
		}

		public static bool Ready(Container chest)
		{
			if ((Object)(object)chest != (Object)null && (Object)(object)chest.m_nview != (Object)null && chest.m_nview.IsValid() && chest.m_nview.IsOwner())
			{
				if (chest.m_inUse && !((Object)(object)InventoryGui.instance == (Object)null))
				{
					return (Object)(object)InventoryGui.instance.m_currentContainer == (Object)(object)chest;
				}
				return true;
			}
			return false;
		}

		public static void Request(Container chest)
		{
			if (!((Object)(object)chest == (Object)null) && !Ready(chest) && !((Object)(object)chest.m_nview == (Object)null) && chest.m_nview.IsValid() && !((Object)(object)Game.instance == (Object)null))
			{
				float unscaledTime = Time.unscaledTime;
				if ((!Pending.TryGetValue(chest, out var value) || !(unscaledTime - value < 2f)) && (!Refused.TryGetValue(chest, out var value2) || !(unscaledTime - value2 < 3f)))
				{
					Pending[chest] = unscaledTime;
					chest.m_nview.InvokeRPC("RPC_RequestOpen", new object[1] { Game.instance.GetPlayerProfile().GetPlayerID() });
				}
			}
		}

		public static bool Waiting()
		{
			if (Pending.Count == 0)
			{
				return false;
			}
			float unscaledTime = Time.unscaledTime;
			bool result = false;
			List<Container> list = null;
			foreach (KeyValuePair<Container, float> item in Pending)
			{
				if ((Object)(object)item.Key != (Object)null && unscaledTime - item.Value < 2f && !Ready(item.Key))
				{
					result = true;
				}
				else
				{
					(list ?? (list = new List<Container>())).Add(item.Key);
				}
			}
			if (list != null)
			{
				foreach (Container item2 in list)
				{
					Pending.Remove(item2);
				}
			}
			return result;
		}

		private static bool OpenResponse(Container __instance, bool granted)
		{
			if (!Pending.ContainsKey(__instance))
			{
				return true;
			}
			if (granted)
			{
				Pending[__instance] = Time.unscaledTime;
			}
			else
			{
				Pending.Remove(__instance);
				Refused[__instance] = Time.unscaledTime;
			}
			return false;
		}
	}
}
namespace DigiCore
{
	public static class ChestFlags
	{
		public const string NoStore = "digi_nostore";

		public const string NoTake = "digi_notake";

		public static bool StoreBlocked(Container chest)
		{
			return Get(chest, "digi_nostore");
		}

		public static bool TakeBlocked(Container chest)
		{
			return Get(chest, "digi_notake");
		}

		private static bool Get(Container chest, string key)
		{
			if ((Object)(object)chest == (Object)null)
			{
				return false;
			}
			ZNetView val = ((Component)chest).GetComponent<ZNetView>();
			if ((Object)(object)val == (Object)null && (Object)(object)chest.m_rootObjectOverride != (Object)null)
			{
				val = chest.m_rootObjectOverride;
			}
			if ((Object)(object)val != (Object)null && val.IsValid())
			{
				return val.GetZDO().GetBool(key, false);
			}
			return false;
		}
	}
	internal static class CreativeWorld
	{
		private const string Guid = "digi.valheim.creativeworld";

		private static FieldInfo _active;

		private static bool _looked;

		internal static bool Active
		{
			get
			{
				if (!_looked)
				{
					_looked = true;
					if (Chainloader.PluginInfos.TryGetValue("digi.valheim.creativeworld", out var value) && (Object)(object)value.Instance != (Object)null)
					{
						_active = AccessTools.Field(((object)value.Instance).GetType(), "_active");
					}
				}
				if (_active != null)
				{
					return (bool)_active.GetValue(null);
				}
				return false;
			}
		}
	}
	public sealed class ModuleInfo
	{
		public readonly Type Type;

		public readonly string Title;

		public readonly string OldGuid;

		public readonly string Description;

		public readonly string[] Requires;

		public readonly bool DefaultOn;

		public readonly bool OffOnce;

		public readonly string FormerTitle;

		public ModuleInfo(Type type, string title, string oldGuid, string description, string[] requires = null, bool defaultOn = true, bool offOnce = false, string formerTitle = null)
		{
			OffOnce = offOnce;
			FormerTitle = formerTitle;
			Type = type;
			Title = title;
			OldGuid = oldGuid;
			Description = description;
			Requires = requires ?? new string[0];
			DefaultOn = defaultOn;
		}
	}
	public abstract class DigiPlugin : BaseUnityPlugin
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<char, bool> <>9__11_0;

			public static Func<string, string> <>9__17_0;

			public static Func<string, bool> <>9__17_1;

			public static Func<string, bool> <>9__17_2;

			public static Func<string, string> <>9__17_3;

			public static Func<string, bool> <>9__17_4;

			public static Func<string, string> <>9__17_5;

			public static Func<string, string> <>9__26_0;

			public static Func<string, string> <>9__26_2;

			public static PopupButtonCallback <>9__26_3;

			public static Func<string, bool> <>9__31_0;

			internal bool <get_PackageName>b__11_0(char c)
			{
				if (!char.IsLetterOrDigit(c))
				{
					return c == ' ';
				}
				return true;
			}

			internal string <Awake>b__17_0(string l)
			{
				return l.Trim();
			}

			internal bool <Awake>b__17_1(string l)
			{
				return l.Length > 0;
			}

			internal bool <Awake>b__17_2(string r)
			{
				return !Chainloader.PluginInfos.ContainsKey(r);
			}

			internal string <Awake>b__17_3(string r)
			{
				if (!RequirementNames.TryGetValue(r, out var value))
				{
					return r;
				}
				return value;
			}

			internal bool <Awake>b__17_4(string r)
			{
				return !Chainloader.PluginInfos.ContainsKey(r);
			}

			internal string <Awake>b__17_5(string r)
			{
				if (!RequirementNames.TryGetValue(r, out var value))
				{
					return r;
				}
				return value;
			}

			internal string <ShowDuplicates>b__26_0(string d)
			{
				return d.Substring(d.IndexOf('|') + 1);
			}

			internal string <ShowDuplicates>b__26_2(string n)
			{
				return n;
			}

			internal void <ShowDuplicates>b__26_3()
			{
				UnifiedPopup.Pop();
			}

			internal bool <Apply>b__31_0(string r)
			{
				return !Chainloader.PluginInfos.ContainsKey(r);
			}
		}

		public const string ModulesSection = "0 - Sub-mods";

		internal static DigiPlugin StartingHost;

		internal static ModuleInfo StartingModule;

		private static readonly Dictionary<string, string> RequirementNames = new Dictionary<string, string>
		{
			{ "randyknapp.mods.epicloot", "Epic Loot" },
			{ "com.jotunn.jotunn", "Jotunn" },
			{ "ValheimLegends", "Valheim Legends" },
			{ "vapok.mods.adventurebackpacks", "Adventure Backpacks" },
			{ "MidnightsFX.StarLevelSystem", "Star Level System" },
			{ "sosal.nordicrugs", "Nordic Rugs" },
			{ "LuminairPrime.valheim.localcraftfromstorageprime", "Local Craft From Storage Prime" }
		};

		private readonly Dictionary<ModuleInfo, DigiModule> _running = new Dictionary<ModuleInfo, DigiModule>();

		private readonly Dictionary<ModuleInfo, ConfigEntry<bool>> _switches = new Dictionary<ModuleInfo, ConfigEntry<bool>>();

		private HashSet<string> _migrated;

		private const string DuplicatesKey = "digi.valheim.duplicates";

		private const string DuplicatesShownKey = "digi.valheim.duplicates.shown";

		private const string PopupOwnerKey = "digi.valheim.duplicates.popup2";

		protected abstract ModuleInfo[] Modules { get; }

		protected virtual bool Standalone => false;

		internal bool IsStandalone => Standalone;

		protected virtual string PackageName
		{
			get
			{
				string text = ((BaseUnityPlugin)this).Info.Metadata.Name.Replace("Digi's ", "");
				if (Standalone)
				{
					return Regex.Replace(text, "[^A-Za-z0-9]+", "_").Trim(new char[1] { '_' });
				}
				return string.Join("_", new string(text.Where((char c) => char.IsLetterOrDigit(c) || c == ' ').ToArray()).Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
			}
		}

		private string MigratedFile => Path.Combine(Paths.ConfigPath, ((BaseUnityPlugin)this).Info.Metadata.GUID + ".migrated.txt");

		private static List<string> Duplicates
		{
			get
			{
				List<string> list = AppDomain.CurrentDomain.GetData("digi.valheim.duplicates") as List<string>;
				if (list == null)
				{
					list = new List<string>();
					AppDomain.CurrentDomain.SetData("digi.valheim.duplicates", list);
				}
				return list;
			}
		}

		protected virtual void Awake()
		{
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = true;
			((BaseUnityPlugin)this).Config.Save();
			_migrated = (File.Exists(MigratedFile) ? new HashSet<string>(from l in File.ReadAllLines(MigratedFile)
				select l.Trim() into l
				where l.Length > 0
				select l) : new HashSet<string>());
			bool flag = !_migrated.Contains("#switches");
			ModuleInfo[] modules;
			if (Standalone)
			{
				modules = Modules;
				foreach (ModuleInfo moduleInfo in modules)
				{
					List<string> list = moduleInfo.Requires.Where((string r) => !Chainloader.PluginInfos.ContainsKey(r)).ToList();
					if (list.Count > 0)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)(moduleInfo.Title + ": not started, needs " + string.Join(" and ", list.Select((string r) => (!RequirementNames.TryGetValue(r, out var value2)) ? r : value2)) + "."));
					}
					else
					{
						StartModule(moduleInfo);
					}
				}
				return;
			}
			modules = Modules;
			foreach (ModuleInfo moduleInfo2 in modules)
			{
				List<string> list2 = moduleInfo2.Requires.Where((string r) => !Chainloader.PluginInfos.ContainsKey(r)).ToList();
				string value2;
				string text = ((moduleInfo2.Requires.Length == 0) ? "" : (" Needs " + string.Join(" and ", moduleInfo2.Requires.Select((string r) => (!RequirementNames.TryGetValue(r, out value2)) ? r : value2)) + "."));
				ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("0 - Sub-mods", moduleInfo2.Title, moduleInfo2.DefaultOn, moduleInfo2.Description + text);
				if (flag && !moduleInfo2.DefaultOn && File.Exists(OldConfigPath(moduleInfo2)))
				{
					val.Value = true;
				}
				if (moduleInfo2.FormerTitle != null && !_migrated.Contains("#renamed:" + moduleInfo2.FormerTitle))
				{
					if (File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath) && ReadCfg(((BaseUnityPlugin)this).Config.ConfigFilePath).TryGetValue("0 - Sub-mods\n" + moduleInfo2.FormerTitle, out var value) && bool.TryParse(value, out var result))
					{
						val.Value = result;
					}
					Remember("#renamed:" + moduleInfo2.FormerTitle);
				}
				if (moduleInfo2.OffOnce && !_migrated.Contains("#off:" + moduleInfo2.OldGuid))
				{
					val.Value = false;
					Remember("#off:" + moduleInfo2.OldGuid);
				}
				_switches[moduleInfo2] = val;
				ModuleInfo captured = moduleInfo2;
				val.SettingChanged += delegate
				{
					Apply(captured);
				};
				if (list2.Count > 0)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)(moduleInfo2.Title + ": off, needs " + string.Join(", ", list2) + "."));
				}
			}
			if (flag)
			{
				Remember("#switches");
			}
			modules = Modules;
			foreach (ModuleInfo module in modules)
			{
				Apply(module);
			}
		}

		private void Start()
		{
			foreach (KeyValuePair<ModuleInfo, DigiModule> item in _running.ToList())
			{
				if (!((Object)(object)item.Value == (Object)null) && !(item.Key.OldGuid == ((BaseUnityPlugin)this).Info.Metadata.GUID) && Chainloader.PluginInfos.ContainsKey(item.Key.OldGuid))
				{
					if (!IsOurSingle(item.Key.OldGuid))
					{
						OtherMods.SwitchOff(item.Key.OldGuid, null, ((BaseUnityPlugin)this).Logger);
						continue;
					}
					item.Value.Teardown();
					_running.Remove(item.Key);
					Forget(item.Key.OldGuid);
					LeaveToSingle(item.Key);
				}
			}
			SettingOrder.Apply(((BaseUnityPlugin)this).Config);
			if (!Application.isBatchMode && AppDomain.CurrentDomain.GetData("digi.valheim.duplicates.popup2") == null)
			{
				AppDomain.CurrentDomain.SetData("digi.valheim.duplicates.popup2", true);
				AppDomain.CurrentDomain.SetData("digi.valheim.duplicates.shown", true);
				((MonoBehaviour)this).StartCoroutine(ShowDuplicates());
			}
		}

		private void LeaveToSingle(ModuleInfo module)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)(module.Title + ": runs as its own mod (" + module.OldGuid + "), so the copy in " + ((BaseUnityPlugin)this).Info.Metadata.Name + " stays off."));
		}

		private static bool IsOurSingle(string guid)
		{
			if (!Chainloader.PluginInfos.TryGetValue(guid, out var value) || (Object)(object)value.Instance == (Object)null)
			{
				return false;
			}
			Type type = ((object)value.Instance).GetType();
			while (type != null)
			{
				if (type.FullName == "DigiCore.DigiPlugin")
				{
					return true;
				}
				type = type.BaseType;
			}
			return false;
		}

		private IEnumerator ShowDuplicates()
		{
			while ((Object)(object)FejdStartup.instance == (Object)null || !UnifiedPopup.IsAvailable())
			{
				yield return (object)new WaitForSeconds(0.5f);
			}
			yield return (object)new WaitForSeconds(1f);
			OtherMods.SweepAgain();
			List<string> off = OtherMods.Names();
			List<string> list = (from n in (from d in Duplicates
					select d.Substring(d.IndexOf('|') + 1) into n
					where !off.Contains(n)
					select n).Distinct()
				orderby n
				select n).ToList();
			if (off.Count == 0 && list.Count == 0)
			{
				yield break;
			}
			string text = "";
			if (off.Count > 0)
			{
				text = "<b>" + string.Join("\n", off) + "</b>\n\nDigi's mods do the same, so these are switched off. You can remove them in your mod manager. (To use one of them instead, switch Digi's version off in F1 and restart.)";
			}
			if (list.Count > 0)
			{
				text = text + ((text.Length > 0) ? "\n\n" : "") + "<b>" + string.Join("\n", list) + "</b>\n\nRemove these in your mod manager: until then, the older Digi mod that does the same stays off (or update it).";
			}
			string obj = ((off.Count > 0) ? "Mods switched off" : "Remove these mods");
			string text2 = text;
			object obj2 = <>c.<>9__26_3;
			if (obj2 == null)
			{
				PopupButtonCallback val = delegate
				{
					UnifiedPopup.Pop();
				};
				<>c.<>9__26_3 = val;
				obj2 = (object)val;
			}
			UnifiedPopup.Push((PopupBase)new WarningPopup(obj, text2, (PopupButtonCallback)obj2, false));
		}

		private static string OldConfigPath(ModuleInfo module)
		{
			return Path.Combine(Paths.ConfigPath, module.OldGuid + ".cfg");
		}

		internal bool FirstTime(string key)
		{
			if (_migrated == null || _migrated.Contains(key))
			{
				return false;
			}
			Remember(key);
			return true;
		}

		private void Remember(string key)
		{
			if (!_migrated.Add(key))
			{
				return;
			}
			try
			{
				File.AppendAllText(MigratedFile, key + Environment.NewLine);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not write " + MigratedFile + ": " + ex.Message));
			}
		}

		private void Forget(string key)
		{
			if (!_migrated.Remove(key))
			{
				return;
			}
			try
			{
				File.WriteAllLines(MigratedFile, _migrated.ToArray());
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not write " + MigratedFile + ": " + ex.Message));
			}
		}

		private void Apply(ModuleInfo module)
		{
			bool value = _switches[module].Value;
			_running.TryGetValue(module, out var value2);
			if (value && (Object)(object)value2 == (Object)null)
			{
				if (module.Requires.Any((string r) => !Chainloader.PluginInfos.ContainsKey(r)))
				{
					return;
				}
				if (module.OldGuid != ((BaseUnityPlugin)this).Info.Metadata.GUID && Chainloader.PluginInfos.ContainsKey(module.OldGuid))
				{
					if (IsOurSingle(module.OldGuid))
					{
						LeaveToSingle(module);
						return;
					}
					OtherMods.SwitchOff(module.OldGuid, null, ((BaseUnityPlugin)this).Logger);
				}
				StartModule(module);
			}
			else if (!value && (Object)(object)value2 != (Object)null)
			{
				value2.Teardown();
				_running.Remove(module);
				((BaseUnityPlugin)this).Logger.LogInfo((object)(module.Title + ": switched off."));
			}
		}

		private void StartModule(ModuleInfo module)
		{
			StartingHost = this;
			StartingModule = module;
			try
			{
				DigiModule digiModule = (DigiModule)(object)((Component)this).gameObject.AddComponent(module.Type);
				digiModule.Host = this;
				digiModule.Info2 = module;
				_running[module] = digiModule;
				MigrateOldSettings(module, digiModule);
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"{module.Title} could not start: {arg}");
			}
			finally
			{
				StartingHost = null;
				StartingModule = null;
			}
			SettingOrder.Apply(((BaseUnityPlugin)this).Config);
		}

		private void MigrateOldSettings(ModuleInfo module, DigiModule component)
		{
			if (_migrated.Contains(module.OldGuid) || module.OldGuid == ((BaseUnityPlugin)this).Info.Metadata.GUID)
			{
				return;
			}
			string path = OldConfigPath(module);
			if (File.Exists(path) && component.ConfigOrNull != null)
			{
				Dictionary<string, string> dictionary = ReadCfg(path);
				int num = 0;
				foreach (ModuleConfig.Bound entry in component.ConfigOrNull.Entries)
				{
					if (dictionary.TryGetValue(entry.Section + "\n" + entry.Key, out var value))
					{
						try
						{
							entry.Entry.SetSerializedValue(value);
							num++;
						}
						catch (Exception ex)
						{
							((BaseUnityPlugin)this).Logger.LogWarning((object)(module.Title + ": could not copy '" + entry.Key + "': " + ex.Message));
						}
					}
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"{module.Title}: copied {num} setting(s) from {Path.GetFileName(path)}.");
			}
			Remember(module.OldGuid);
		}

		private static Dictionary<string, string> ReadCfg(string path)
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			string text = "";
			string[] array = File.ReadAllLines(path);
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length == 0 || text2.StartsWith("#"))
				{
					continue;
				}
				if (text2.StartsWith("[") && text2.EndsWith("]"))
				{
					text = text2.Substring(1, text2.Length - 2);
					continue;
				}
				int num = text2.IndexOf(" = ", StringComparison.Ordinal);
				if (num > 0)
				{
					dictionary[text + "\n" + text2.Substring(0, num).Trim()] = text2.Substring(num + 3);
				}
			}
			return dictionary;
		}

		protected virtual void OnDestroy()
		{
			foreach (DigiModule item in _running.Values.ToList())
			{
				item?.Teardown();
			}
			_running.Clear();
		}

		public bool IsRunning(Type moduleType)
		{
			return _running.Any((KeyValuePair<ModuleInfo, DigiModule> p) => p.Key.Type == moduleType && (Object)(object)p.Value != (Object)null);
		}
	}
	public abstract class DigiModule : MonoBehaviour
	{
		internal DigiPlugin Host;

		internal ModuleInfo Info2;

		private ModuleConfig _config;

		private ManualLogSource _logger;

		private Harmony _harmony;

		internal ModuleConfig ConfigOrNull => _config;

		protected ModuleConfig Config => _config ?? (_config = new ModuleConfig(((BaseUnityPlugin)(Host ?? DigiPlugin.StartingHost)).Config, (Host ?? DigiPlugin.StartingHost).IsStandalone ? null : (Info2 ?? DigiPlugin.StartingModule).Title));

		protected ManualLogSource Logger => _logger ?? (_logger = Logger.CreateLogSource("Digi's " + (Info2 ?? DigiPlugin.StartingModule)?.Title));

		protected Harmony ModuleHarmony
		{
			get
			{
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Expected O, but got Unknown
				//IL_004a: Expected O, but got Unknown
				Harmony obj = _harmony;
				if (obj == null)
				{
					Harmony val = new Harmony(((object)this).GetType().Namespace?.ToLowerInvariant() + "." + Guid.NewGuid().ToString("N"));
					Harmony val2 = val;
					_harmony = val;
					obj = val2;
				}
				return obj;
			}
		}

		protected bool SwitchOffReplaced(string guid, string name)
		{
			return OtherMods.SwitchOff(guid, name, Logger);
		}

		protected bool FirstTime(string key)
		{
			return (Host ?? DigiPlugin.StartingHost)?.FirstTime("#once:" + (Info2 ?? DigiPlugin.StartingModule)?.Title + ":" + key) ?? false;
		}

		protected Harmony PatchModule(Type type)
		{
			ModuleHarmony.PatchAll(type);
			return ModuleHarmony;
		}

		protected Harmony PatchModuleNamespace()
		{
			string text = ((object)this).GetType().Namespace;
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(((object)this).GetType().Assembly);
			foreach (Type type in typesFromAssembly)
			{
				if (type.Namespace == text || (type.Namespace != null && text != null && type.Namespace.StartsWith(text + ".")))
				{
					ModuleHarmony.CreateClassProcessor(type).Patch();
				}
			}
			return ModuleHarmony;
		}

		internal void Teardown()
		{
			try
			{
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning((object)("Unpatch: " + ex.Message));
			}
			Object.Destroy((Object)(object)this);
		}
	}
	public sealed class ModuleConfig
	{
		public sealed class Bound
		{
			public string Section;

			public string Key;

			public ConfigEntryBase Entry;
		}

		private readonly ConfigFile _file;

		private readonly string _prefix;

		internal readonly List<Bound> Entries = new List<Bound>();

		private static readonly char[] Invalid = new char[8] { '=', '\n', '\t', '\\', '"', '\'', '[', ']' };

		public ConfigFile File => _file;

		internal bool Standalone => _prefix.Length == 0;

		public string ConfigFilePath => _file.ConfigFilePath;

		internal ModuleConfig(ConfigFile file, string title)
		{
			_file = file;
			_prefix = ((title == null) ? "" : (title + " - "));
		}

		public void Reload()
		{
		}

		public void Save()
		{
			_file.Save();
		}

		public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null)
		{
			section = Clean(section);
			key = Clean(key);
			ConfigEntry<T> val = _file.Bind<T>(_prefix + section, key, defaultValue, configDescription);
			if (!Entries.Any((Bound b) => b.Section == section && b.Key == key))
			{
				Entries.Add(new Bound
				{
					Section = section,
					Key = key,
					Entry = (ConfigEntryBase)(object)val
				});
			}
			return val;
		}

		private static string Clean(string name)
		{
			if (name.IndexOfAny(Invalid) < 0)
			{
				return name;
			}
			string[] value = name.Split(Invalid, StringSplitOptions.None);
			return string.Join("", value).Trim();
		}

		public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, string description)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return Bind(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}

		public ConfigEntry<T> Bind<T>(ConfigDefinition definition, T defaultValue, ConfigDescription configDescription = null)
		{
			return Bind(definition.Section, definition.Key, defaultValue, configDescription);
		}

		public bool TryGetEntry<T>(ConfigDefinition definition, out ConfigEntry<T> entry)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			return _file.TryGetEntry<T>(new ConfigDefinition(_prefix + definition.Section, definition.Key), ref entry);
		}
	}
	internal static class OtherMods
	{
		private const string SwitchedKey = "digi.valheim.switchedoff";

		private static List<string> Switched
		{
			get
			{
				List<string> list = AppDomain.CurrentDomain.GetData("digi.valheim.switchedoff") as List<string>;
				if (list == null)
				{
					list = new List<string>();
					AppDomain.CurrentDomain.SetData("digi.valheim.switchedoff", list);
				}
				return list;
			}
		}

		internal static List<string> Names()
		{
			return (from n in Switched.Select((string l) => l.Substring(l.IndexOf('|') + 1)).Distinct()
				orderby n
				select n).ToList();
		}

		internal static bool SwitchOff(string guid, string name, ManualLogSource log)
		{
			if (!Chainloader.PluginInfos.TryGetValue(guid, out var value) || (Object)(object)value.Instance == (Object)null)
			{
				return false;
			}
			object obj = name;
			if (obj == null)
			{
				BepInPlugin metadata = value.Metadata;
				obj = ((metadata != null) ? metadata.Name : null) ?? guid;
			}
			name = (string)obj;
			int num = Silence(value.Instance);
			if (!Switched.Any((string l) => l.StartsWith(guid + "|", StringComparison.Ordinal)))
			{
				Switched.Add(guid + "|" + name);
				if (log != null)
				{
					log.LogWarning((object)$"{name} is installed too: switched it off ({num} patches removed), ours does its job. You can remove it.");
				}
			}
			return true;
		}

		internal static void SweepAgain()
		{
			foreach (string item in Switched.ToList())
			{
				string key = item.Substring(0, item.IndexOf('|'));
				if (Chainloader.PluginInfos.TryGetValue(key, out var value) && (Object)(object)value.Instance != (Object)null)
				{
					Silence(value.Instance);
				}
			}
		}

		private static int Silence(BaseUnityPlugin plugin)
		{
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			Assembly assembly = ((object)plugin).GetType().Assembly;
			if (assembly == typeof(OtherMods).Assembly)
			{
				return 0;
			}
			int num = 0;
			try
			{
				MonoBehaviour[] array = Object.FindObjectsByType<MonoBehaviour>((FindObjectsInactive)1, (FindObjectsSortMode)0);
				foreach (MonoBehaviour val in array)
				{
					if (!((Object)(object)val == (Object)null) && !(((object)val).GetType().Assembly != assembly))
					{
						val.StopAllCoroutines();
						((Behaviour)val).enabled = false;
					}
				}
				if (((Behaviour)plugin).enabled)
				{
					((Behaviour)plugin).enabled = false;
				}
				foreach (MethodBase item in Harmony.GetAllPatchedMethods().ToList())
				{
					Patches patchInfo = Harmony.GetPatchInfo(item);
					if (patchInfo == null)
					{
						continue;
					}
					foreach (Patch item2 in patchInfo.Prefixes.Concat(patchInfo.Postfixes).Concat(patchInfo.Transpilers).Concat(patchInfo.Finalizers)
						.Concat(patchInfo.ILManipulators)
						.ToList())
					{
						Type type = item2.PatchMethod?.DeclaringType;
						if (!(type == null) && !(type.Assembly != assembly) && !(type.Namespace ?? "").StartsWith("ServerSync", StringComparison.Ordinal))
						{
							try
							{
								new Harmony(item2.owner).Unpatch(item, item2.PatchMethod);
								num++;
							}
							catch (Exception)
							{
							}
						}
					}
				}
				Unhook(plugin.Config, assembly);
			}
			catch (Exception)
			{
			}
			return num;
		}

		private static void Unhook(ConfigFile config, Assembly assembly)
		{
			if (config == null)
			{
				return;
			}
			Strip(config, typeof(ConfigFile), assembly);
			foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in config)
			{
				Strip(item.Value, ((object)item.Value).GetType(), assembly);
			}
		}

		private static void Strip(object owner, Type type, Assembly assembly)
		{
			FieldInfo field = type.GetField("SettingChanged", BindingFlags.Instance | BindingFlags.NonPublic);
			if (owner != null && !(field == null) && field.GetValue(owner) is Delegate obj)
			{
				Delegate[] array = (from d in obj.GetInvocationList()
					where d.Method.DeclaringType == null || d.Method.DeclaringType.Assembly != assembly
					select d).ToArray();
				if (array.Length < obj.GetInvocationList().Length)
				{
					field.SetValue(owner, Delegate.Combine(array));
				}
			}
		}
	}
}
namespace DigiQoL
{
	[BepInPlugin("digi.valheim.qol", "Digi's Inventory and QoL", "1.0.39")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : DigiPlugin
	{
		public const string Guid = "digi.valheim.qol";

		public const string Name = "Digi's Inventory and QoL";

		public const string Version = "1.0.39";

		protected override ModuleInfo[] Modules { get; } = new ModuleInfo[19]
		{
			new ModuleInfo(typeof(BackpackAtStations.Plugin), "Backpack At Stations", "digi.valheim.backpackatstations", "Open your Adventure Backpack at crafting stations (older Adventure Backpacks; 2.4 and newer do it themselves).", new string[1] { "vapok.mods.adventurebackpacks" }),
			new ModuleInfo(typeof(BackpackQuickOpen.Plugin), "Backpack Quick Open", "digi.valheim.backpackquickopen", "Middle-click a backpack in your inventory to open it without wearing it, e.g. while you wear a cape.", new string[1] { "vapok.mods.adventurebackpacks" }),
			new ModuleInfo(typeof(StoreNearby.Plugin), "Store Nearby", "digi.valheim.storenearby", "A Store Nearby button under your inventory (and an open backpack): your items go into the chests around you that already hold them; a checkbox per chest; replaces Local Craft From Storage's."),
			new ModuleInfo(typeof(StoreInBackpacks.Plugin), "Store In Backpacks", "digi.valheim.storeinbackpacks", "A To Backpacks button next to Store Nearby: your items go into the backpacks you carry that already hold them.", new string[1] { "vapok.mods.adventurebackpacks" }),
			new ModuleInfo(typeof(SafeItemMove.Plugin), "Safe Item Move", "digi.valheim.safeitemmove", "Items you drag around your inventory can no longer vanish, chests never flash another chest's items, holding E on a chest no longer dumps your stacks into it, and Place stacks leaves your hotbar alone."),
			new ModuleInfo(typeof(AchievementKeeper.Plugin), "Achievement Keeper", "digi.valheim.achievementkeeper", "Steam achievements keep working with mods."),
			new ModuleInfo(typeof(KeepRested.Plugin), "Keep Rested", "digi.valheim.keeprested", "Your Rested buff stays when you log out and back in, and resting gives Rested twice as fast."),
			new ModuleInfo(typeof(EffectDetails.Plugin), "Effect Details", "digi.valheim.effectdetails", "Effect tooltips show the values the game leaves out, e.g. All damage: +10% for Aesir mead, and weapon tooltips a damage total."),
			new ModuleInfo(typeof(CameraClipFix.Plugin), "Camera Clip Fix", "digi.valheim.cameraclipfix", "In third person the camera no longer goes partly into a floor above you, a roof or a wall: it comes closer instead."),
			new ModuleInfo(typeof(ChestFillOrder.Plugin), "Chest Fill Order", "digi.valheim.chestfillorder", "What you put into a chest, cart, ship or backpack goes into the first free slot from the top left, instead of the game's bottom row first."),
			new ModuleInfo(typeof(ChestSorter.Plugin), "Chest Sorter", "digi.valheim.chestsorter", "Chests sort themselves when you open them and after Store Nearby: grouped by kind, A-Z, from the top left, stacks merged."),
			new ModuleInfo(typeof(ChestWindowFit.Plugin), "Chest Window Fit", "digi.valheim.chestwindowfit", "Chests with more rows than the chest window shows (the Grausten chest) open in a window tall enough for all of them: no scroll bar."),
			new ModuleInfo(typeof(ItemPickupFix.Plugin), "Item Pickup Fix", "digi.valheim.itempickupfix", "Items from other mods that cannot be picked up and fall through the floor (a collider without a shape) get a working one, and Equipment Slots' quick slot key V no longer switches the game's auto pickup off too."),
			new ModuleInfo(typeof(SellToHaldor.Plugin), "Sell To Haldor", "digi.valheim.selltohaldor", "Haldor also buys your food and feasts (a box in his window) and every kind of hide and leather."),
			new ModuleInfo(typeof(LighterInventory.Plugin), "Lighter Inventory", "digi.valheim.lighterinventory", "An open inventory costs less: items and the recipe panel are redrawn when something changes instead of every frame, also Equipment Slots' panel; opening it no longer rebuilds an unchanged recipe list and only draws the recipes in view."),
			new ModuleInfo(typeof(SkillXp.Plugin), "Skill XP", "digi.valheim.skillxp", "The Skills window shows each skill's XP, e.g. 24  12/63."),
			new ModuleInfo(typeof(AutoCloseDoors.Plugin), "Auto Close Doors", "digi.valheim.autoclosedoors", "Doors you built close by themselves 15 seconds after opening, never on someone standing in the doorway."),
			new ModuleInfo(typeof(CompactStatusEffects.Plugin), "Compact Status Effects", "digi.valheim.compactstatuseffects", "The effect icons top right take less room: smaller icons, no names under them, and the effects that never change (what you wear, always-on forsaken powers) left out."),
			new ModuleInfo(typeof(HudGrid.Plugin), "HUD Grid", "digi.valheim.hudgrid", "Better Archery's arrow slots, Valheim Legends' abilities and CDEV's quick slots in one tidy grid beside the health bar, in the hotbar's look.")
		};
	}
}
namespace StoreNearby
{
	public class Plugin : DigiModule
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static UnityAction <0>__Clicked;

			public static Func<string, string> <1>__Normal;
		}

		internal const string LcfspGuid = "LuminairPrime.valheim.localcraftfromstorageprime";

		private const string LcfspConfig = "LuminairPrime.valheim.localcraftfromstorageprime.cfg";

		private const string Label = "Store Nearby";

		internal static ConfigEntry<float> Range;

		internal static ConfigEntry<bool> StoreFood;

		internal static ConfigEntry<bool> StorePotions;

		internal static ConfigEntry<bool> StoreMagic;

		internal static ConfigEntry<bool> ExtraSlots;

		internal static ConfigEntry<bool> Backpack;

		internal static ConfigEntry<bool> Checkbox;

		internal static ConfigEntry<int> KeepRows;

		internal static ConfigEntry<string> AlwaysKeep;

		internal static ConfigEntry<string> AlwaysStore;

		public static bool Running;

		internal static Button Button;

		private static readonly ChestRules Rules = new ChestRules
		{
			BlockFlag = "digi_nostore"
		};

		private static readonly Chests.Area Area = new Chests.Area(Rules);

		private static Plugin _instance;

		private static ChestCheckbox _box;

		private static float _nextCheck;

		private static bool _busy;

		private static FieldInfo _backpackIsOpen;

		private static bool _backpackResolved;

		private const string CheckboxTooltip = "<color=yellow>Ticked</color> (normal): Store Nearby may put your items into this chest.\n<color=yellow>Unticked</color>: Store Nearby skips this chest.\n\nCrafting, building and the auto stations keep using it as normal (that is the other box).";

		private static readonly string[] KeepPrefabs = new string[13]
		{
			"CryptKey", "DvergrKey", "BloodGoldKey", "HildirKey_forestcrypt", "HildirKey_mountaincave", "HildirKey_plainsfortress", "chest_hildir1", "chest_hildir2", "chest_hildir3", "BarberKit",
			"BombSiege", "Catapult_ammo", "Catapult_Ammo_BloodGold"
		};

		private static HashSet<string> _keepTokens;

		private static HashSet<string> _storeTokens;

		private static HashSet<string> _made;

		private static ObjectDB _madeFor;

		private const string MagicKey = "randyknapp.mods.epicloot#EpicLoot.MagicItemComponent";

		private static Func<ItemData, bool> _favourite;

		private static bool _favouriteResolved;

		private static ChestCheckbox Box => _box ?? (_box = new ChestCheckbox("DigiStoreNearbyCheckbox", "digi_nostore", "Store Nearby", "Store Nearby puts into it", "<color=yellow>Ticked</color> (normal): Store Nearby may put your items into this chest.\n<color=yellow>Unticked</color>: Store Nearby skips this chest.\n\nCrafting, building and the auto stations keep using it as normal (that is the other box)."));

		private void Awake()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			_instance = this;
			Range = base.Config.Bind("1 - Store Nearby", "Range (m)", 50f, new ConfigDescription("How far from you a chest may be.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 100f), Array.Empty<object>()));
			Backpack = base.Config.Bind("1 - Store Nearby", "Open backpack too", defaultValue: true, "With an Adventure Backpacks backpack open, the button shows under it and stores your bag and the backpack.");
			StoreFood = base.Config.Bind("2 - What goes", "Store food", defaultValue: true, "Cooked food (stews, pies, cooked meat, ...) goes too, into chests that already hold it. Off: it stays with you. Raw food (berries, mushrooms, honey, ...) always goes.");
			StorePotions = base.Config.Bind("2 - What goes", "Store potions", defaultValue: true, "Meads and potions go too, into chests that already hold them. Off: they stay with you.");
			StoreMagic = base.Config.Bind("2 - What goes", "Store magic gear", defaultValue: true, "Epic Loot gear (magic and unidentified weapons, armour, ...) goes too, into chests that already hold Epic Loot gear (any piece). Worn gear, the hotbar and kept rows, favourites and the always-keep list stay with you. Off: it stays with you.");
			KeepRows = base.Config.Bind("2 - What goes", "Keep rows", 0, new ConfigDescription("Rows of your inventory below the hotbar that stay with you (the hotbar, the top row, always stays).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 7), Array.Empty<object>()));
			ExtraSlots = base.Config.Bind("2 - What goes", "Leave extra slots alone", defaultValue: true, "Items in slots that other mods add outside the inventory (equipment and quick slots) are never stored.");
			AlwaysKeep = base.Config.Bind("2 - What goes", "Always keep", "", "These always stay with you: item names or prefab names, comma-separated (\"Honey, Tankard\"), or the kinds food, potions, materials, trophies, fish, magic.");
			AlwaysStore = base.Config.Bind("2 - What goes", "Always store", "", "These always go, even gear or keys that normally stay: item names or prefab names, comma-separated. Always keep wins.");
			Checkbox = base.Config.Bind("3 - Chests", "Chest checkbox", defaultValue: true, "A \"Store Nearby\" checkbox in chest windows (where the chest's title was): untick it and Store Nearby skips that chest.");
			Checkbox.SettingChanged += delegate
			{
				RefreshBox();
			};
			AlwaysKeep.SettingChanged += delegate
			{
				_keepTokens = null;
			};
			AlwaysStore.SettingChanged += delegate
			{
				_storeTokens = null;
			};
			if (FirstTime("from local craft from storage"))
			{
				TakeOverSettings();
			}
		}

		private void Start()
		{
			SwitchOffReplaced("LuminairPrime.valheim.localcraftfromstorageprime", "Local Craft From Storage Prime");
			Chests.Use();
			PatchModule(typeof(Plugin));
			Running = true;
		}

		private void OnDestroy()
		{
			if (Running)
			{
				Running = false;
				Chests.Release();
				if ((Object)(object)Button != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)Button).gameObject);
				}
				Button = null;
				_box?.Destroy();
				_box = null;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void BeforeStore(Player player, List<Inventory> sources, float range)
		{
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void AfterStore(List<Container> chests)
		{
		}

		public static bool KeepsRow(int row)
		{
			return row <= ((KeepRows != null) ? KeepRows.Value : 0);
		}

		private static void RefreshBox()
		{
			if ((Object)(object)InventoryGui.instance != (Object)null)
			{
				Box.Refresh(InventoryGui.instance, Checkbox.Value);
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "Show")]
		[HarmonyPostfix]
		private static void Shown(InventoryGui __instance)
		{
			_nextCheck = 0f;
			Box.Refresh(__instance, Checkbox.Value);
		}

		[HarmonyPatch(typeof(InventoryGui), "Update")]
		[HarmonyPostfix]
		private static void Updated(InventoryGui __instance)
		{
			if (!InventoryGui.IsVisible())
			{
				if ((Object)(object)Button != (Object)null && ((Component)Button).gameObject.activeSelf)
				{
					((Component)Button).gameObject.SetActive(false);
				}
			}
			else
			{
				if (ChestCheckbox.Closing(__instance))
				{
					return;
				}
				Box.Update(__instance, Checkbox.Value);
				bool flag = BackpackOpen(__instance);
				if (!((Object)(object)__instance.m_currentContainer == (Object)null || flag))
				{
					if ((Object)(object)Button != (Object)null && ((Component)Button).gameObject.activeSelf)
					{
						((Component)Button).gameObject.SetActive(false);
					}
					return;
				}
				if ((Object)(object)Button == (Object)null)
				{
					Create(__instance);
				}
				if (!((Object)(object)Button == (Object)null))
				{
					RectTransform val = (flag ? __instance.m_container : __instance.m_player);
					if ((Object)(object)((Component)Button).transform.parent != (Object)(object)val)
					{
						((Component)Button).transform.SetParent((Transform)(object)val, false);
					}
					if (!((Component)Button).gameObject.activeSelf)
					{
						((Component)Button).gameObject.SetActive(true);
					}
					if (Time.unscaledTime >= _nextCheck)
					{
						_nextCheck = Time.unscaledTime + 0.5f;
						((Selectable)Button).interactable = !_busy && Here().Count > 0;
					}
				}
			}
		}

		private static void Create(InventoryGui gui)
		{
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Expected O, but got Unknown
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Expected O, but got Unknown
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			Button val = (((Object)(object)gui.m_takeAllButton != (Object)null) ? gui.m_takeAllButton : gui.m_stackAllButton);
			if ((Object)(object)val == (Object)null || (Object)(object)gui.m_player == (Object)null)
			{
				return;
			}
			Transform val2 = ((Transform)gui.m_player).Find("DigiStoreNearbyButton");
			if ((Object)(object)val2 != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)val2).gameObject);
			}
			GameObject val3 = Object.Instantiate<GameObject>(((Component)val).gameObject, (Transform)(object)gui.m_player, false);
			((Object)val3).name = "DigiStoreNearbyButton";
			Localize[] componentsInChildren = val3.GetComponentsInChildren<Localize>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				((Behaviour)componentsInChildren[i]).enabled = false;
			}
			Button = val3.GetComponent<Button>();
			Button.onClick = new ButtonClickedEvent();
			ButtonClickedEvent onClick = Button.onClick;
			object obj = <>O.<0>__Clicked;
			if (obj == null)
			{
				UnityAction val4 = Clicked;
				<>O.<0>__Clicked = val4;
				obj = (object)val4;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
			TMP_Text componentInChildren = val3.GetComponentInChildren<TMP_Text>(true);
			RectTransform val5 = (RectTransform)val3.transform;
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.text = "Store Nearby";
				float num = componentInChildren.GetPreferredValues("Store Nearby").x + 40f;
				if (num > val5.sizeDelta.x)
				{
					val5.sizeDelta = new Vector2(num, val5.sizeDelta.y);
				}
			}
			Vector2 val6 = default(Vector2);
			((Vector2)(ref val6))..ctor(1f, 0f);
			val5.anchorMax = val6;
			val5.anchorMin = val6;
			val5.pivot = new Vector2(1f, 1f);
			val5.anchoredPosition = new Vector2(-1.3f, -10f);
			((Transform)val5).localScale = Vector3.one;
		}

		private static bool BackpackOpen(InventoryGui gui)
		{
			if (!_backpackResolved)
			{
				_backpackResolved = true;
				Type type = AccessTools.TypeByName("AdventureBackpacks.Patches.InventoryGuiPatches");
				_backpackIsOpen = ((type != null) ? AccessTools.Field(type, "BackpackIsOpen") : null);
			}
			if (Backpack.Value && _backpackIsOpen != null && (Object)(object)gui.m_currentContainer != (Object)null)
			{
				return (bool)_backpackIsOpen.GetValue(null);
			}
			return false;
		}

		private static List<Container> Here()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			Rules.Range = Range.Value;
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer != (Object)null))
			{
				return new List<Container>();
			}
			return Chests.Near(Area, ((Component)localPlayer).transform.position);
		}

		private static void Clicked()
		{
			Player localPlayer = Player.m_localPlayer;
			InventoryGui instance = InventoryGui.instance;
			if (_busy || (Object)(object)localPlayer == (Object)null || (Object)(object)instance == (Object)null || ((Character)localPlayer).IsDead() || ((Character)localPlayer).IsTeleporting())
			{
				return;
			}
			List<Inventory> list = new List<Inventory> { ((Humanoid)localPlayer).m_inventory };
			Container currentContainer = instance.m_currentContainer;
			if (BackpackOpen(instance))
			{
				list.Add(instance.m_currentContainer.GetInventory());
			}
			try
			{
				BeforeStore(localPlayer, list, Range.Value);
			}
			catch (Exception ex)
			{
				Plugin instance2 = _instance;
				if (instance2 != null)
				{
					instance2.Logger.LogWarning((object)("Before Store Nearby: " + ex.Message));
				}
			}
			HashSet<string> wanted = new HashSet<string>();
			bool magic = false;
			foreach (Inventory item in list)
			{
				foreach (ItemData allItem in item.GetAllItems())
				{
					if (Sendable(allItem, item))
					{
						wanted.Add(allItem.m_shared.m_name);
					}
					if (SendableMagic(allItem, item))
					{
						magic = true;
					}
				}
			}
			if (wanted.Count == 0 && !magic)
			{
				((Character)localPlayer).Message((MessageType)2, "Nothing to store", 0, (Sprite)null, false);
				return;
			}
			bool flag = false;
			foreach (Container item2 in Here())
			{
				if (!((Object)(object)item2 == (Object)null) && !((Object)(object)item2 == (Object)(object)currentContainer) && !Chests.Ready(item2) && !Chests.OpenByOthers(item2) && item2.GetInventory().GetAllItems().Any((ItemData i) => i?.m_shared != null && (wanted.Contains(i.m_shared.m_name) || (magic && IsMagic(i)))))
				{
					Chests.Request(item2);
					flag = true;
				}
			}
			if (flag && Chests.Waiting() && (Object)(object)_instance != (Object)null)
			{
				((MonoBehaviour)_instance).StartCoroutine(StoreWhenReady(localPlayer, list, currentContainer));
			}
			else
			{
				Store(localPlayer, list, currentContainer);
			}
		}

		private static IEnumerator StoreWhenReady(Player player, List<Inventory> sources, Container exclude)
		{
			_busy = true;
			float until = Time.unscaledTime + 2.5f;
			while (Chests.Waiting() && Time.unscaledTime < until)
			{
				yield return null;
			}
			_busy = false;
			if ((Object)(object)player != (Object)null && (Object)(object)player == (Object)(object)Player.m_localPlayer && InventoryGui.IsVisible())
			{
				Store(player, sources, exclude);
			}
		}

		private static void Store(Player player, List<Inventory> sources, Container exclude)
		{
			List<Container> list = Here();
			List<Container> list2 = new List<Container>();
			int num = 0;
			bool flag = false;
			foreach (Inventory source in sources)
			{
				foreach (ItemData item in source.GetAllItems().ToList())
				{
					bool flag2 = SendableMagic(item, source);
					bool flag3 = Sendable(item, source);
					if (!flag2 && !flag3)
					{
						continue;
					}
					foreach (Container item2 in list)
					{
						if (item.m_stack <= 0 || !source.ContainsItem(item))
						{
							break;
						}
						if ((Object)(object)item2 == (Object)null || (Object)(object)item2 == (Object)(object)exclude || !Chests.Ready(item2))
						{
							continue;
						}
						Chests.Fresh(item2);
						Inventory inventory = item2.GetInventory();
						if ((!flag2 || !HoldsMagic(inventory)) && (!flag3 || !inventory.ContainsItemByName(item.m_shared.m_name)))
						{
							continue;
						}
						flag = true;
						int num2 = MoveInto(inventory, source, item);
						if (num2 > 0)
						{
							num += num2;
							if (!list2.Contains(item2))
							{
								list2.Add(item2);
							}
						}
					}
				}
			}
			if (num > 0)
			{
				((Character)player).Message((MessageType)2, string.Format("Stored {0} item{1} in {2} chest{3}", num, (num == 1) ? "" : "s", list2.Count, (list2.Count == 1) ? "" : "s"), 0, (Sprite)null, false);
			}
			else
			{
				((Character)player).Message((MessageType)2, flag ? "The chests with these items are full" : "No chest nearby holds these items", 0, (Sprite)null, false);
			}
			try
			{
				AfterStore(list2);
			}
			catch (Exception ex)
			{
				Plugin instance = _instance;
				if (instance != null)
				{
					instance.Logger.LogWarning((object)("After Store Nearby: " + ex.Message));
				}
			}
		}

		private static int MoveInto(Inventory target, Inventory source, ItemData item)
		{
			int stack = item.m_stack;
			if (target.HaveEmptySlot())
			{
				if (target.AddItem(item))
				{
					source.RemoveItem(item);
					return stack;
				}
				source.Changed(false, false);
				return stack - item.m_stack;
			}
			int num = 0;
			while (item.m_stack > 0)
			{
				ItemData val = target.FindFreeStackItem(item.m_shared.m_name, item.m_quality, (float)item.m_worldLevel);
				if (val == null)
				{
					break;
				}
				int num2 = Mathf.Min(item.m_stack, val.m_shared.m_maxStackSize - val.m_stack);
				if (num2 <= 0)
				{
					break;
				}
				val.m_stack += num2;
				item.m_stack -= num2;
				num += num2;
			}
			if (num > 0)
			{
				if (item.m_stack <= 0)
				{
					source.RemoveItem(item);
				}
				else
				{
					source.Changed(false, false);
				}
				target.Changed(false, false);
			}
			return num;
		}

		public static bool Sendable(ItemData item, Inventory source)
		{
			if (!Movable(item, source))
			{
				return false;
			}
			string text = Kind(item);
			if (Listed(item, text, ref _keepTokens, AlwaysKeep))
			{
				return false;
			}
			if (Listed(item, text, ref _storeTokens, AlwaysStore))
			{
				return true;
			}
			switch (text)
			{
			case "materials":
			case "trophies":
			case "fish":
				return !Kept(item);
			case "food":
				if (StoreFood != null)
				{
					return StoreFood.Value;
				}
				return true;
			case "potions":
				if (StorePotions != null)
				{