Decompiled source of RustyHeathensQoL v1.0.31

plugins/RustyHeathensQoL/RustyHeathensQoL.dll

Decompiled 2 days ago
using System;
using System.Buffers.Binary;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using RustyHeathens.Automation;
using RustyHeathens.Backpacks;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Rusty Heathens QoL")]
[assembly: AssemblyDescription("Heathens' Haven quality-of-life features")]
[assembly: AssemblyCompany("RustyLaserGaming")]
[assembly: AssemblyProduct("Rusty Heathens QoL")]
[assembly: AssemblyFileVersion("1.0.31")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.31.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace RustyHeathens.QoL
{
	internal static class AchievementSupport
	{
		internal static void Install(Harmony harmony)
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			try
			{
				Type type = typeof(Game).Assembly.GetType("Achievements");
				MethodInfo methodInfo = ((type == null) ? null : type.GetMethod("IsCheatedAtAll", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null));
				if (methodInfo == null || !methodInfo.IsStatic || methodInfo.ReturnType != typeof(bool))
				{
					Warn("Achievement support skipped: this game version has no supported achievement evaluator.");
				}
				else
				{
					harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(AchievementSupport), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception ex)
			{
				Warn("Achievement support could not be installed; other QoL features remain active. " + ex.Message);
			}
		}

		internal static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			FieldInfo field = typeof(Game).GetField("isModded", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			int index = -1;
			int num = 0;
			if (field != null && field.IsStatic && field.FieldType == typeof(bool))
			{
				for (int i = 0; i < list.Count; i++)
				{
					if (list[i].opcode == OpCodes.Ldsfld && field.Equals(list[i].operand))
					{
						index = i;
						num++;
					}
				}
			}
			if (num != 1)
			{
				Warn("Achievement support skipped: expected one modded-flag check, found " + num + ". The evaluator was left unchanged by QoL.");
				return list;
			}
			list[index].opcode = OpCodes.Ldc_I4_0;
			list[index].operand = null;
			if ((Object)(object)Plugin.Instance != (Object)null)
			{
				Plugin.Instance.LogInfo("[RHQOL] Modded achievement support active. Character, item and world restrictions still apply.");
			}
			return list;
		}

		private static void Warn(string message)
		{
			if ((Object)(object)Plugin.Instance != (Object)null)
			{
				Plugin.Instance.LogWarning("[RHQOL] " + message);
			}
		}
	}
	internal static class BackpackAuthority
	{
		private sealed class DedicatedPlayerState
		{
			internal long PeerId;

			internal long PlayerId;

			internal ZDOID CharacterId = ZDOID.None;

			internal ZDOID BackpackId = ZDOID.None;

			internal int LastEmoteId = int.MinValue;

			internal float OpenAt = -1f;

			internal int OpenAttemptsRemaining;

			internal float NextMaintenance;

			internal float NextAssigned;

			internal bool Activated;
		}

		internal const string ArgusBackpackGuid = "ArgusMagnus.ServersideQoL.Backpack";

		internal const string ClientOpenRpc = "RHSQOL_BackpackOpen_v1";

		internal const string ClientAssignedRpc = "RHSQOL_BackpackAssigned_v2";

		internal const string RequestRpc = "RHSQOL_BackpackRequest_v2";

		internal const string DeathRpc = "RHSQOL_BackpackDeath_v2";

		private static readonly int MarkerKey = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack");

		private static readonly int PlayerKey = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack_Player");

		private static readonly int SlotsKey = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack_Slots");

		private static readonly int CanonicalKey = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack_Canonical");

		private static readonly int ArchivedKey = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack_Archived");

		private static readonly string[] BossKeys = new string[2] { "defeated_eikthyr", "defeated_gdking" };

		private static Container backpack;

		private static GameObject backpackObject;

		private static ZDOID backpackId = ZDOID.None;

		private static float openAt = -1f;

		private static float nextMaintenance;

		private static long lastPlayerId;

		private static long lastWorldUid;

		private static bool argusWarningLogged;

		private static readonly Dictionary<long, DedicatedPlayerState> DedicatedStates = new Dictionary<long, DedicatedPlayerState>();

		private static readonly HashSet<long> SeenDedicatedPeers = new HashSet<long>();

		private static float nextDedicatedTick;

		private static readonly Dictionary<long, ZDOID> CanonicalBackpacks = new Dictionary<long, ZDOID>();

		private static readonly HashSet<long> DuplicateWarnings = new HashSet<long>();

		private static bool globalLookupFailed;

		private static bool persistentBagFound;

		private static readonly HashSet<long> OptedOutPeers = new HashSet<long>();

		internal static bool LegacyAuthorityPresent => Chainloader.PluginInfos?.ContainsKey("com.rustylasergaming.rustyheathensserverqol") ?? false;

		internal static bool ArgusBackpackPresent
		{
			get
			{
				if (Chainloader.PluginInfos != null)
				{
					return Chainloader.PluginInfos.ContainsKey("ArgusMagnus.ServersideQoL.Backpack");
				}
				return false;
			}
		}

		private static ZNetPeer FindPeer(long sender)
		{
			if ((Object)(object)ZNet.instance != (Object)null)
			{
				foreach (ZNetPeer peer in ZNet.instance.GetPeers())
				{
					if (peer != null && peer.m_uid == sender)
					{
						return peer;
					}
				}
			}
			return null;
		}

		internal static void Clear()
		{
			//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)
			backpack = null;
			backpackObject = null;
			backpackId = ZDOID.None;
			openAt = -1f;
			nextMaintenance = 0f;
			lastPlayerId = 0L;
			lastWorldUid = 0L;
			argusWarningLogged = false;
			nextDedicatedTick = 0f;
			DedicatedStates.Clear();
			CanonicalBackpacks.Clear();
			DuplicateWarnings.Clear();
			SeenDedicatedPeers.Clear();
			OptedOutPeers.Clear();
			globalLookupFailed = false;
			persistentBagFound = false;
		}

		internal static void RegisterRpc()
		{
			ZRoutedRpc.instance.Register<string>("RHSQOL_BackpackRequest_v2", (Action<long, string>)OnClientRequest);
			ZRoutedRpc.instance.Register<ZPackage>("RHSQOL_BackpackDeath_v2", (Action<long, ZPackage>)delegate
			{
			});
		}

		private static DedicatedPlayerState StateFor(ZNetPeer peer, ZDO player)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			long num = player.GetLong(ZDOVars.s_playerID, 0L);
			if (!DedicatedStates.TryGetValue(peer.m_uid, out var value) || value.PlayerId != num)
			{
				value = new DedicatedPlayerState
				{
					PeerId = peer.m_uid,
					PlayerId = num,
					CharacterId = peer.m_characterID,
					LastEmoteId = player.GetInt(ZDOVars.s_emoteID, 0)
				};
				DedicatedStates[peer.m_uid] = value;
			}
			value.CharacterId = peer.m_characterID;
			return value;
		}

		private static void OnClientRequest(long sender, string request)
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			Plugin instance = Plugin.Instance;
			if (!ActivationAllowed(instance) || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || ZDOMan.instance == null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			ZNetPeer val = FindPeer(sender);
			if (val == null || !val.IsReady() || ((ZDOID)(ref val.m_characterID)).IsNone())
			{
				return;
			}
			if (request == "disabled")
			{
				OptedOutPeers.Add(sender);
				DedicatedStates.Remove(sender);
			}
			else if (request == "enabled")
			{
				OptedOutPeers.Remove(sender);
			}
			else
			{
				if (OptedOutPeers.Contains(sender))
				{
					return;
				}
				ZDO zDO = ZDOMan.instance.GetZDO(val.m_characterID);
				if (zDO == null || zDO.GetBool(ZDOVars.s_dead, false) || zDO.GetLong(ZDOVars.s_playerID, 0L) == 0L)
				{
					return;
				}
				bool flag = request == "open|" + instance.BackpackOpenEmoteValue;
				if (!flag && request != "resolve")
				{
					return;
				}
				DedicatedPlayerState dedicatedPlayerState = StateFor(val, zDO);
				dedicatedPlayerState.Activated = true;
				if (EnsureDedicatedBackpack(dedicatedPlayerState, zDO, instance))
				{
					ZRoutedRpc.instance.InvokeRoutedRPC(sender, "RHSQOL_BackpackAssigned_v2", new object[1] { dedicatedPlayerState.BackpackId });
					if (flag)
					{
						dedicatedPlayerState.OpenAttemptsRemaining = 6;
						dedicatedPlayerState.OpenAt = Time.realtimeSinceStartup;
						OpenDedicatedBackpack(dedicatedPlayerState, zDO, val, instance);
					}
				}
			}
		}

		internal static bool ActivationAllowed(Plugin plugin)
		{
			if ((Object)(object)plugin == (Object)null || !plugin.BackpackEnabledValue || LegacyAuthorityPresent)
			{
				return false;
			}
			if (ArgusBackpackPresent)
			{
				if (!argusWarningLogged)
				{
					argusWarningLogged = true;
					plugin.LogBackpackWarning("ArgusMagnus.ServersideQoL.Backpack is still loaded. Rusty Backpack is blocked to prevent two backpack systems from touching player storage. Remove the Argus Backpack add-on before using Rusty Backpack.");
				}
				return false;
			}
			return true;
		}

		internal static void Tick()
		{
			Plugin instance = Plugin.Instance;
			if (ActivationAllowed(instance) && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer())
			{
				TickDedicated(instance);
				if (!ZNet.instance.IsDedicated())
				{
					TickLocal(instance);
				}
			}
		}

		private static void TickLocal(Plugin plugin)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!plugin.BackpackClientEnabled)
			{
				openAt = -1f;
			}
			else
			{
				if ((Object)(object)localPlayer == (Object)null || ZDOMan.instance == null || (Object)(object)ZNetScene.instance == (Object)null || (Object)(object)ZoneSystem.instance == (Object)null)
				{
					return;
				}
				long playerID = localPlayer.GetPlayerID();
				long worldUID = ZNet.instance.GetWorldUID();
				if (playerID != lastPlayerId || worldUID != lastWorldUid)
				{
					ForgetRuntimeReference();
					lastPlayerId = playerID;
					lastWorldUid = worldUID;
				}
				if (openAt >= 0f && Time.realtimeSinceStartup >= openAt && !((Character)localPlayer).IsTeleporting())
				{
					openAt = -1f;
					if (!((Character)localPlayer).IsDead())
					{
						OpenBackpackNow(localPlayer, plugin);
					}
				}
				if (Time.realtimeSinceStartup >= nextMaintenance)
				{
					nextMaintenance = Time.realtimeSinceStartup + 1f;
					FollowPlayer(localPlayer);
					if (!((Character)localPlayer).IsTeleporting())
					{
						EnsureCapacity(localPlayer, plugin);
					}
				}
			}
		}

		private static void TickDedicated(Plugin plugin)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			if (ZDOMan.instance == null || (Object)(object)ZNetScene.instance == (Object)null || (Object)(object)ZoneSystem.instance == (Object)null || ZRoutedRpc.instance == null)
			{
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup < nextDedicatedTick)
			{
				return;
			}
			nextDedicatedTick = realtimeSinceStartup + 0.1f;
			IList<ZNetPeer> list = new List<ZNetPeer>(ZNet.instance.GetPeers());
			SeenDedicatedPeers.Clear();
			for (int i = 0; i < list.Count; i++)
			{
				ZNetPeer val = list[i];
				if (val == null || !val.IsReady() || val.m_uid == 0L || ((ZDOID)(ref val.m_characterID)).IsNone())
				{
					continue;
				}
				SeenDedicatedPeers.Add(val.m_uid);
				if (OptedOutPeers.Contains(val.m_uid))
				{
					continue;
				}
				ZDO zDO = ZDOMan.instance.GetZDO(val.m_characterID);
				if (zDO == null || !zDO.IsValid() || zDO.GetLong(ZDOVars.s_playerID, 0L) == 0L || !DedicatedStates.TryGetValue(val.m_uid, out var value) || !value.Activated || value.PlayerId != zDO.GetLong(ZDOVars.s_playerID, 0L))
				{
					continue;
				}
				value.CharacterId = val.m_characterID;
				bool flag = zDO.GetBool(ZDOVars.s_dead, false);
				int num = zDO.GetInt(ZDOVars.s_emoteID, 0);
				if (num != value.LastEmoteId)
				{
					value.LastEmoteId = num;
					string a = zDO.GetString(ZDOVars.s_emote, string.Empty);
					if (!flag && string.Equals(a, plugin.BackpackOpenEmoteValue, StringComparison.OrdinalIgnoreCase) && EnsureDedicatedBackpack(value, zDO, plugin))
					{
						value.OpenAttemptsRemaining = 6;
						value.OpenAt = realtimeSinceStartup + 0.25f;
						ZDO zDO2 = ZDOMan.instance.GetZDO(value.BackpackId);
						if (zDO2 != null)
						{
							ZDOMan.instance.ForceSendZDO(val.m_uid, zDO2.m_uid);
						}
					}
				}
				if (flag)
				{
					value.OpenAt = -1f;
					value.OpenAttemptsRemaining = 0;
					continue;
				}
				if (value.OpenAt >= 0f && realtimeSinceStartup >= value.OpenAt)
				{
					OpenDedicatedBackpack(value, zDO, val, plugin);
					value.OpenAttemptsRemaining--;
					value.OpenAt = ((value.OpenAttemptsRemaining > 0) ? (realtimeSinceStartup + 0.35f) : (-1f));
				}
				if (realtimeSinceStartup >= value.NextMaintenance)
				{
					value.NextMaintenance = realtimeSinceStartup + 1f;
					MaintainDedicatedBackpack(value, zDO, val, plugin);
				}
			}
			OptedOutPeers.RemoveWhere((long peer) => !SeenDedicatedPeers.Contains(peer));
			List<long> list2 = null;
			foreach (KeyValuePair<long, DedicatedPlayerState> dedicatedState in DedicatedStates)
			{
				if (!SeenDedicatedPeers.Contains(dedicatedState.Key))
				{
					if (list2 == null)
					{
						list2 = new List<long>();
					}
					list2.Add(dedicatedState.Key);
				}
			}
			if (list2 != null)
			{
				for (int num2 = 0; num2 < list2.Count; num2++)
				{
					DedicatedStates.Remove(list2[num2]);
				}
			}
		}

		private unsafe static bool EnsureDedicatedBackpack(DedicatedPlayerState state, ZDO playerZdo, Plugin plugin)
		{
			//IL_0015: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: 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_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: 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)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			if (CanonicalBackpacks.TryGetValue(state.PlayerId, out var value))
			{
				state.BackpackId = value;
			}
			ZDO val = (((ZDOID)(ref state.BackpackId)).IsNone() ? null : ZDOMan.instance.GetZDO(state.BackpackId));
			if (val != null && val.IsValid() && !IsDedicatedBackpackFor(val, state.PlayerId))
			{
				return false;
			}
			if (IsDedicatedBackpackFor(val, state.PlayerId))
			{
				int desiredSlots = GetDesiredSlots(plugin);
				if (val.GetInt(SlotsKey, 0) < desiredSlots)
				{
					val = ResizeDedicatedBackpack(state, playerZdo, val, desiredSlots, plugin);
				}
				return val != null;
			}
			val = FindDedicatedBackpackGlobal(state.PlayerId, plugin);
			if (val != null)
			{
				state.BackpackId = val.m_uid;
				CanonicalBackpacks[state.PlayerId] = val.m_uid;
				int desiredSlots2 = GetDesiredSlots(plugin);
				if (val.GetInt(SlotsKey, 0) < desiredSlots2)
				{
					val = ResizeDedicatedBackpack(state, playerZdo, val, desiredSlots2, plugin);
				}
				return val != null;
			}
			if (globalLookupFailed)
			{
				return false;
			}
			int desiredSlots3 = GetDesiredSlots(plugin);
			ZDO val2 = CreateDedicatedBackpackZdo(playerZdo.GetPosition() + Vector3.down * 0.6f, state.PeerId, state.PlayerId, desiredSlots3, plugin);
			if (val2 == null)
			{
				return false;
			}
			state.BackpackId = val2.m_uid;
			CanonicalBackpacks[state.PlayerId] = val2.m_uid;
			if (plugin.VerboseLoggingValue)
			{
				string[] array = new string[7] { "CREATED dedicated backpack zdo=", null, null, null, null, null, null };
				ZDOID uid = val2.m_uid;
				array[1] = ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString();
				array[2] = " slots=";
				array[3] = desiredSlots3.ToString();
				array[4] = " playerId=";
				array[5] = state.PlayerId.ToString();
				array[6] = ".";
				plugin.LogBackpackInfo(string.Concat(array));
			}
			return true;
		}

		private static bool IsDedicatedBackpackFor(ZDO zdo, long playerId)
		{
			if (zdo != null && zdo.IsValid() && zdo.GetBool(MarkerKey, false) && !zdo.GetBool(ArchivedKey, false))
			{
				return zdo.GetLong(PlayerKey, 0L) == playerId;
			}
			return false;
		}

		private unsafe static ZDO FindDedicatedBackpackGlobal(long playerId, Plugin plugin)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			globalLookupFailed = false;
			try
			{
				List<ZDOID> list = new List<ZDOID>(ZDOExtraData.GetAllZDOIDsWithHash((Type)4, PlayerKey));
				ZDO val = null;
				int num = -1;
				int num2 = 0;
				bool flag = false;
				List<ZDO> list2 = new List<ZDO>();
				for (int i = 0; i < list.Count; i++)
				{
					ZDO zDO = ZDOMan.instance.GetZDO(list[i]);
					if (!IsDedicatedBackpackFor(zDO, playerId))
					{
						continue;
					}
					num2++;
					list2.Add(zDO);
					int slots = Math.Max(1, zDO.GetInt(SlotsKey, plugin.BackpackInitialSlotsValue));
					GetStoredInventorySize(zDO, slots, out var width, out var height);
					int num3 = 0;
					try
					{
						Inventory val2 = LoadInventoryFromZdo(zDO, width, height);
						if (val2 != null)
						{
							num3 = val2.NrOfItems();
						}
					}
					catch (Exception innerException)
					{
						ZDOID uid = zDO.m_uid;
						throw new InvalidOperationException("Could not read saved backpack " + ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString() + "; recovery must not create or archive storage.", innerException);
					}
					bool flag2 = zDO.GetBool(CanonicalKey, false);
					if (val == null || (flag2 && !flag) || (flag2 == flag && (num3 > num || (num3 == num && string.CompareOrdinal(((object)Unsafe.As<ZDOID, ZDOID>(ref zDO.m_uid)/*cast due to .constrained prefix*/).ToString(), ((object)Unsafe.As<ZDOID, ZDOID>(ref val.m_uid)/*cast due to .constrained prefix*/).ToString()) < 0))))
					{
						val = zDO;
						num = num3;
						flag = flag2;
					}
				}
				if (val != null)
				{
					val.Set(CanonicalKey, true);
					foreach (ZDO item in list2)
					{
						if (!(item.m_uid == val.m_uid))
						{
							item.Set(CanonicalKey, false);
							item.Set(ArchivedKey, true);
						}
					}
				}
				if (num2 > 1 && DuplicateWarnings.Add(playerId))
				{
					plugin.LogBackpackWarning("Found " + num2 + " persistent Rusty Backpack ZDOs for playerId=" + playerId + ". The canonical-backpack recovery path preserves every other saved object and its contents.");
				}
				if (val != null && plugin.VerboseLoggingValue)
				{
					string[] array = new string[7] { "RECOVERED global dedicated backpack zdo=", null, null, null, null, null, null };
					ZDOID uid2 = val.m_uid;
					array[1] = ((object)(*(ZDOID*)(&uid2))/*cast due to .constrained prefix*/).ToString();
					array[2] = " playerId=";
					array[3] = playerId.ToString();
					array[4] = " itemStacks=";
					array[5] = num.ToString();
					array[6] = ".";
					plugin.LogBackpackInfo(string.Concat(array));
				}
				return val;
			}
			catch (Exception ex)
			{
				globalLookupFailed = true;
				plugin.LogBackpackWarning("Global backpack recovery failed for playerId=" + playerId + ": " + ex.Message);
				return null;
			}
		}

		private static ZDO CreateDedicatedBackpackZdo(Vector3 position, long peerId, long playerId, int slots, Plugin plugin)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Expected O, but got Unknown
			//IL_012c: 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)
			GameObject prefab = ZNetScene.instance.GetPrefab("piece_chest_private");
			if ((Object)(object)prefab == (Object)null)
			{
				prefab = ZNetScene.instance.GetPrefab("piece_chest_wood");
			}
			if ((Object)(object)prefab == (Object)null)
			{
				plugin.LogBackpackError("Could not find a vanilla chest prefab to host the dedicated Rusty backpack.");
				return null;
			}
			BackpackCapacityRules.GetBackpackInventorySize(slots, out var width, out var height);
			int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)prefab).name);
			ZDO val = ZDOMan.instance.CreateNewZDO(position, stableHashCode);
			if (val == null)
			{
				return null;
			}
			val.SetPrefab(stableHashCode);
			val.SetRotation(Quaternion.identity);
			val.Persistent = true;
			ZNetView component = prefab.GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null)
			{
				val.SetType(component.m_type);
			}
			val.SetDistant(true);
			val.Set(MarkerKey, true);
			val.Set(CanonicalKey, true);
			val.Set(PlayerKey, playerId);
			val.Set(SlotsKey, slots, false);
			val.Set(ZDOVars.s_addedDefaultItems, true);
			SetContainerCustomFields(val, width, height, "Rusty Backpack");
			val.Set(ZDOVars.s_items, SaveInventoryBytes(new Inventory("Rusty Backpack", (Sprite)null, width, height)));
			val.SetOwner(peerId);
			ZDOMan.instance.ForceSendZDO(peerId, val.m_uid);
			return val;
		}

		private static void SetContainerCustomFields(ZDO zdo, int width, int height, string name)
		{
			zdo.Set("HasFields", true);
			zdo.Set("HasFieldsContainer", true);
			zdo.Set("Container.m_width", width);
			zdo.Set("Container.m_height", height);
			zdo.Set("Container.m_name", name);
			zdo.Set("Container.m_checkGuardStone", false);
			zdo.Set("Container.m_autoDestroyEmpty", false);
			zdo.Set("HasFieldsPiece", true);
			zdo.Set("Piece.m_canBeRemoved", false);
		}

		private static ZDO ResizeDedicatedBackpack(DedicatedPlayerState state, ZDO playerZdo, ZDO oldZdo, int desiredSlots, Plugin plugin)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			int num = Math.Max(1, oldZdo.GetInt("Container.m_width", 8));
			int height = Math.Max(oldZdo.GetInt("Container.m_height", 1), (desiredSlots + num - 1) / num);
			oldZdo.Set(SlotsKey, desiredSlots, false);
			SetContainerCustomFields(oldZdo, num, height, "Rusty Backpack");
			ZDOMan.instance.ForceSendZDO(state.PeerId, oldZdo.m_uid);
			return oldZdo;
		}

		private static void MaintainDedicatedBackpack(DedicatedPlayerState state, ZDO playerZdo, ZNetPeer peer, Plugin plugin)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//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: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			if (!EnsureDedicatedBackpack(state, playerZdo, plugin))
			{
				return;
			}
			ZDO zDO = ZDOMan.instance.GetZDO(state.BackpackId);
			if (zDO != null)
			{
				zDO.SetDistant(true);
				Vector3 val = playerZdo.GetPosition() + Vector3.down * 0.6f;
				Vector3 val2 = zDO.GetPosition() - val;
				if (((Vector3)(ref val2)).sqrMagnitude > 2.25f)
				{
					MoveDedicatedZdo(zDO, val, peer.m_uid);
				}
				if (zDO.GetOwner() != peer.m_uid)
				{
					zDO.SetOwner(peer.m_uid);
				}
				if (Time.realtimeSinceStartup >= state.NextAssigned)
				{
					state.NextAssigned = Time.realtimeSinceStartup + 5f;
					ZDOMan.instance.ForceSendZDO(peer.m_uid, zDO.m_uid);
					ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, "RHSQOL_BackpackAssigned_v2", new object[1] { zDO.m_uid });
				}
			}
		}

		private static void MoveDedicatedZdo(ZDO zdo, Vector3 position, long peerId)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			zdo.SetPosition(position);
			ZDOMan.instance.ForceSendZDO(peerId, zdo.m_uid);
		}

		private unsafe static void OpenDedicatedBackpack(DedicatedPlayerState state, ZDO playerZdo, ZNetPeer peer, Plugin plugin)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: 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_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			if (!EnsureDedicatedBackpack(state, playerZdo, plugin))
			{
				return;
			}
			ZDO zDO = ZDOMan.instance.GetZDO(state.BackpackId);
			if (zDO != null)
			{
				zDO.SetDistant(true);
				if (zDO.GetOwner() != peer.m_uid)
				{
					zDO.SetOwner(peer.m_uid);
				}
				MoveDedicatedZdo(zDO, playerZdo.GetPosition() + Vector3.down * 0.6f, peer.m_uid);
				ZDOMan.instance.ForceSendZDO(peer.m_uid, zDO.m_uid);
				ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, "RHSQOL_BackpackOpen_v1", new object[1] { zDO.m_uid });
				if (plugin.VerboseLoggingValue)
				{
					string[] array = new string[7] { "OPEN-SENT dedicated backpack zdo=", null, null, null, null, null, null };
					ZDOID uid = zDO.m_uid;
					array[1] = ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString();
					array[2] = " player=";
					array[3] = peer.m_playerName;
					array[4] = " attemptsLeft=";
					array[5] = state.OpenAttemptsRemaining.ToString();
					array[6] = ".";
					plugin.LogBackpackInfo(string.Concat(array));
				}
			}
		}

		private static void GetStoredInventorySize(ZDO zdo, int slots, out int width, out int height)
		{
			BackpackCapacityRules.GetBackpackInventorySize(slots, out width, out height);
			width = Math.Max(1, zdo.GetInt("Container.m_width", width));
			height = Math.Max(1, zdo.GetInt("Container.m_height", height));
		}

		private static Inventory LoadInventoryFromZdo(ZDO zdo, int width, int height)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			Inventory val = new Inventory("Rusty Backpack", (Sprite)null, width, height);
			byte[] byteArray = zdo.GetByteArray(ZDOVars.s_items, (byte[])null);
			if (byteArray != null && byteArray.Length != 0)
			{
				ZPackage val2 = new ZPackage();
				val2.Load(byteArray);
				val.Load(val2);
			}
			return val;
		}

		private static byte[] SaveInventoryBytes(Inventory inventory)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			inventory.Save(val);
			return val.GetArray();
		}

		internal static void QueueLocalOpen(Player player, string emote)
		{
			Plugin instance = Plugin.Instance;
			if ((Object)(object)player != (Object)null && (Object)(object)player == (Object)(object)Player.m_localPlayer && !((Character)player).IsDead() && ActivationAllowed(instance) && instance.BackpackClientEnabled && !((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsDedicated() && ZNet.instance.IsServer())
			{
				string backpackOpenEmoteValue = instance.BackpackOpenEmoteValue;
				if (string.Equals(emote ?? string.Empty, backpackOpenEmoteValue ?? "wave", StringComparison.OrdinalIgnoreCase))
				{
					openAt = Time.realtimeSinceStartup + 0.15f;
				}
			}
		}

		private unsafe static void OpenBackpackNow(Player player, Plugin plugin)
		{
			//IL_009d: 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)
			try
			{
				if ((Object)(object)InventoryGui.instance == (Object)null || !EnsureBackpack(player, plugin) || (Object)(object)backpack == (Object)null)
				{
					((Character)player).Message((MessageType)2, "Rusty Backpack could not find or load its saved container. Check the BepInEx log.", 0, (Sprite)null, false);
					return;
				}
				BackpackTravel.ClearStaleUse(backpack);
				if (!BackpackOpenSafety.TryLoad(backpack))
				{
					((Character)player).Message((MessageType)2, "Rusty Backpack stayed closed to protect saved items. Check the BepInEx log.", 0, (Sprite)null, false);
					return;
				}
				FollowPlayer(player);
				BackpackClient.Register(backpack);
				backpack.SetInUse(true);
				InventoryGui.instance.Show(backpack, 1);
				string[] obj = new string[5] { "Opened solo backpack ", null, null, null, null };
				ZDOID val = backpackId;
				obj[1] = ((object)(*(ZDOID*)(&val))/*cast due to .constrained prefix*/).ToString();
				obj[2] = " with ";
				obj[3] = backpack.GetInventory().NrOfItems().ToString();
				obj[4] = " stacks.";
				plugin.LogBackpackInfo(string.Concat(obj));
			}
			catch (Exception ex)
			{
				plugin.LogBackpackError("Open failed: " + ex);
				((Character)player).Message((MessageType)2, "Rusty Backpack could not open. Check the BepInEx log.", 0, (Sprite)null, false);
			}
		}

		private static bool EnsureBackpack(Player player, Plugin plugin)
		{
			if ((Object)(object)backpackObject != (Object)null && (Object)(object)backpack != (Object)null)
			{
				return true;
			}
			long playerID = player.GetPlayerID();
			GameObject val = FindExistingBackpack(player, playerID, plugin);
			if ((Object)(object)val != (Object)null)
			{
				BindRuntimeBackpack(val);
				EnsureCapacity(player, plugin);
				return (Object)(object)backpack != (Object)null;
			}
			if (globalLookupFailed || persistentBagFound)
			{
				return false;
			}
			int desiredSlots = GetDesiredSlots(plugin);
			GameObject val2 = CreateHiddenBackpack(player, playerID, desiredSlots, plugin);
			if ((Object)(object)val2 == (Object)null)
			{
				return false;
			}
			BindRuntimeBackpack(val2);
			return (Object)(object)backpack != (Object)null;
		}

		private static GameObject FindExistingBackpack(Player player, long playerId, Plugin plugin)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			ZDO val = (((ZDOID)(ref backpackId)).IsNone() ? null : ZDOMan.instance.GetZDO(backpackId));
			if (!((ZDOID)(ref backpackId)).IsNone() && !IsDedicatedBackpackFor(val, playerId))
			{
				persistentBagFound = true;
				return null;
			}
			if (val == null)
			{
				val = FindDedicatedBackpackGlobal(playerId, plugin);
			}
			persistentBagFound = val != null;
			if (val == null)
			{
				return null;
			}
			val.SetOwner(ZDOMan.GetSessionID());
			val.SetPosition(((Component)player).transform.position + Vector3.down * 0.5f);
			return (GameObject)(((object)ZNetScene.instance.FindInstance(val.m_uid)) ?? ((object)/*isinst with value type is only supported in some contexts*/));
		}

		private unsafe static GameObject CreateHiddenBackpack(Player player, long playerId, int slots, Plugin plugin)
		{
			//IL_0112: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: 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_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			GameObject prefab = ZNetScene.instance.GetPrefab("piece_chest_private");
			if ((Object)(object)prefab == (Object)null)
			{
				prefab = ZNetScene.instance.GetPrefab("piece_chest_wood");
			}
			if ((Object)(object)prefab == (Object)null)
			{
				plugin.LogBackpackError("Could not find a vanilla chest prefab to host the Rusty backpack.");
				return null;
			}
			Container component = prefab.GetComponent<Container>();
			if ((Object)(object)component == (Object)null)
			{
				plugin.LogBackpackError("Selected vanilla chest prefab has no Container component.");
				return null;
			}
			BackpackCapacityRules.GetBackpackInventorySize(slots, out var width, out var height);
			int width2 = component.m_width;
			int height2 = component.m_height;
			string name = component.m_name;
			PrivacySetting privacy = component.m_privacy;
			bool checkGuardStone = component.m_checkGuardStone;
			bool autoDestroyEmpty = component.m_autoDestroyEmpty;
			GameObject val = null;
			try
			{
				component.m_width = width;
				component.m_height = height;
				component.m_name = "Rusty Backpack";
				component.m_privacy = (PrivacySetting)0;
				component.m_checkGuardStone = false;
				component.m_autoDestroyEmpty = false;
				Vector3 val2 = ((Component)player).transform.position + Vector3.down * 0.5f;
				val = Object.Instantiate<GameObject>(prefab, val2, Quaternion.identity);
			}
			finally
			{
				component.m_width = width2;
				component.m_height = height2;
				component.m_name = name;
				component.m_privacy = privacy;
				component.m_checkGuardStone = checkGuardStone;
				component.m_autoDestroyEmpty = autoDestroyEmpty;
			}
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			ZNetView component2 = val.GetComponent<ZNetView>();
			Container component3 = val.GetComponent<Container>();
			if ((Object)(object)component2 == (Object)null || component2.GetZDO() == null || (Object)(object)component3 == (Object)null)
			{
				plugin.LogBackpackError("Vanilla chest host did not initialize correctly.");
				Object.Destroy((Object)(object)val);
				return null;
			}
			ZDO zDO = component2.GetZDO();
			zDO.Persistent = true;
			zDO.Set(MarkerKey, true);
			zDO.Set(PlayerKey, playerId);
			zDO.Set(SlotsKey, slots, false);
			zDO.Set(CanonicalKey, true);
			zDO.Set(ZDOVars.s_addedDefaultItems, true);
			SetContainerCustomFields(zDO, width, height, "Rusty Backpack");
			BackpackHostVisibility.HideIfRustyBackpack(component2);
			if (plugin.VerboseLoggingValue)
			{
				string[] array = new string[11]
				{
					"CREATED local-test backpack zdo=", null, null, null, null, null, null, null, null, null,
					null
				};
				ZDOID uid = zDO.m_uid;
				array[1] = ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString();
				array[2] = " slots=";
				array[3] = slots.ToString();
				array[4] = " (";
				array[5] = width.ToString();
				array[6] = "x";
				array[7] = height.ToString();
				array[8] = ") player=";
				array[9] = playerId.ToString();
				array[10] = ".";
				plugin.LogBackpackInfo(string.Concat(array));
			}
			return val;
		}

		private static void BindRuntimeBackpack(GameObject obj)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			backpackObject = obj;
			backpack = (((Object)(object)obj == (Object)null) ? null : obj.GetComponent<Container>());
			ZNetView val = (((Object)(object)obj == (Object)null) ? null : obj.GetComponent<ZNetView>());
			backpackId = (((Object)(object)val != (Object)null && val.GetZDO() != null) ? val.GetZDO().m_uid : ZDOID.None);
			BackpackClient.AssignedId = backpackId;
			if ((Object)(object)backpack != (Object)null)
			{
				backpack.m_privacy = (PrivacySetting)0;
				BackpackHostVisibility.HideIfRustyBackpack(val);
			}
		}

		private static void FollowPlayer(Player player)
		{
			//IL_0009: 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)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player != (Object)null)
			{
				BackpackTravel.Move(backpackId, player.GetPlayerID(), ((Component)player).transform.position + Vector3.down * 0.5f);
			}
		}

		private static void EnsureCapacity(Player player, Plugin plugin)
		{
			if ((Object)(object)backpack == (Object)null || (Object)(object)backpackObject == (Object)null)
			{
				return;
			}
			int desiredSlots = GetDesiredSlots(plugin);
			Inventory inventory = backpack.GetInventory();
			if (inventory != null && inventory.GetWidth() * inventory.GetHeight() < desiredSlots)
			{
				ZNetView component = ((Component)backpack).GetComponent<ZNetView>();
				if ((Object)(object)component != (Object)null && component.IsValid() && component.IsOwner())
				{
					BackpackCapacity.TryGrow(backpack, component, desiredSlots);
				}
			}
		}

		private static int GetDesiredSlots(Plugin plugin)
		{
			int num = 0;
			if ((Object)(object)ZoneSystem.instance != (Object)null)
			{
				for (int i = 0; i < BossKeys.Length; i++)
				{
					try
					{
						if (ZoneSystem.instance.GetGlobalKey(BossKeys[i]))
						{
							num++;
						}
					}
					catch
					{
					}
				}
			}
			return BackpackCapacityRules.CalculateBackpackSlots(plugin.BackpackInitialSlotsValue, plugin.BackpackSlotsPerBossValue, num);
		}

		private static void ForgetRuntimeReference()
		{
			//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_001b: Unknown result type (might be due to invalid IL or missing references)
			backpack = null;
			backpackObject = null;
			backpackId = ZDOID.None;
			BackpackClient.AssignedId = ZDOID.None;
		}
	}
	internal static class BackpackCapacity
	{
		internal const int Width = 8;

		internal const int Rows = 4;

		private static readonly HashSet<Inventory> Recovery = new HashSet<Inventory>();

		private static readonly HashSet<Inventory> Notified = new HashSet<Inventory>();

		private static readonly FieldInfo WidthField = typeof(Inventory).GetField("m_width", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly MethodInfo SaveMethod = typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);

		[ThreadStatic]
		internal static int Loading;

		internal static void Clear()
		{
			Recovery.Clear();
			Notified.Clear();
			Loading = 0;
		}

		internal static bool BlockDeposit(Inventory inventory)
		{
			if (Loading == 0 && inventory != null)
			{
				if (!Recovery.Contains(inventory))
				{
					return BackpackClient.BlockUnverifiedDeposit(inventory);
				}
				return true;
			}
			return false;
		}

		internal static void TryGrow(Container container, ZNetView view, int desiredSlots)
		{
			Inventory inventory = container.GetInventory();
			int width = inventory.GetWidth();
			int height = inventory.GetHeight();
			if (width != 8 || height >= 4 || SaveMethod == null || !BackpackOpenSafety.TryLoad(container))
			{
				return;
			}
			int num = Math.Min(4, (desiredSlots + width - 1) / width);
			if (num <= height)
			{
				return;
			}
			int height2 = container.m_height;
			try
			{
				StandaloneInventory.SetRawHeight(inventory, num);
				container.m_height = num;
				SaveMethod.Invoke(container, null);
				if (!view.IsOwner())
				{
					throw new InvalidOperationException("Backpack ownership changed.");
				}
				ZDO zDO = view.GetZDO();
				zDO.Set("Container.m_width", width);
				zDO.Set("Container.m_height", num);
				zDO.Set("RHSQOL_RustyBackpack_Slots", desiredSlots);
			}
			catch (Exception ex)
			{
				StandaloneInventory.SetRawHeight(inventory, height);
				container.m_height = height2;
				Plugin.Instance?.LogWarning("[RHQOL Backpack] Capacity increase deferred: " + ex.Message);
			}
		}

		internal static void Apply(Container container, ZNetView view)
		{
			Inventory inventory = container.GetInventory();
			int width = inventory.GetWidth();
			int height = inventory.GetHeight();
			if (width <= 8 && height <= 4)
			{
				Recovery.Remove(inventory);
				return;
			}
			Recovery.Add(inventory);
			bool flag = true;
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (allItem != null && !BackpackCapacityRules.Fits(allItem.m_gridPos.x, allItem.m_gridPos.y))
				{
					flag = false;
					break;
				}
			}
			if (!flag)
			{
				if ((Object)(object)Player.m_localPlayer != (Object)null && view.IsOwner() && Notified.Add(inventory))
				{
					((Character)Player.m_localPlayer).Message((MessageType)2, "Backpack limit: 4 rows. Remove items from the extra rows, then reopen. Deposits are paused until recovery is complete.", 0, (Sprite)null, false);
				}
			}
			else
			{
				if (!view.IsOwner() || WidthField == null || SaveMethod == null)
				{
					return;
				}
				int num = Math.Min(8, width);
				int num2 = Math.Min(4, height);
				int width2 = container.m_width;
				int height2 = container.m_height;
				try
				{
					WidthField.SetValue(inventory, num);
					StandaloneInventory.SetRawHeight(inventory, num2);
					container.m_width = num;
					container.m_height = num2;
					if (inventory.GetWidth() != num || inventory.GetHeight() != num2)
					{
						throw new InvalidOperationException("Inventory dimensions could not be changed.");
					}
					SaveMethod.Invoke(container, null);
					if (!view.IsOwner())
					{
						throw new InvalidOperationException("Backpack ownership changed.");
					}
					ZDO zDO = view.GetZDO();
					zDO.Set("Container.m_width", num);
					zDO.Set("Container.m_height", num2);
					zDO.Set("RHSQOL_RustyBackpack_Slots", num * num2);
					Recovery.Remove(inventory);
				}
				catch (Exception ex)
				{
					WidthField.SetValue(inventory, width);
					StandaloneInventory.SetRawHeight(inventory, height);
					container.m_width = width2;
					container.m_height = height2;
					if ((Object)(object)Plugin.Instance != (Object)null)
					{
						Plugin.Instance.LogWarning("[RHQOL Backpack] Capacity recovery deferred; items retained: " + ex.Message);
					}
				}
			}
		}
	}
	internal static class BackpackCapacityRules
	{
		internal static bool Fits(int x, int y)
		{
			if (x >= 0 && x < 8 && y >= 0)
			{
				return y < 4;
			}
			return false;
		}

		internal static int CalculateBackpackSlots(int initial, int additional, int bosses)
		{
			long val = Math.Max(1, initial) + (long)Math.Max(0, additional) * (long)Math.Min(2, Math.Max(0, bosses));
			return (int)Math.Min(32L, val);
		}

		internal static void GetBackpackInventorySize(int slots, out int width, out int height)
		{
			width = 8;
			height = (Math.Max(1, Math.Min(32, slots)) + width - 1) / width;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "Show")]
	internal static class BackpackCapacityShowPatch
	{
		private static bool Prefix(Container __0)
		{
			if (BackpackOpenSafety.IsBackpack(__0) && !BackpackOpenSafety.TryLoad(__0))
			{
				return false;
			}
			BackpackClient.Register(__0);
			return true;
		}
	}
	internal static class BackpackClient
	{
		internal const string RequestRpc = "RHSQOL_BackpackRequest_v2";

		internal const string AssignedRpc = "RHSQOL_BackpackAssigned_v2";

		internal const string DeathRpc = "RHSQOL_BackpackDeath_v2";

		private static readonly int Marker = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack");

		private static readonly int PlayerKey = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack_Player");

		private static readonly Dictionary<Inventory, Container> Hosts = new Dictionary<Inventory, Container>();

		private static readonly HashSet<Inventory> Weightless = new HashSet<Inventory>();

		internal static ZDOID AssignedId = ZDOID.None;

		internal static void Clear()
		{
			//IL_001e: 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)
			Weightless.Clear();
			Hosts.Clear();
			BackpackOpenSafety.Clear();
			BackpackCapacity.Clear();
			AssignedId = ZDOID.None;
			BackpackDeathCapture.Clear();
		}

		internal static bool BlockUnverifiedDeposit(Inventory inventory)
		{
			if (inventory != null && Hosts.TryGetValue(inventory, out var value))
			{
				return !BackpackOpenSafety.IsWritable(value);
			}
			return false;
		}

		internal static bool IsWeightless(Inventory inv)
		{
			if (inv != null)
			{
				return Weightless.Contains(inv);
			}
			return false;
		}

		internal static bool IsGrave(Container container)
		{
			if ((Object)(object)container == (Object)null)
			{
				return false;
			}
			ZNetView component = ((Component)container).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return false;
			}
			ZDO zDO = component.GetZDO();
			if (!zDO.GetBool("RHSQOL_RustyBackpack_Grave", false))
			{
				return zDO.GetString(ZDOVars.s_ownerName, "").EndsWith(" - Rusty Backpack", StringComparison.Ordinal);
			}
			return true;
		}

		internal static void Register(Container container)
		{
			if ((Object)(object)container == (Object)null || container.GetInventory() == null)
			{
				return;
			}
			ZNetView component = ((Component)container).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return;
			}
			ZDO zDO = component.GetZDO();
			if (!zDO.GetBool(Marker, false) && !IsGrave(container))
			{
				return;
			}
			Weightless.Add(container.GetInventory());
			if (zDO.GetBool(Marker, false))
			{
				int height = (container.m_height = Math.Max(container.GetInventory().GetHeight(), zDO.GetInt("Container.m_height", container.m_height)));
				StandaloneInventory.SetRawHeight(container.GetInventory(), height);
				Hosts[container.GetInventory()] = container;
				if (BackpackOpenSafety.IsWritable(container))
				{
					BackpackCapacity.Apply(container, component);
				}
				if ((Object)(object)Player.m_localPlayer != (Object)null && zDO.GetLong(PlayerKey, 0L) == Player.m_localPlayer.GetPlayerID())
				{
					StandaloneInventoryUI.RegisterRustyBackpack(container.GetInventory());
				}
			}
		}

		internal static Container OwnedBackpack()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if (((ZDOID)(ref AssignedId)).IsNone() || (Object)(object)ZNetScene.instance == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return null;
			}
			GameObject val = ZNetScene.instance.FindInstance(AssignedId);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			ZNetView component = val.GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner())
			{
				return null;
			}
			ZDO zDO = component.GetZDO();
			if (!zDO.GetBool(Marker, false) || zDO.GetLong(PlayerKey, 0L) != Player.m_localPlayer.GetPlayerID())
			{
				return null;
			}
			Container component2 = val.GetComponent<Container>();
			Register(component2);
			if (!BackpackOpenSafety.TryLoad(component2))
			{
				return null;
			}
			return component2;
		}

		private static byte[] Save(Inventory inv)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			inv.Save(val);
			return val.GetArray();
		}

		private static void Restore(Container container, byte[] bytes)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Load(bytes);
			container.GetInventory().Load(val);
			Persist(container);
		}

		private static void Persist(Container container)
		{
			ZNetView component = ((Component)container).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsOwner())
			{
				throw new InvalidOperationException("Backpack/grave ownership changed.");
			}
			AccessTools.Method(typeof(Container), "Save", Type.EmptyTypes, (Type[])null).Invoke(container, null);
			byte[] byteArray = component.GetZDO().GetByteArray(ZDOVars.s_items, (byte[])null);
			byte[] array = Save(container.GetInventory());
			if (byteArray == null || byteArray.Length != array.Length)
			{
				throw new InvalidOperationException("Recovery save failed.");
			}
			for (int i = 0; i < array.Length; i++)
			{
				if (byteArray[i] != array[i])
				{
					throw new InvalidOperationException("Recovery save failed.");
				}
			}
		}

		internal static bool Recover(Container grave)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null))
			{
				Plugin instance = Plugin.Instance;
				if (instance != null && instance.BackpackClientEnabled && !((Object)(object)grave == (Object)null) && IsGrave(grave))
				{
					ZNetView component = ((Component)grave).GetComponent<ZNetView>();
					if ((Object)(object)component == (Object)null || !component.IsValid() || component.GetZDO().GetLong(ZDOVars.s_owner, 0L) != localPlayer.GetPlayerID())
					{
						return false;
					}
					Container target = OwnedBackpack();
					if ((Object)(object)target == (Object)null || !component.IsOwner())
					{
						if ((Object)(object)Plugin.Instance != (Object)null)
						{
							Plugin.Instance.RequestBackpack(open: false, "wave");
						}
						((Character)localPlayer).Message((MessageType)2, "Open your Rusty Backpack with Wave, then use Take All on the backpack grave.", 0, (Sprite)null, false);
						return true;
					}
					Inventory src = grave.GetInventory();
					Inventory dst = target.GetInventory();
					List<ItemData> list = new List<ItemData>(src.GetAllItems());
					int num = 0;
					try
					{
						foreach (ItemData item in list)
						{
							if (item != null && dst.CanAddItem(item, item.m_stack))
							{
								byte[] beforeSrc = Save(src);
								byte[] beforeDst = Save(dst);
								int amount = item.m_stack;
								string name = item.m_shared.m_name;
								int sourceCount = src.CountItems(name, -1, true);
								int destCount = dst.CountItems(name, -1, true);
								if (TransferSafety.Commit(delegate
								{
									if (!dst.AddItem(item.Clone()))
									{
										throw new InvalidOperationException("Backpack is full.");
									}
									Persist(target);
								}, () => dst.CountItems(name, -1, true) == destCount + amount, delegate
								{
									if (!src.RemoveItem(item))
									{
										throw new InvalidOperationException("Grave changed.");
									}
									Persist(grave);
								}, () => src.CountItems(name, -1, true) == sourceCount - amount, delegate
								{
									Restore(target, beforeDst);
								}, delegate
								{
									Restore(grave, beforeSrc);
								}))
								{
									num++;
								}
							}
						}
					}
					catch (Exception ex)
					{
						if ((Object)(object)Plugin.Instance != (Object)null)
						{
							Plugin.Instance.LogWarning("[RHQOL Backpack] Recovery stopped: " + ex);
						}
						((Character)localPlayer).Message((MessageType)2, "Backpack recovery stopped. Check the log before retrying.", 0, (Sprite)null, false);
						return true;
					}
					((Character)localPlayer).Message((MessageType)2, num + " stack(s) returned to Rusty Backpack." + ((src.NrOfItems() > 0) ? " Remaining items stay in the grave until there is space." : ""), 0, (Sprite)null, false);
					if (src.NrOfItems() == 0)
					{
						TombStone component2 = ((Component)grave).GetComponent<TombStone>();
						if ((Object)(object)component2 != (Object)null)
						{
							try
							{
								AccessTools.Method(typeof(TombStone), "OnTakeAllSuccess", (Type[])null, (Type[])null).Invoke(component2, null);
							}
							catch
							{
							}
						}
					}
					return true;
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(TombStone), "Setup")]
	internal static class BackpackDeathAnchorSetupPatch
	{
		private static void Postfix(TombStone __instance, long ownerUID)
		{
			BackpackDeathCapture.RecordGrave(__instance, ownerUID);
		}
	}
	internal static class BackpackDeathCapture
	{
		internal sealed class Snapshot
		{
			internal ZDOID Backpack;

			internal ZDOID Character;

			internal long PlayerId;

			internal byte[] Items;

			internal BackpackDeathLocation Location;
		}

		private static Snapshot active;

		internal static void Clear()
		{
			active = null;
		}

		internal static Snapshot Begin(Player player)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			active = null;
			if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || (Object)(object)Plugin.Instance == (Object)null)
			{
				return null;
			}
			ZNetView component = ((Component)player).GetComponent<ZNetView>();
			Container val = BackpackClient.OwnedBackpack();
			if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner() || (Object)(object)val == (Object)null)
			{
				return null;
			}
			ZPackage val2 = new ZPackage();
			val.GetInventory().Save(val2);
			Vector3 centerPoint = ((Character)player).GetCenterPoint();
			active = new Snapshot
			{
				Backpack = BackpackClient.AssignedId,
				Character = component.GetZDO().m_uid,
				PlayerId = player.GetPlayerID(),
				Items = val2.GetArray(),
				Location = new BackpackDeathLocation
				{
					DeathPoint = centerPoint,
					GravePoint = centerPoint
				}
			};
			return active;
		}

		internal static void RecordGrave(TombStone grave, long owner)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: 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)
			if (active == null || (Object)(object)grave == (Object)null || owner != active.PlayerId)
			{
				return;
			}
			ZNetView component = ((Component)grave).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid() || !BackpackDeathPlacement.IsInventoryGrave(component.GetZDO(), owner))
			{
				return;
			}
			Vector3 position = ((Component)grave).transform.position;
			if (BackpackDeathPlacement.Finite(position))
			{
				Vector3 val = position - active.Location.DeathPoint;
				if (!(((Vector3)(ref val)).sqrMagnitude > 16f))
				{
					active.Location.GraveId = component.GetZDO().m_uid;
					active.Location.GravePoint = position;
				}
			}
		}

		internal static void Finish(Snapshot snapshot)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			Clear();
			if (snapshot != null && !((Object)(object)Plugin.Instance == (Object)null))
			{
				ZPackage val = new ZPackage();
				val.Write(snapshot.Backpack);
				val.Write(snapshot.Items);
				BackpackDeathPlacement.Write(val, snapshot.Character, snapshot.Location);
				Plugin.Instance.SendToServer("RHSQOL_BackpackDeath_v2", val);
			}
		}
	}
	[HarmonyPatch(typeof(Player), "OnDeath")]
	internal static class BackpackDeathFlushPatch
	{
		private static void Prefix(Player __instance, ref BackpackDeathCapture.Snapshot __state)
		{
			try
			{
				__state = BackpackDeathCapture.Begin(__instance);
			}
			catch (Exception ex)
			{
				if ((Object)(object)Plugin.Instance != (Object)null)
				{
					Plugin.Instance.LogWarning("[RHQOL Backpack] Death snapshot: " + ex.Message);
				}
			}
		}

		private static void Postfix(BackpackDeathCapture.Snapshot __state)
		{
			try
			{
				BackpackDeathCapture.Finish(__state);
			}
			catch (Exception ex)
			{
				if ((Object)(object)Plugin.Instance != (Object)null)
				{
					Plugin.Instance.LogWarning("[RHQOL Backpack] Death report: " + ex.Message);
				}
			}
		}

		private static void Finalizer()
		{
			BackpackDeathCapture.Clear();
		}
	}
	internal sealed class BackpackGraveAnchor : MonoBehaviour
	{
		private ZNetView view;

		private Rigidbody body;

		private bool pinned;

		private bool wasKinematic;

		private void Awake()
		{
			view = ((Component)this).GetComponent<ZNetView>();
			body = ((Component)this).GetComponent<Rigidbody>();
		}

		private void ReleaseBody()
		{
			if (pinned && (Object)(object)body != (Object)null)
			{
				body.isKinematic = wasKinematic;
			}
			pinned = false;
		}

		private void OnDisable()
		{
			ReleaseBody();
		}

		internal void Follow()
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: 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_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: 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)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: 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_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: 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)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)view == (Object)null || !view.IsValid() || !view.IsOwner() || ZDOMan.instance == null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				ReleaseBody();
				return;
			}
			ZDO zDO = view.GetZDO();
			if (!zDO.GetBool("RHSQOL_RustyBackpack_Grave", false))
			{
				ReleaseBody();
				return;
			}
			ZDOID zDOID = zDO.GetZDOID("RHSQOL_RustyBackpack_DeathAnchor");
			ZDO val = (((ZDOID)(ref zDOID)).IsNone() ? null : ZDOMan.instance.GetZDO(zDOID));
			if (!BackpackDeathPlacement.IsInventoryGrave(val, zDO.GetLong(ZDOVars.s_owner, 0L)))
			{
				ReleaseBody();
				return;
			}
			GameObject val2 = ZNetScene.instance.FindInstance(zDOID);
			Vector3 point = (((Object)(object)val2 == (Object)null) ? val.GetPosition() : val2.transform.position);
			if (!BackpackDeathPlacement.Finite(point))
			{
				ReleaseBody();
				return;
			}
			Vector3 val3 = BackpackDeathPlacement.Beside(point);
			if ((Object)(object)ZoneSystem.instance != (Object)null)
			{
				val3.y = Mathf.Max(val3.y, ZoneSystem.instance.GetGroundHeight(val3) + 0.5f);
			}
			if (!BackpackDeathPlacement.Finite(val3))
			{
				ReleaseBody();
				return;
			}
			Vector3 val4;
			if ((Object)(object)body != (Object)null)
			{
				if (!pinned)
				{
					wasKinematic = body.isKinematic;
					if (!wasKinematic)
					{
						body.linearVelocity = Vector3.zero;
						body.angularVelocity = Vector3.zero;
					}
					body.isKinematic = true;
					pinned = true;
				}
				val4 = body.position - val3;
				if (((Vector3)(ref val4)).sqrMagnitude > 0.0001f)
				{
					body.position = val3;
				}
			}
			val4 = ((Component)this).transform.position - val3;
			if (((Vector3)(ref val4)).sqrMagnitude > 0.0001f)
			{
				((Component)this).transform.position = val3;
			}
			val4 = zDO.GetPosition() - val3;
			if (!(((Vector3)(ref val4)).sqrMagnitude > 0.0001f))
			{
				val4 = zDO.GetVec3(ZDOVars.s_spawnPoint, val3 + Vector3.up) - val3;
				if (!(((Vector3)(ref val4)).sqrMagnitude > 0.0001f))
				{
					return;
				}
			}
			zDO.SetPosition(val3);
			zDO.Set(ZDOVars.s_spawnPoint, val3);
		}

		private void FixedUpdate()
		{
			Follow();
		}
	}
	[HarmonyPatch(typeof(TombStone), "Awake")]
	internal static class BackpackGraveAnchorAwakePatch
	{
		private static void Postfix(TombStone __instance)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.IsValid() && component.GetZDO().GetBool("RHSQOL_RustyBackpack_Grave", false))
			{
				ZDOID zDOID = component.GetZDO().GetZDOID("RHSQOL_RustyBackpack_DeathAnchor");
				if (!((ZDOID)(ref zDOID)).IsNone() && (Object)(object)((Component)__instance).GetComponent<BackpackGraveAnchor>() == (Object)null)
				{
					((Component)__instance).gameObject.AddComponent<BackpackGraveAnchor>();
				}
			}
		}
	}
	[HarmonyPatch(typeof(TombStone), "EasyFitInInventory")]
	internal static class BackpackGraveAutoLootPatch
	{
		private static bool Prefix(TombStone __instance, ref bool __result)
		{
			if (!BackpackClient.IsGrave(((Component)__instance).GetComponent<Container>()))
			{
				return true;
			}
			__result = false;
			return false;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "OnTakeAll")]
	internal static class BackpackGraveTakeAllPatch
	{
		private static bool Prefix(Container ___m_currentContainer)
		{
			return !BackpackClient.Recover(___m_currentContainer);
		}
	}
	internal static class BackpackHostVisibility
	{
		private static readonly int MarkerKey = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack");

		internal static void HideIfRustyBackpack(ZNetView view)
		{
			if (!((Object)(object)view == (Object)null) && view.IsValid() && view.GetZDO().GetBool(MarkerKey, false))
			{
				GameObject gameObject = ((Component)view).gameObject;
				Renderer[] componentsInChildren = gameObject.GetComponentsInChildren<Renderer>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					componentsInChildren[i].enabled = false;
				}
				LODGroup[] componentsInChildren2 = gameObject.GetComponentsInChildren<LODGroup>(true);
				for (int i = 0; i < componentsInChildren2.Length; i++)
				{
					componentsInChildren2[i].enabled = false;
				}
				Collider[] componentsInChildren3 = gameObject.GetComponentsInChildren<Collider>(true);
				for (int i = 0; i < componentsInChildren3.Length; i++)
				{
					componentsInChildren3[i].enabled = false;
				}
				Light[] componentsInChildren4 = gameObject.GetComponentsInChildren<Light>(true);
				for (int i = 0; i < componentsInChildren4.Length; i++)
				{
					((Behaviour)componentsInChildren4[i]).enabled = false;
				}
				WearNTear component = gameObject.GetComponent<WearNTear>();
				if ((Object)(object)component != (Object)null)
				{
					((Behaviour)component).enabled = false;
				}
				Container component2 = gameObject.GetComponent<Container>();
				if (!((Object)(object)component2 == (Object)null))
				{
					component2.m_open = null;
					component2.m_closed = null;
					component2.m_name = "Rusty Backpack";
					component2.m_checkGuardStone = false;
					component2.m_autoDestroyEmpty = false;
				}
			}
		}
	}
	[HarmonyPatch(typeof(Container), "SetInUse")]
	internal static class BackpackHideBeforeUsePatch
	{
		private static void Prefix(Container __instance, bool __0, ZNetView ___m_nview)
		{
			if (__instance.IsInUse() != __0)
			{
				BackpackHostVisibility.HideIfRustyBackpack(___m_nview);
			}
		}
	}
	internal static class BackpackOpenSafety
	{
		private static readonly int Marker = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack");

		private static readonly int PlayerKey = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack_Player");

		private static readonly int Archived = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack_Archived");

		private static readonly MethodInfo Load = AccessTools.DeclaredMethod(typeof(Container), "Load", (Type[])null, (Type[])null);

		private static readonly FieldInfo Revision = AccessTools.Field(typeof(Container), "m_lastRevision");

		private static readonly FieldInfo Loading = AccessTools.Field(typeof(Container), "m_loading");

		private static readonly MethodInfo NotifyChanged = AccessTools.DeclaredMethod(typeof(Inventory), "Changed", new Type[2]
		{
			typeof(bool),
			typeof(bool)
		}, (Type[])null);

		private static readonly FieldInfo Width = AccessTools.Field(typeof(Inventory), "m_width");

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

		private static readonly HashSet<ZDOID> Reported = new HashSet<ZDOID>();

		internal static bool IsBackpack(Container bag)
		{
			if ((Object)(object)bag != (Object)null)
			{
				ZNetView component = ((Component)bag).GetComponent<ZNetView>();
				if (component != null && component.IsValid())
				{
					return component.GetZDO().GetBool(Marker, false);
				}
			}
			return false;
		}

		internal static void Clear()
		{
			Ready.Clear();
			Reported.Clear();
		}

		internal static void Forget(Container bag)
		{
			Ready.Remove(bag);
		}

		internal static bool IsWritable(Container bag)
		{
			if (!Ready.Contains(bag) || (Object)(object)bag == (Object)null)
			{
				return false;
			}
			ZNetView component = ((Component)bag).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid() && component.IsOwner() && !component.GetZDO().GetBool(Archived, false) && (Object)(object)Player.m_localPlayer != (Object)null)
			{
				return component.GetZDO().GetLong(PlayerKey, 0L) == Player.m_localPlayer.GetPlayerID();
			}
			return false;
		}

		internal unsafe static bool TryLoad(Container bag)
		{
			//IL_038d: Unknown result type (might be due to invalid IL or missing references)
			//IL_03aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_03af: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Expected O, but got Unknown
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Expected O, but got Unknown
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)bag == (Object)null || bag.GetInventory() == null)
			{
				return false;
			}
			if (!IsBackpack(bag))
			{
				return false;
			}
			if (bag.IsInUse())
			{
				return IsWritable(bag);
			}
			Ready.Remove(bag);
			ZNetView component = ((Component)bag).GetComponent<ZNetView>();
			ZDO zDO = component.GetZDO();
			if (!component.IsOwner() || zDO.GetBool(Archived, false) || (Object)(object)Player.m_localPlayer == (Object)null || zDO.GetLong(PlayerKey, 0L) != Player.m_localPlayer.GetPlayerID())
			{
				return false;
			}
			Inventory inventory = bag.GetInventory();
			byte[] byteArray = zDO.GetByteArray(ZDOVars.s_items, (byte[])null);
			try
			{
				BackpackCapacityRules.GetBackpackInventorySize(zDO.GetInt("RHSQOL_RustyBackpack_Slots", 16), out var width, out var height);
				int width2 = Math.Max(inventory.GetWidth(), zDO.GetInt("Container.m_width", width));
				int height2 = Math.Max(inventory.GetHeight(), zDO.GetInt("Container.m_height", height));
				if (width2 <= 0 || height2 <= 0 || width2 > 64 || height2 > 64 || Load == null || Revision == null || Loading == null || Width == null)
				{
					throw new InvalidOperationException("Saved backpack dimensions or load hooks are unavailable.");
				}
				if (byteArray != null)
				{
					Inventory val = new Inventory("Rusty Backpack verification", (Sprite)null, width2, height2);
					val.Load(new ZPackage(byteArray));
					List<ItemData> list = null;
					if (!MatchesSavedBytes(val, byteArray))
					{
						list = BackpackSavedItems.Read(byteArray, ref width2, ref height2);
						val.GetAllItems().Clear();
						val.GetAllItems().AddRange(list);
						if (!MatchesSavedBytes(val, byteArray))
						{
							throw new InvalidOperationException("Saved backpack could not be reconstructed without altering item data.");
						}
					}
					Width.SetValue(inventory, width2);
					StandaloneInventory.SetRawHeight(inventory, height2);
					bag.m_width = width2;
					bag.m_height = height2;
					if (!MatchesSavedBytes(inventory, byteArray) && list != null)
					{
						if (NotifyChanged == null)
						{
							throw new InvalidOperationException("Backpack inventory refresh hook is unavailable.");
						}
						Loading.SetValue(bag, true);
						try
						{
							inventory.GetAllItems().Clear();
							inventory.GetAllItems().AddRange(list);
							NotifyChanged.Invoke(inventory, new object[2] { false, false });
							Revision.SetValue(bag, zDO.DataRevision);
						}
						finally
						{
							Loading.SetValue(bag, false);
						}
						Plugin instance = Plugin.Instance;
						if (instance != null)
						{
							string[] obj = new string[5]
							{
								"Restored all ",
								list.Count.ToString(),
								" saved stacks from backpack ",
								null,
								null
							};
							ZDOID uid = zDO.m_uid;
							obj[3] = ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString();
							obj[4] = ".";
							instance.LogBackpackInfo(string.Concat(obj));
						}
					}
					else if (!MatchesSavedBytes(inventory, byteArray))
					{
						Revision.SetValue(bag, zDO.DataRevision - 1);
						try
						{
							Load.Invoke(bag, null);
						}
						finally
						{
							Loading.SetValue(bag, false);
						}
					}
					if (MatchesSavedBytes(inventory, byteArray))
					{
						byte[] byteArray2 = zDO.GetByteArray(ZDOVars.s_items, (byte[])null);
						if (byteArray2 != null && byteArray2.SequenceEqual(byteArray))
						{
							goto IL_0356;
						}
					}
					throw new InvalidOperationException("The backpack or its saved data changed during loading.");
				}
				if (inventory.NrOfItems() != 0)
				{
					throw new InvalidOperationException("The live backpack contains items without a matching save.");
				}
				goto IL_0356;
				IL_0356:
				if (!component.IsOwner())
				{
					return false;
				}
				Ready.Add(bag);
				Reported.Remove(zDO.m_uid);
				return true;
			}
			catch (Exception ex)
			{
				if (Reported.Add(zDO.m_uid))
				{
					Plugin instance2 = Plugin.Instance;
					if (instance2 != null)
					{
						ZDOID uid = zDO.m_uid;
						instance2.LogWarning("[RHQOL Backpack] Open blocked to preserve bag " + ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString() + ": " + ex.GetBaseException().Message);
					}
				}
				return false;
			}
		}

		private static bool MatchesSavedBytes(Inventory inventory, byte[] expected)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			inventory.Save(val);
			return BackpackSaveComparison.Matches(expected, val.GetArray());
		}
	}
	[HarmonyPatch(typeof(Container), "Save")]
	internal static class BackpackGuardSavePatch
	{
		private static bool Prefix(Container __instance)
		{
			if (BackpackOpenSafety.IsBackpack(__instance))
			{
				return BackpackOpenSafety.IsWritable(__instance);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Container), "SetInUse")]
	internal static class BackpackGuardUsePatch
	{
		private static bool Prefix(Container __instance, bool __0)
		{
			if (__0 && BackpackOpenSafety.IsBackpack(__instance))
			{
				return BackpackOpenSafety.TryLoad(__instance);
			}
			return true;
		}

		private static void Postfix(Container __instance, bool __0)
		{
			if (!__0)
			{
				BackpackOpenSafety.Forget(__instance);
			}
		}
	}
	[HarmonyPatch]
	internal static class BackpackRecoveryBoolAddPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			MethodInfo[] methods = typeof(Inventory).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			MethodInfo[] array = methods;
			foreach (MethodInfo methodInfo in array)
			{
				if (methodInfo.Name == "AddItem" && methodInfo.ReturnType == typeof(bool))
				{
					yield return methodInfo;
				}
			}
		}

		private static bool Prefix(Inventory __instance, ref bool __result)
		{
			if (!BackpackCapacity.BlockDeposit(__instance))
			{
				return true;
			}
			__result = false;
			return false;
		}
	}
	[HarmonyPatch]
	internal static class BackpackRecoveryCanAddPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			MethodInfo[] methods = typeof(Inventory).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			MethodInfo[] array = methods;
			foreach (MethodInfo methodInfo in array)
			{
				if (methodInfo.Name == "CanAddItem" && methodInfo.ReturnType == typeof(bool))
				{
					yield return methodInfo;
				}
			}
		}

		private static bool Prefix(Inventory __instance, ref bool __result)
		{
			if (!BackpackCapacity.BlockDeposit(__instance))
			{
				return true;
			}
			__result = false;
			return false;
		}
	}
	[HarmonyPatch]
	internal static class BackpackRecoveryItemAddPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			MethodInfo[] methods = typeof(Inventory).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			MethodInfo[] array = methods;
			foreach (MethodInfo methodInfo in array)
			{
				if (methodInfo.Name == "AddItem" && methodInfo.ReturnType == typeof(ItemData))
				{
					yield return methodInfo;
				}
			}
		}

		private static bool Prefix(Inventory __instance, ref ItemData __result)
		{
			if (!BackpackCapacity.BlockDeposit(__instance))
			{
				return true;
			}
			__result = null;
			return false;
		}
	}
	[HarmonyPatch]
	internal static class BackpackRecoveryLoadPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			MethodInfo[] methods = typeof(Inventory).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			MethodInfo[] array = methods;
			foreach (MethodInfo methodInfo in array)
			{
				if (methodInfo.Name == "Load")
				{
					yield return methodInfo;
				}
			}
		}

		[HarmonyPriority(800)]
		private static void Prefix(out int __state)
		{
			__state = BackpackCapacity.Loading;
			BackpackCapacity.Loading++;
		}

		private static void Finalizer(int __state)
		{
			BackpackCapacity.Loading = __state;
		}
	}
	internal static class BackpackSaveComparison
	{
		internal const int CurrentFormat = 110;

		private const int HeaderSize = 6;

		internal static bool Matches(byte[] expected, byte[] actual)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			if (expected.Length != actual.Length)
			{
				return false;
			}
			if (expected.AsSpan().SequenceEqual(actual))
			{
				return true;
			}
			if (expected.Length < 6 || !expected.AsSpan(0, 6).SequenceEqual(actual.AsSpan(0, 6)))
			{
				return false;
			}
			ZPackage val = new ZPackage(expected);
			if (val.ReadInt() != 110)
			{
				return false;
			}
			int num = val.ReadUShort();
			for (int i = 0; i < num; i++)
			{
				int pos = val.GetPos();
				int num2 = val.ReadInt();
				int num3 = BinaryPrimitives.ReadInt32LittleEndian(actual.AsSpan(pos, 4));
				if (num3 != num2 && (num2 < 0 || Math.Abs((long)num3 - (long)num2) > 1 || num3 != (int)((float)num2 * 0.01f * 100f)))
				{
					return false;
				}
				val.SetPos(pos);
				int item = ItemData.Load(val, (Item)110).Item1;
				int num4 = pos + 4;
				int length = val.GetPos() - num4;
				if (item == 0 || !expected.AsSpan(num4, length).SequenceEqual(actual.AsSpan(num4, length)))
				{
					return false;
				}
			}
			return val.GetPos() == expected.Length;
		}
	}
	internal static class BackpackSavedItems
	{
		internal static List<ItemData> Read(byte[] data, ref int width, ref int height)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			ZPackage val = new ZPackage(data);
			int num = val.ReadInt();
			if (num != 110)
			{
				throw new InvalidOperationException("Saved inventory format " + num + " did not round-trip through Valheim's inventory loader.");
			}
			int num2 = val.ReadUShort();
			if (num2 > 4096)
			{
				throw new InvalidOperationException("Saved backpack item count exceeds its supported capacity.");
			}
			List<ItemData> list = new List<ItemData>(num2);
			HashSet<(int, int)> hashSet = new HashSet<(int, int)>();
			for (int i = 0; i < num2; i++)
			{
				ValueTuple<int, ItemData> valueTuple = ItemData.Load(val, (Item)num);
				int item = valueTuple.Item1;
				ItemData item2 = valueTuple.Item2;
				ObjectDB instance = ObjectDB.instance;
				GameObject val2 = ((instance != null) ? instance.GetItemPrefab(item) : null);
				SharedData val3 = ((val2 == null) ? null : val2.GetComponent<ItemDrop>()?.m_itemData?.m_shared);
				if (val3 == null)
				{
					throw new InvalidOperationException("Missing item prefab " + item + " at saved stack " + (i + 1) + " of " + num2 + ".");
				}
				(int, int) tuple = (item2.m_gridPos.x, item2.m_gridPos.y);
				if (tuple.Item1 < 0 || tuple.Item1 >= 64 || tuple.Item2 < 0 || tuple.Item2 >= 64 || !hashSet.Add(tuple))
				{
					(int, int) tuple2 = tuple;
					throw new InvalidOperationException("Saved backpack contains an invalid or duplicate slot at " + tuple2.ToString() + ".");
				}
				if (item2.m_stack <= 0)
				{
					throw new InvalidOperationException("Saved backpack contains an invalid quantity for " + ((Object)val2).name + ".");
				}
				item2.m_dropPrefab = val2;
				item2.m_shared = val3;
				list.Add(item2);
				width = Math.Max(width, tuple.Item1 + 1);
				height = Math.Max(height, tuple.Item2 + 1);
			}
			if (val.GetPos() != data.Length)
			{
				throw new InvalidOperationException("Saved backpack has unrecognized trailing data.");
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(Inventory), "IsTeleportable")]
	internal static class BackpackTeleportCargoPatch
	{
		private static void Postfix(Inventory __instance, bool __0, ref bool __result)
		{
			Player localPlayer = Player.m_localPlayer;
			if (__result && !((Object)(object)localPlayer == (Object)null) && __instance == ((Humanoid)localPlayer).GetInventory())
			{
				Container val = BackpackClient.OwnedBackpack();
				if ((Object)(object)val != (Object)null && !val.GetInventory().IsTeleportable(__0))
				{
					__result = false;
				}
			}
		}
	}
	internal static class BackpackTravel
	{
		private static readonly int Marker = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack");

		private static readonly int PlayerKey = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack_Player");

		private static readonly int Archived = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack_Archived");

		private static readonly FieldRef<InventoryGui, Container> OpenContainer = AccessTools.FieldRefAccess<InventoryGui, Container>("m_currentContainer");

		internal static void ClearStaleUse(Container bag)
		{
			if (BackpackOpenSafety.IsBackpack(bag) && bag.IsInUse() && !BackpackOpenSafety.IsWritable(bag) && !IsOpen(bag))
			{
				bag.SetInUse(false);
			}
		}

		private static bool IsOpen(Container bag)
		{
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)instance != (Object)null)
			{
				return (Object)(object)OpenContainer.Invoke(instance) == (Object)(object)bag;
			}
			return false;
		}

		internal static void CloseOpenBackpack()
		{
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)instance != (Object)null && BackpackOpenSafety.IsBackpack(OpenContainer.Invoke(instance)))
			{
				instance.Hide();
			}
		}

		internal static void MoveAssigned(Player player)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)player == (Object)null) && !((Object)(object)player != (Object)(object)Player.m_localPlayer))
			{
				Plugin instance = Plugin.Instance;
				if (instance != null && instance.BackpackClientEnabled)
				{
					float num = (((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) ? 0.5f : 0.6f);
					Move(BackpackClient.AssignedId, player.GetPlayerID(), ((Component)player).transform.position + Vector3.down * num);
				}
			}
		}

		internal static void Move(ZDOID id, long playerId, Vector3 position)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			if (((ZDOID)(ref id)).IsNone() || ZDOMan.instance == null)
			{
				return;
			}
			ZDO zDO = ZDOMan.instance.GetZDO(id);
			if (zDO == null || !zDO.IsValid() || !zDO.IsOwner() || !zDO.Persistent || !zDO.GetBool(Marker, false) || zDO.GetBool(Archived, false) || zDO.GetLong(PlayerKey, 0L) != playerId)
			{
				return;
			}
			Vector3 val = zDO.GetPosition() - position;
			if (((Vector3)(ref val)).sqrMagnitude > 2.25f)
			{
				zDO.SetPosition(position);
			}
			ZNetScene instance = ZNetScene.instance;
			GameObject val2 = ((instance != null) ? instance.FindInstance(id) : null);
			if ((Object)(object)val2 != (Object)null)
			{
				val = val2.transform.position - position;
				if (((Vector3)(ref val)).sqrMagnitude > 0.0004f)
				{
					val2.transform.position = position;
				}
			}
		}
	}
	[HarmonyPatch(typeof(Player), "TeleportTo")]
	internal static class BackpackPortalBeginPatch
	{
		private static void Postfix(Player __instance, bool __result)
		{
			if (__result && (Object)(object)__instance == (Object)(object)Player.m_localPlayer)
			{
				BackpackTravel.CloseOpenBackpack();
			}
		}
	}
	[HarmonyPatch(typeof(Player), "UpdateTeleport")]
	internal static class BackpackPortalArrivalPatch
	{
		private static void Prefix(Player __instance, out bool __state)
		{
			__state = (Object)(object)__instance == (Object)(object)Player.m_localPlayer && ((Character)__instance).IsTeleporting();
		}

		private static void Postfix(Player __instance, bool __state)
		{
			if (__state)
			{
				BackpackTravel.MoveAssigned(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Container), "Awake")]
	internal static class BackpackWeightRegistrationPatch
	{
		private static void Postfix(Container __instance)
		{
			BackpackClient.Register(__instance);
		}
	}
	internal static class CharacterPreview
	{
		private static GameObject renderObject;

		private static RawImage rawImage;

		private static GameObject cameraObject;

		private static Camera previewCamera;

		private static RenderTexture renderTexture;

		private static GameObject lightObjectA;

		private static GameObject lightObjectB;

		private static GameObject snapshotRoot;

		private static readonly List<Mesh> ownedMeshes = new List<Mesh>();

		private const int PreviewLayer = 31;

		private static readonly Vector3 PreviewBase = new Vector3(0f, -1000f, 0f);

		private static bool dirty = true;

		private static float nextRefresh;

		private const float PreviewTextureAspect = 0.8f;

		internal static void MarkDirty()
		{
			dirty = true;
		}

		internal static void Show()
		{
			if (StandaloneInventory.Active)
			{
				StandaloneInventoryUI.Show();
				if (EnsureRender())
				{
					renderObject.SetActive(true);
					dirty = true;
					RefreshNow();
				}
			}
		}

		internal static void Hide()
		{
			StandaloneInventoryUI.Hide();
			if ((Object)(object)renderObject != (Object)null)
			{
				renderObject.SetActive(false);
			}
			if ((Object)(object)previewCamera != (Object)null)
			{
				((Behaviour)previewCamera).enabled = false;
			}
		}

		internal static void Tick()
		{
			if (StandaloneInventory.Active && dirty && !((Object)(object)InventoryGui.instance == (Object)null) && InventoryGui.IsVisible() && !(Time.unscaledTime < nextRefresh))
			{
				nextRefresh = Time.unscaledTime + 0.25f;
				RefreshNow();
			}
		}

		internal static void DestroyAll()
		{
			DestroySnapshot();
			if ((Object)(object)cameraObject != (Object)null)
			{
				Object.Destroy((Object)(object)cameraObject);
			}
			if ((Object)(object)lightObjectA != (Object)null)
			{
				Object.Destroy((Object)(object)lightObjectA);
			}
			if ((Object)(object)lightObjectB != (Object)null)
			{
				Object.Destroy((Object)(object)lightObjectB);
			}
			cameraObject = null;
			lightObjectA = null;
			lightObjectB = null;
			previewCamera = null;
			if ((Object)(object)renderTexture != (Object)null)
			{
				renderTexture.Release();
				Object.Destroy((Object)(object)renderTexture);
				renderTexture = null;
			}
			if ((Object)(object)renderObject != (Object)null)
			{
				Object.Destroy((Object)(object)renderObject);
			}
			renderObject = null;
			rawImage = null;
			dirty = true;
			StandaloneInventoryUI.DestroyAll();
		}

		private static bool EnsureRender()
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: 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_00e3: 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_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Expected O, but got Unknown
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			RectTransform previewRoot = StandaloneInventoryUI.PreviewRoot;
			if ((Object)(object)previewRoot == (Object)null)
			{
				return false;
			}
			if ((Object)(object)renderObject != (Object)null)
			{
				if ((Object)(object)renderObject.transform.parent != (Object)(object)previewRoot)
				{
					renderObject.transform.SetParent((Transform)(object)previewRoot, false);
				}
				return true;
			}
			renderObject = new GameObject("RHQOL Character", new Type[4]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(RawImage),
				typeof(AspectRatioFitter)
			});
			RectTransform component = renderObject.GetComponent<RectTransform>();
			((Transform)component).SetParent((Transform)(object)previewRoot, false);
			component.anchorMin = new Vector2(0.5f, 0.5f);
			component.anchorMax = new Vector2(0.5f, 0.5f);
			component.pivot = new Vector2(0.5f, 0.5f);
			component.anchoredPosition = Vector2.zero;
			component.sizeDelta = new Vector2(256f, 320f);
			AspectRatioFitter component2 = renderObject.GetComponent<AspectRatioFitter>();
			component2.aspectMode = (AspectMode)4;
			component2.aspectRatio = 0.8f;
			if ((Object)((Component)previewRoot).GetComponent<RectMask2D>() == (Object)null)
			{
				((Component)previewRoot).gameObject.AddComponent<RectMask2D>();
			}
			rawImage = renderObject.GetComponent<RawImage>();
			((Graphic)rawImage).color = new Color(1f, 1f, 1f, 0f);
			((Graphic)rawImage).raycastTarget = false;
			renderObject.transform.SetAsLastSibling();
			return true;
		}

		private static void EnsureCamera()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Expected O, but got Unknown
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Expected O, but got Unknown
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Expected O, but got Unknown
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Expected O, but got Unknown
			//IL_029e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)previewCamera == (Object)null)
			{
				cameraObject = new GameObject("RHQOL Character Preview Camera");
				previewCamera = cameraObject.AddComponent<Camera>();
				previewCamera.clearFlags = (CameraClearFlags)2;
				previewCamera.backgroundColor = new Color(0f, 0f, 0f, 0f);
				previewCamera.cullingMask = int.MinValue;
				previewCamera.renderingPath = (RenderingPath)(-1);
				previewCamera.useOcclusionCulling = false;
				previewCamera.allowHDR = false;
				previewCamera.allowMSAA = false;
				previewCamera.nearClipPlane = 0.05f;
				previewCamera.farClipPlane = 12f;
				previewCamera.fieldOfView = 30f;
				((Behaviour)previewCamera).enabled = false;
				lightObjectA = new GameObject("RHQOL Preview Key Light");
				Light obj = lightObjectA.AddComponent<Light>();
				obj.type = (LightType)2;
				obj.intensity = 3f;
				obj.range = 6f;
				obj.cullingMask = int.MinValue;
				lightObjectB = new GameObject("RHQOL Preview Fill Light");
				Light obj2 = lightObjectB.AddComponent<Light>();
				obj2.type = (LightType)2;
				obj2.intensity = 1.8f;
				obj2.range = 6f;
				obj2.cullingMask = int.MinValue;
			}
			if ((Object)(object)renderTexture == (Object)null || ((Texture)renderTexture).width != 512 || ((Texture)renderTexture).height != 640)
			{
				if ((Object)(object)renderTexture != (Object)null)
				{
					if ((Object)(object)previewCamera != (Object)null && (Object)(object)previewCamera.targetTexture == (Object)(object)renderTexture)
					{
						previewCamera.targetTexture = null;
					}
					renderTexture.Release();
					Object.Destroy((Object)(object)renderTexture);
				}
				renderTexture = new RenderTexture(512, 640, 24, (RenderTextureFormat)0);
				((Object)renderTexture).name = "RHQOL Character Preview RT";
				renderTexture.useMipMap = false;
				renderTexture.autoGenerateMips = false;
				((Texture)renderTexture).wrapMode = (TextureWrapMode)1;
				((Texture)renderTexture).filterMode = (FilterMode)1;
				renderTexture.Create();
			}
			previewCamera.targetTexture = renderTexture;
			previewCamera.aspect = 0.8f;
			previewCamera.fieldOfView = 30f;
			previewCamera.ResetProjectionMatrix();
			if ((Object)rawImage != (Object)null)
			{
				rawImage.texture = (Texture)(object)renderTexture;
				rawImage.uvRect = new Rect(0f, 0f, 1f, 1f);
			}
		}

		private static void RefreshNow()
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unkn

plugins/RustyHeathensQoL/RustyHeathensFermenterSigns.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("RustyHeathensFermenterSigns")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.7.0")]
[assembly: AssemblyInformationalVersion("1.0.7")]
[assembly: AssemblyProduct("RustyHeathensFermenterSigns")]
[assembly: AssemblyTitle("RustyHeathensFermenterSigns")]
[assembly: AssemblyVersion("1.0.7.0")]
namespace RustyHeathensFermenterSigns;

internal static class BrewStatus
{
	internal static string Format(string status, string brew, double totalSeconds, double elapsedSeconds)
	{
		if (status == "Empty")
		{
			return "Fermenter\nEmpty";
		}
		brew = brew?.Trim();
		if (brew != null && brew.StartsWith("Mead Base:", StringComparison.OrdinalIgnoreCase))
		{
			brew = brew.Substring("Mead Base:".Length).TrimStart();
		}
		if (string.IsNullOrWhiteSpace(brew))
		{
			brew = "Fermenter";
		}
		if (status == "Ready")
		{
			return brew + "\nReady to collect";
		}
		if (status == "Exposed")
		{
			return brew + "\nNeeds shelter";
		}
		if (status != "Fermenting" || !ValidDuration(totalSeconds) || double.IsNaN(elapsedSeconds) || double.IsInfinity(elapsedSeconds))
		{
			return brew + "\nWaiting for status";
		}
		double seconds = Math.Max(0.0, totalSeconds - Math.Max(0.0, elapsedSeconds));
		return brew + "\n" + Duration(seconds) + " left";
	}

	private static bool ValidDuration(double seconds)
	{
		if (seconds >= 0.0)
		{
			return seconds <= 2147483647.0;
		}
		return false;
	}

	private static string Duration(double seconds)
	{
		if (!ValidDuration(seconds))
		{
			return "—";
		}
		int num = (int)Math.Ceiling(seconds);
		int num2 = num / 3600;
		int num3 = num / 60 % 60;
		if (num2 <= 0)
		{
			return $"{num3}:{num % 60:00}";
		}
		return $"{num2}h {num3:00}m {num % 60:00}s";
	}
}
[BepInPlugin("com.rustylasergaming.rustyheathensfermentersigns", "Rusty Heathens Fermenter Signs", "1.0.7")]
[BepInDependency("com.rustylasergaming.rustyheathensqol", "1.0.10")]
public sealed class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(Fermenter), "Awake")]
	private static class AttachSign
	{
		private static void Postfix(Fermenter __instance)
		{
			if (Object.op_Implicit((Object)(object)instance))
			{
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if (Object.op_Implicit((Object)(object)component))
				{
					((Component)__instance).gameObject.AddComponent<FermenterSign>().Initialize(__instance, component);
				}
			}
		}
	}

	public sealed class FermenterSign : MonoBehaviour
	{
		private const float RangeSquared = 144f;

		private Fermenter fermenter;

		private ZNetView view;

		private GameObject sign;

		private Component nativeLabel;

		private MethodInfo refreshTextMesh;

		private PropertyInfo renderedTextBounds;

		private Vector3 nativeLabelScale;

		private Vector3 nativeLabelPosition;

		private Vector2 usableTextArea;

		private string lastText;

		private float nextRefresh;

		internal void Initialize(Fermenter station, ZNetView netView)
		{
			fermenter = station;
			view = netView;
			nextRefresh = Time.unscaledTime + (float)Math.Abs(((Object)this).GetInstanceID() % 31) * 0.01f;
		}

		private void LateUpdate()
		{
			if (!Object.op_Implicit((Object)(object)instance))
			{
				if (Object.op_Implicit((Object)(object)sign))
				{
					Object.Destroy((Object)(object)sign);
				}
				Object.Destroy((Object)(object)this);
			}
			else if (Time.unscaledTime >= nextRefresh)
			{
				nextRefresh = Time.unscaledTime + 0.4f;
				Refresh();
			}
		}

		private void Refresh()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (Object.op_Implicit((Object)(object)view) && view.IsValid() && Object.op_Implicit((Object)(object)localPlayer) && Object.op_Implicit((Object)(object)ZNet.instance))
			{
				Vector3 val = ((Component)localPlayer).transform.position - ((Component)this).transform.position;
				if (!(((Vector3)(ref val)).sqrMagnitude > 144f))
				{
					try
					{
						string? text = getStatus.Invoke(fermenter, null).ToString();
						string text2 = ((text == "Empty") ? null : getContentName(fermenter));
						if (!string.IsNullOrEmpty(text2) && Localization.instance != null)
						{
							text2 = Localization.instance.Localize(text2);
						}
						string text3 = BrewStatus.Format(elapsedSeconds: (text == "Fermenting") ? getElapsedTime(fermenter) : 0.0, status: text, brew: text2, totalSeconds: getDuration.Invoke(fermenter));
						if (Object.op_Implicit((Object)(object)sign) || TryCreateSign())
						{
							if (!sign.activeSelf)
							{
								sign.SetActive(true);
							}
							if (lastText != text3)
							{
								UpdateSignText(text3);
								lastText = text3;
							}
						}
						return;
					}
					catch (Exception ex)
					{
						((BaseUnityPlugin)instance).Logger.LogWarning((object)("Could not read a fermenter sign: " + ex.GetBaseException().Message));
						if (Object.op_Implicit((Object)(object)sign))
						{
							Object.Destroy((Object)(object)sign);
						}
						((Behaviour)this).enabled = false;
						return;
					}
				}
			}
			if (Object.op_Implicit((Object)(object)sign) && sign.activeSelf)
			{
				sign.SetActive(false);
			}
		}

		private bool TryCreateSign()
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: 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_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: 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_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: 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_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Unknown result type (might be due to invalid IL or missing references)
			//IL_0386: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_0397: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03af: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0611: Unknown result type (might be due to invalid IL or missing references)
			//IL_0616: Unknown result type (might be due to invalid IL or missing references)
			//IL_0627: Unknown result type (might be due to invalid IL or missing references)
			//IL_062c: Unknown result type (might be due to invalid IL or missing references)
			ZNetScene instance = ZNetScene.instance;
			if (!Object.op_Implicit((Object)(object)instance))
			{
				return false;
			}
			GameObject prefab = instance.GetPrefab("sign");
			if (!Object.op_Implicit((Object)(object)prefab))
			{
				prefab = instance.GetPrefab("piece_sign");
			}
			if (!Object.op_Implicit((Object)(object)prefab))
			{
				return false;
			}
			GameObject val = new GameObject("Wooden sign");
			if (!CopyVisuals(prefab.transform, val.transform))
			{
				Object.Destroy((Object)(object)val);
				throw new InvalidOperationException("The wooden sign prefab has no usable mesh.");
			}
			MeshRenderer[] componentsInChildren = val.GetComponentsInChildren<MeshRenderer>(true);
			Bounds bounds = ((Renderer)componentsInChildren[0]).bounds;
			MeshRenderer[] array = componentsInChildren;
			foreach (MeshRenderer val2 in array)
			{
				((Bounds)(ref bounds)).Encapsulate(((Renderer)val2).bounds);
			}
			sign = new GameObject("Rusty Heathens Fermenter Sign");
			Transform transform = sign.transform;
			transform.SetParent(((Component)this).transform, false);
			if (!TryGetBarrelBounds(out var barrel))
			{
				Object.Destroy((Object)(object)sign);
				Object.Destroy((Object)(object)val);
				return false;
			}
			Transform val3 = getOutputPoint.Invoke(fermenter);
			Vector3 val4 = (Object.op_Implicit((Object)(object)val3) ? (((Component)this).transform.InverseTransformPoint(val3.position) - ((Bounds)(ref barrel)).center) : Vector3.forward);
			val4.y = 0f;
			val4 = ((((Vector3)(ref val4)).sqrMagnitude < 0.04f) ? Vector3.forward : ((Vector3)(ref val4)).normalized);
			transform.localRotation = Quaternion.LookRotation(val4, Vector3.up);
			transform.localPosition = FindFrontSurface(barrel, val4) - val4 * 0.018f;
			float num = Mathf.Min(1.32f, Mathf.Min(((Bounds)(ref barrel)).size.x, ((Bounds)(ref barrel)).size.z) * 0.92f);
			float num2 = Mathf.Min(0.59f, ((Bounds)(ref barrel)).size.y * 0.36f);
			usableTextArea = new Vector2(num * 0.86f, num2 * 0.76f);
			Vector3 val5 = default(Vector3);
			((Vector3)(ref val5))..ctor(num / Mathf.Max(((Bounds)(ref bounds)).size.x, 0.01f), num2 / Mathf.Max(((Bounds)(ref bounds)).size.y, 0.01f), Mathf.Clamp(num / Mathf.Max(((Bounds)(ref bounds)).size.x, 0.01f), 0.65f, 1.1f));
			val.transform.SetParent(transform, false);
			val.transform.localScale = val5;
			Sign componentInChildren = prefab.GetComponentInChildren<Sign>(true);
			Component val6 = (Component)(Object.op_Implicit((Object)(object)componentInChildren) ? /*isinst with value type is only supported in some contexts*/: null);
			Canvas val7 = (Object.op_Implicit((Object)(object)val6) ? val6.GetComponentInParent<Canvas>(true) : null);
			if (!Object.op_Implicit((Object)(object)val7) || (Object)(object)((Component)val7).transform == (Object)(object)prefab.transform || !((Component)val7).transform.IsChildOf(prefab.transform) || Object.op_Implicit((Object)(object)((Component)val7).GetComponentInChildren<ZNetView>(true)) || Object.op_Implicit((Object)(object)((Component)val7).GetComponentInChildren<Sign>(true)) || Object.op_Implicit((Object)(object)((Component)val7).GetComponentInChildren<Collider>(true)))
			{
				throw new InvalidOperationException("The wooden sign prefab has no isolated text canvas.");
			}
			bool num3 = prefab.transform.InverseTransformPoint(val6.transform.position).z < ((Bounds)(ref bounds)).center.z;
			Quaternion val8 = (num3 ? Quaternion.Euler(0f, 180f, 0f) : Quaternion.identity);
			float num4 = (num3 ? ((Bounds)(ref bounds)).max.z : ((Bounds)(ref bounds)).min.z);
			val.transform.localRotation = val8;
			val.transform.localPosition = -(val8 * Vector3.Scale(new Vector3(((Bounds)(ref bounds)).center.x, ((Bounds)(ref bounds)).center.y, num4), val5));
			Transform val9 = CopyCanvasParent(((Component)val7).transform.parent, prefab.transform, val.transform);
			Canvas component = Object.Instantiate<GameObject>(((Component)val7).gameObject, val9, false).GetComponent<Canvas>();
			component.overrideSorting = false;
			nativeLabel = FindClonedLabel(val6, ((Component)val7).transform, ((Component)component).transform);
			if (!Object.op_Implicit((Object)(object)nativeLabel))
			{
				throw new InvalidOperationException("Could not locate the cloned wooden sign text.");
			}
			Type type = ((object)nativeLabel).GetType();
			refreshTextMesh = type.GetMethod("ForceMeshUpdate", new Type[2]
			{
				typeof(bool),
				typeof(bool)
			}) ?? throw new MissingMethodException(type.FullName, "ForceMeshUpdate");
			renderedTextBounds = type.GetProperty("textBounds") ?? throw new MissingMemberException(type.FullName, "textBounds");
			SetTextOption(type, "richText", true);
			SetTextOption(type, "overrideColorTags", false);
			SetTextOption(type, "enableVertexGradient", false);
			SetTextOption(type, "color", Color.white);
			object? obj = type.GetProperty("fontSharedMaterial")?.GetValue(nativeLabel);
			Material val10 = (Material)((obj is Material) ? obj : null);
			if (val10 != null)
			{
				Material whiteSignMaterial = Plugin.instance.GetWhiteSignMaterial(val10);
				if ((Object)(object)whiteSignMaterial != (Object)(object)val10)
				{
					SetTextOption(type, "fontSharedMaterial", whiteSignMaterial);
				}
			}
			SetTextOption(type, "raycastTarget", false);
			SetTextOption(type, "enableAutoSizing", false);
			PropertyInfo property = type.GetProperty("textWrappingMode");
			if ((object)property != null && property.CanWrite)
			{
				property.SetValue(nativeLabel, Enum.Parse(property.PropertyType, "NoWrap"));
			}
			else
			{
				SetTextOption(type, "enableWordWrapping", false);
			}
			PropertyInfo property2 = type.GetProperty("overflowMode");
			if ((object)property2 != null && property2.CanWrite)
			{
				property2.SetValue(nativeLabel, Enum.Parse(property2.PropertyType, "Overflow"));
			}
			nativeLabelScale = nativeLabel.transform.localScale;
			nativeLabelPosition = nativeLabel.transform.localPosition;
			((Component)component).gameObject.SetActive(true);
			nativeLabel.gameObject.SetActive(true);
			return true;
		}

		private void UpdateSignText(string text)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: 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_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: 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_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: 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_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = nativeLabel.transform;
			Transform transform2 = sign.transform;
			transform.localPosition = nativeLabelPosition;
			transform.localScale = nativeLabelScale;
			string text2 = text.Replace('<', '<').Replace('>', '>');
			nativeTextProperty.SetValue(nativeLabel, "<color=#FFFFFF>" + text2 + "</color>");
			refreshTextMesh.Invoke(nativeLabel, new object[2] { true, true });
			Bounds val = (Bounds)renderedTextBounds.GetValue(nativeLabel);
			Matrix4x4 val2 = transform2.worldToLocalMatrix * transform.localToWorldMatrix;
			Vector3 val3 = ((Matrix4x4)(ref val2)).MultiplyVector(Vector3.right * ((Bounds)(ref val)).size.x);
			Vector3 val4 = ((Matrix4x4)(ref val2)).MultiplyVector(Vector3.up * ((Bounds)(ref val)).size.y);
			float num = Mathf.Min(new float[3]
			{
				1.6f,
				usableTextArea.x / Mathf.Max(0.001f, Mathf.Abs(val3.x) + Mathf.Abs(val4.x)),
				usableTextArea.y / Mathf.Max(0.001f, Mathf.Abs(val3.y) + Mathf.Abs(val4.y))
			});
			transform.localScale = nativeLabelScale * num;
			Vector3 val5 = transform2.InverseTransformPoint(transform.TransformPoint(((Bounds)(ref val)).center));
			transform.position -= transform2.TransformVector(new Vector3(val5.x, val5.y, 0f));
		}

		private void SetTextOption(Type type, string property, object value)
		{
			PropertyInfo property2 = type.GetProperty(property);
			if ((object)property2 != null && property2.CanWrite)
			{
				property2.SetValue(nativeLabel, value);
			}
		}

		private static Component FindClonedLabel(Component source, Transform sourceCanvas, Transform clonedCanvas)
		{
			Stack<int> stack = new Stack<int>();
			Transform val = source.transform;
			while ((Object)(object)val != (Object)(object)sourceCanvas)
			{
				stack.Push(val.GetSiblingIndex());
				val = val.parent;
			}
			while (stack.Count > 0)
			{
				clonedCanvas = clonedCanvas.GetChild(stack.Pop());
			}
			return ((Component)clonedCanvas).GetComponent(((object)source).GetType());
		}

		private static Transform CopyCanvasParent(Transform source, Transform root, Transform destination)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)source == (Object)(object)root)
			{
				return destination;
			}
			Transform val = CopyCanvasParent(source.parent, root, destination);
			Transform transform = new GameObject(((Object)source).name).transform;
			transform.SetParent(val, false);
			transform.localPosition = source.localPosition;
			transform.localRotation = source.localRotation;
			transform.localScale = source.localScale;
			return transform;
		}

		private bool TryGetBarrelBounds(out Bounds barrel)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: 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_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			barrel = default(Bounds);
			bool flag = false;
			MeshRenderer[] componentsInChildren = ((Component)this).GetComponentsInChildren<MeshRenderer>();
			foreach (MeshRenderer val in componentsInChildren)
			{
				if (!((Renderer)val).enabled || ((Component)val).transform.IsChildOf(sign.transform))
				{
					continue;
				}
				Bounds localBounds = ((Renderer)val).localBounds;
				Matrix4x4 val2 = ((Component)this).transform.worldToLocalMatrix * ((Renderer)val).localToWorldMatrix;
				for (int j = 0; j < 8; j++)
				{
					Vector3 val3 = ((Matrix4x4)(ref val2)).MultiplyPoint3x4(new Vector3(((j & 1) == 0) ? ((Bounds)(ref localBounds)).min.x : ((Bounds)(ref localBounds)).max.x, ((j & 2) == 0) ? ((Bounds)(ref localBounds)).min.y : ((Bounds)(ref localBounds)).max.y, ((j & 4) == 0) ? ((Bounds)(ref localBounds)).min.z : ((Bounds)(ref localBounds)).max.z));
					if (!flag)
					{
						barrel = new Bounds(val3, Vector3.zero);
						flag = true;
					}
					else
					{
						((Bounds)(ref barrel)).Encapsulate(val3);
					}
				}
			}
			if (flag)
			{
				return Mathf.Min(((Bounds)(ref barrel)).size.x, ((Bounds)(ref barrel)).size.z) >= 0.2f;
			}
			return false;
		}

		private Vector3 FindFrontSurface(Bounds barrel, Vector3 front)
		{
			//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_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			Vector3 center = ((Bounds)(ref barrel)).center;
			center.y = Mathf.Lerp(((Bounds)(ref barrel)).min.y, ((Bounds)(ref barrel)).max.y, 0.65f);
			Vector2 val = new Vector2(front.x / ((Bounds)(ref barrel)).extents.x, front.z / ((Bounds)(ref barrel)).extents.z);
			float num = 1f / ((Vector2)(ref val)).magnitude;
			Vector3 result = center + front * num;
			Vector3 val2 = ((Component)this).transform.TransformPoint(center + front * (num + 0.5f));
			Vector3 val3 = ((Component)this).transform.TransformPoint(center);
			Vector3 val4 = val3 - val2;
			Ray val5 = default(Ray);
			((Ray)(ref val5))..ctor(val2, ((Vector3)(ref val4)).normalized);
			float num2 = Vector3.Distance(val2, val3);
			Collider[] componentsInChildren = ((Component)this).GetComponentsInChildren<Collider>();
			RaycastHit val7 = default(RaycastHit);
			foreach (Collider val6 in componentsInChildren)
			{
				if (val6.enabled && !val6.isTrigger && val6.Raycast(val5, ref val7, num2) && !(((RaycastHit)(ref val7)).distance >= num2))
				{
					num2 = ((RaycastHit)(ref val7)).distance;
					result = ((Component)this).transform.InverseTransformPoint(((RaycastHit)(ref val7)).point);
				}
			}
			return result;
		}

		private static bool CopyVisuals(Transform source, Transform destination)
		{
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			bool result = false;
			MeshFilter component = ((Component)source).GetComponent<MeshFilter>();
			MeshRenderer component2 = ((Component)source).GetComponent<MeshRenderer>();
			if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.sharedMesh) && Object.op_Implicit((Object)(object)component2) && ((Renderer)component2).enabled)
			{
				((Component)destination).gameObject.AddComponent<MeshFilter>().sharedMesh = component.sharedMesh;
				((Renderer)((Component)destination).gameObject.AddComponent<MeshRenderer>()).sharedMaterials = ((Renderer)component2).sharedMaterials;
				result = true;
			}
			foreach (Transform item in source)
			{
				Transform val = item;
				if (((Component)val).gameObject.activeSelf)
				{
					Transform transform = new GameObject(((Object)val).name).transform;
					transform.SetParent(destination, false);
					transform.localPosition = val.localPosition;
					transform.localRotation = val.localRotation;
					transform.localScale = val.localScale;
					if (CopyVisuals(val, transform))
					{
						result = true;
					}
					else
					{
						Object.Destroy((Object)(object)((Component)transform).gameObject);
					}
				}
			}
			return result;
		}
	}

	private const string Id = "com.rustylasergaming.rustyheathensfermentersigns";

	private static Plugin instance;

	private Harmony harmony;

	private Harmony wishboneHarmony;

	private readonly Dictionary<Material, Material> whiteSignMaterials = new Dictionary<Material, Material>();

	private static MethodInfo getStatus;

	private static Func<Fermenter, string> getContentName;

	private static Func<Fermenter, double> getElapsedTime;

	private static FieldRef<Fermenter, float> getDuration;

	private static FieldInfo nativeTextField;

	private static PropertyInfo nativeTextProperty;

	private static FieldRef<Fermenter, Transform> getOutputPoint;

	private void Awake()
	{
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_0121: Expected O, but got Unknown
		if (Application.isBatchMode)
		{
			return;
		}
		wishboneHarmony = WishboneFix.Install(((BaseUnityPlugin)this).Logger);
		try
		{
			Type typeFromHandle = typeof(Fermenter);
			getStatus = AccessTools.Method(typeFromHandle, "GetStatus", Type.EmptyTypes, (Type[])null) ?? throw new MissingMethodException(typeFromHandle.FullName, "GetStatus");
			getContentName = AccessTools.MethodDelegate<Func<Fermenter, string>>(AccessTools.Method(typeFromHandle, "GetContentName", Type.EmptyTypes, (Type[])null), (object)null, true);
			getElapsedTime = AccessTools.MethodDelegate<Func<Fermenter, double>>(AccessTools.Method(typeFromHandle, "GetFermentationTime", Type.EmptyTypes, (Type[])null), (object)null, true);
			getDuration = AccessTools.FieldRefAccess<Fermenter, float>("m_fermentationDuration");
			nativeTextField = AccessTools.Field(typeof(Sign), "m_textWidget") ?? throw new MissingFieldException("Sign", "m_textWidget");
			nativeTextProperty = nativeTextField.FieldType.GetProperty("text") ?? throw new MissingMemberException(nativeTextField.FieldType.FullName, "text");
			getOutputPoint = AccessTools.FieldRefAccess<Fermenter, Transform>("m_outputPoint");
			instance = this;
			harmony = new Harmony("com.rustylasergaming.rustyheathensfermentersigns");
			harmony.PatchAll(typeof(Plugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Fermenter signs active.");
		}
		catch (Exception arg)
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			instance = null;
			((BaseUnityPlugin)this).Logger.LogError((object)$"Fermenter sign setup failed: {arg}");
		}
	}

	private void OnDestroy()
	{
		Harmony obj = wishboneHarmony;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		Harmony obj2 = harmony;
		if (obj2 != null)
		{
			obj2.UnpatchSelf();
		}
		instance = null;
		foreach (Material value in whiteSignMaterials.Values)
		{
			Object.Destroy((Object)(object)value);
		}
		whiteSignMaterials.Clear();
	}

	private Material GetWhiteSignMaterial(Material original)
	{
		//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_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Expected O, but got Unknown
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)original) || !original.HasProperty("_FaceColor") || original.GetColor("_FaceColor") == Color.white)
		{
			return original;
		}
		if (!whiteSignMaterials.TryGetValue(original, out var value))
		{
			value = new Material(original);
			value.SetColor("_FaceColor", Color.white);
			whiteSignMaterials.Add(original, value);
		}
		return value;
	}
}
internal sealed class WishboneFix
{
	private const string PatchId = "com.rustylasergaming.rustyheathensfermentersigns.wishbone";

	private static FieldRef<Humanoid, ItemData> mainUtility;

	private static FieldRef<ItemData> extraUtility;

	private static Func<Player, ItemData> getExtraUtility;

	private static Func<Inventory, Vector2i, int> slotIndex;

	private static Func<Inventory, bool, Vector2i> emptyNormal;

	private static Action<Inventory> notifyInventory;

	private static FieldRef<InventoryGui, GameObject> dragObject;

	private static FieldRef<InventoryGui, ItemData> dragItem;

	private static int automaticEquip;

	private static float nextCheck;

	private static Player previousPlayer;

	private static ItemData pendingMove;

	internal static Harmony Install(ManualLogSource logger)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Expected O, but got Unknown
		//IL_00e5: Expected O, but got Unknown
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: Expected O, but got Unknown
		//IL_0124: Expected O, but got Unknown
		//IL_0141: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Expected O, but got Unknown
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_017a: Expected O, but got Unknown
		//IL_0197: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Expected O, but got Unknown
		//IL_01b9: Expected O, but got Unknown
		//IL_01df: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f8: Expected O, but got Unknown
		//IL_021e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0233: Unknown result type (might be due to invalid IL or missing references)
		//IL_0240: Expected O, but got Unknown
		//IL_0240: Expected O, but got Unknown
		//IL_0267: Unknown result type (might be due to invalid IL or missing references)
		//IL_0274: Expected O, but got Unknown
		Harmony val = new Harmony("com.rustylasergaming.rustyheathensfermentersigns.wishbone");
		try
		{
			Type type = AccessTools.TypeByName("RustyHeathens.QoL.StandaloneInventory") ?? throw new TypeLoadException("Rusty Heathens QoL equipment routines");
			mainUtility = AccessTools.FieldRefAccess<Humanoid, ItemData>("m_utilityItem");
			extraUtility = AccessTools.StaticFieldRefAccess<ItemData>(AccessTools.Field(type, "extraUtilityEquipped"));
			getExtraUtility = Bind<Func<Player, ItemData>>(type, "GetExtraUtility");
			slotIndex = Bind<Func<Inventory, Vector2i, int>>(type, "SlotIndexForPosition");
			emptyNormal = Bind<Func<Inventory, bool, Vector2i>>(type, "FindEmptyNormal");
			notifyInventory = Bind<Action<Inventory>>(type, "NotifyInventory");
			dragObject = AccessTools.FieldRefAccess<InventoryGui, GameObject>("m_dragGo");
			dragItem = AccessTools.FieldRefAccess<InventoryGui, ItemData>("m_dragItem");
			val.Patch((MethodBase)Require(type, "ReconcileAll"), new HarmonyMethod(typeof(WishboneFix), "BeginAutomatic", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(WishboneFix), "EndAutomatic", (Type[])null), (HarmonyMethod)null);
			val.Patch((MethodBase)Require(type, "EnsureDedicatedSlotEquipment"), new HarmonyMethod(typeof(WishboneFix), "BeginAutomatic", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(WishboneFix), "EndAutomatic", (Type[])null), (HarmonyMethod)null);
			val.Patch((MethodBase)Require(type, "TryAutoEquipAddedItem"), new HarmonyMethod(typeof(WishboneFix), "PickupPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)Require(type, "EquipExtraUtility"), new HarmonyMethod(typeof(WishboneFix), "ExtraEquipPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)Require(type, "TryHandleExtraUtilityUnequip"), new HarmonyMethod(typeof(WishboneFix), "ExtraUnequipPrefix", (Type[])null), new HarmonyMethod(typeof(WishboneFix), "ExtraUnequipPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)Require(typeof(Humanoid), "EquipItem"), new HarmonyMethod(typeof(WishboneFix), "EquipPrefix", (Type[])null)
			{
				priority = 800
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)Require(typeof(Humanoid), "UnequipItem"), new HarmonyMethod(typeof(WishboneFix), "UnequipPrefix", (Type[])null), new HarmonyMethod(typeof(WishboneFix), "UnequipPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)Require(typeof(Player), "Update"), (HarmonyMethod)null, new HarmonyMethod(typeof(WishboneFix), "CheckEquipment", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			logger.LogInfo((object)"Wishbone equip and lingering-effect fixes active.");
			return val;
		}
		catch (Exception arg)
		{
			val.UnpatchSelf();
			logger.LogError((object)$"Wishbone fix setup failed: {arg}");
			return null;
		}
	}

	private static MethodInfo Require(Type type, string method)
	{
		return AccessTools.Method(type, method, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.FullName, method);
	}

	private static T Bind<T>(Type type, string method) where T : Delegate
	{
		return AccessTools.MethodDelegate<T>(Require(type, method), (object)null, true);
	}

	private static bool IsWishbone(ItemData item)
	{
		if (!(item?.m_shared?.m_name == "$item_wishbone"))
		{
			if (Object.op_Implicit((Object)(object)item?.m_dropPrefab))
			{
				return ((Object)item.m_dropPrefab).name == "Wishbone";
			}
			return false;
		}
		return true;
	}

	private static void BeginAutomatic()
	{
		automaticEquip++;
	}

	private static void EndAutomatic()
	{
		automaticEquip--;
	}

	private static bool PickupPrefix(ItemData __1, ref bool __result)
	{
		if (!IsWishbone(__1))
		{
			return true;
		}
		__result = false;
		return false;
	}

	private static bool EquipPrefix(Humanoid __instance, ItemData __0, ref bool __result)
	{
		if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || !IsWishbone(__0) || automaticEquip == 0 || __0.m_equipped)
		{
			return true;
		}
		__result = false;
		return false;
	}

	private static bool ExtraEquipPrefix(Player __0, ItemData __1)
	{
		if ((Object)(object)__0 != (Object)(object)Player.m_localPlayer || !IsWishbone(__1))
		{
			return true;
		}
		if (((Humanoid)__0).GetInventory().ContainsItem(__1))
		{
			if (automaticEquip != 0)
			{
				return __1.m_equipped;
			}
			return true;
		}
		return false;
	}

	private static bool ExtraUnequipPrefix(Humanoid __0, ItemData __1, ref bool __result)
	{
		if ((Object)(object)__0 != (Object)(object)Player.m_localPlayer || !IsWishbone(__1) || mainUtility.Invoke(__0) != __1)
		{
			return true;
		}
		__result = false;
		return false;
	}

	private static void ExtraUnequipPostfix(Humanoid __0, ItemData __1, bool __result)
	{
		if (__result && (Object)(object)__0 == (Object)(object)Player.m_localPlayer && IsWishbone(__1))
		{
			pendingMove = __1;
		}
	}

	private static void UnequipPrefix(Humanoid __instance, ItemData __0, out bool __state)
	{
		__state = (Object)(object)__instance == (Object)(object)Player.m_localPlayer && IsWishbone(__0);
	}

	private static void UnequipPostfix(ItemData __0, bool __state)
	{
		if (__state)
		{
			pendingMove = __0;
		}
	}

	private static void CheckEquipment(Player __instance)
	{
		//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0208: Unknown result type (might be due to invalid IL or missing references)
		//IL_020d: Unknown result type (might be due to invalid IL or missing references)
		//IL_020f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0222: Unknown result type (might be due to invalid IL or missing references)
		//IL_0224: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
		{
			return;
		}
		if ((Object)(object)previousPlayer != (Object)(object)__instance)
		{
			previousPlayer = __instance;
			pendingMove = null;
			nextCheck = 0f;
		}
		if (Time.unscaledTime < nextCheck)
		{
			return;
		}
		nextCheck = Time.unscaledTime + 0.2f;
		Inventory inventory = ((Humanoid)__instance).GetInventory();
		if (inventory == null)
		{
			return;
		}
		ItemData val = mainUtility.Invoke((Humanoid)(object)__instance);
		if (IsWishbone(val) && !inventory.ContainsItem(val))
		{
			((Humanoid)__instance).UnequipItem(val, false);
		}
		ItemData val2 = extraUtility.Invoke();
		if (IsWishbone(val2) && !inventory.ContainsItem(val2))
		{
			val2.m_equipped = false;
			extraUtility.Invoke() = null;
		}
		ItemData val3 = mainUtility.Invoke((Humanoid)(object)__instance);
		bool num = IsWishbone(val3) && val3.m_equipped && inventory.ContainsItem(val3);
		ItemData val4 = getExtraUtility(__instance);
		if (!(num | (IsWishbone(val4) && val4.m_equipped && inventory.ContainsItem(val4))) && Object.op_Implicit((Object)(object)ObjectDB.instance))
		{
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("Wishbone");
			StatusEffect val5 = ((!Object.op_Implicit((Object)(object)itemPrefab)) ? null : itemPrefab.GetComponent<ItemDrop>()?.m_itemData)?.m_shared?.m_equipStatusEffect;
			if (Object.op_Implicit((Object)(object)val5))
			{
				int num2 = val5.NameHash();
				SEMan sEMan = ((Character)__instance).GetSEMan();
				if (sEMan != null && sEMan.HaveStatusEffect(num2))
				{
					sEMan.RemoveStatusEffect(num2, true);
				}
			}
		}
		ItemData val6 = pendingMove;
		if (val6 == null)
		{
			return;
		}
		if (val6.m_equipped || !inventory.ContainsItem(val6) || slotIndex(inventory, val6.m_gridPos) < 0)
		{
			pendingMove = null;
			return;
		}
		InventoryGui instance = InventoryGui.instance;
		if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)dragObject.Invoke(instance)) || dragItem.Invoke(instance) != val6)
		{
			Vector2i val7 = emptyNormal(inventory, arg2: true);
			if (val7.x >= 0)
			{
				pendingMove = null;
				val6.m_gridPos = val7;
				notifyInventory(inventory);
			}
		}
	}
}