Decompiled source of RustyHeathensServerQoL v1.0.1

RustyHeathensServerQoL.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using RustyHeathens.Automation;
using RustyHeathens.Backpacks;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Rusty Heathens Server QoL")]
[assembly: AssemblyDescription("Server-side quality-of-life modules for Heathens' Haven")]
[assembly: AssemblyCompany("RustyLaserGaming")]
[assembly: AssemblyProduct("Rusty Heathens Server QoL")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyVersion("1.0.1.0")]
[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.Automation
{
	internal static class GroundStoreRules
	{
		internal static bool IsEligible(bool isPiece, int maxStackSize, bool isConsumable)
		{
			if (!isPiece && maxStackSize > 0)
			{
				if (!isConsumable)
				{
					return maxStackSize > 1;
				}
				return true;
			}
			return false;
		}
	}
	internal static class LiveAutoStore
	{
		private sealed class Request
		{
			internal ZDOID Drop;

			internal int Token;

			internal long Deadline;

			internal float Range;

			internal float NextAttempt;

			internal string Item = "unknown";

			internal string LastWait = "not_attempted";

			internal readonly List<ZDOID> Chests = new List<ZDOID>();

			internal Action<string> Log;

			internal Action<ZPackage> Report;
		}

		internal const string ReadyRpc = "RHSQOL_StoreReady_v3";

		internal const string JobRpc = "RHSQOL_StoreJob_v3";

		internal const string ResultRpc = "RHSQOL_StoreResult_v3";

		private static readonly Dictionary<ZDOID, Request> Pending = new Dictionary<ZDOID, Request>();

		private static readonly Dictionary<ZDOID, int> Seen = new Dictionary<ZDOID, int>();

		private static readonly MethodInfo LoadDrop = AccessTools.Method(typeof(ItemDrop), "Load", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo LoadChest = AccessTools.Method(typeof(Container), "CheckForChanges", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo RequestOwn = AccessTools.Method(typeof(ItemDrop), "RequestOwn", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo ChestAccess = AccessTools.Method(typeof(Container), "CheckAccess", new Type[1] { typeof(long) }, (Type[])null);

		private static bool paused;

		private static long Now
		{
			get
			{
				if (!((Object)(object)ZNet.instance == (Object)null))
				{
					return ZNet.instance.GetTime().Ticks;
				}
				return 0L;
			}
		}

		internal static void Clear()
		{
			Pending.Clear();
			Seen.Clear();
			paused = false;
		}

		private static ZNetView View(GameObject obj)
		{
			if (!((Object)(object)obj == (Object)null))
			{
				return obj.GetComponent<ZNetView>();
			}
			return null;
		}

		private static GameObject Instance(ZDOID id)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)ZNetScene.instance == (Object)null))
			{
				return ZNetScene.instance.FindInstance(id);
			}
			return null;
		}

		internal static void Handle(ZPackage pkg, Action<string> log, Action<ZPackage> report)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: 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_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			if (pkg == null || paused || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			pkg.SetPos(0);
			Request request = new Request();
			request.Drop = pkg.ReadZDOID();
			request.Token = pkg.ReadInt();
			request.Deadline = pkg.ReadLong();
			request.Range = pkg.ReadSingle();
			int num = pkg.ReadInt();
			if (request.Token > 0 && !((ZDOID)(ref request.Drop)).IsNone() && num > 0 && num <= 64 && !(request.Range <= 0f) && !(request.Range > 64f) && StoreLease.IsLive(Now, request.Deadline) && (!Seen.TryGetValue(request.Drop, out var value) || value < request.Token) && (!Pending.TryGetValue(request.Drop, out var value2) || !StoreLease.IsLive(Now, value2.Deadline)))
			{
				for (int i = 0; i < num; i++)
				{
					request.Chests.Add(pkg.ReadZDOID());
				}
				request.Log = log;
				request.Report = report;
				if (Seen.Count > 4096 && Pending.Count == 0)
				{
					Seen.Clear();
				}
				Seen[request.Drop] = request.Token;
				Pending[request.Drop] = request;
				Tick();
			}
		}

		private unsafe static void Finish(Request request, string status, int amount, ZDOID chest)
		{
			//IL_0006: 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_007e: Expected O, but got Unknown
			//IL_0080: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			Pending.Remove(request.Drop);
			if (status != "stored" && request.Log != null)
			{
				Action<string> log = request.Log;
				string[] obj = new string[6] { "RESULT drop=", null, null, null, null, null };
				ZDOID drop = request.Drop;
				obj[1] = ((object)(*(ZDOID*)(&drop))/*cast due to .constrained prefix*/).ToString();
				obj[2] = " item=";
				obj[3] = request.Item;
				obj[4] = " reason=";
				obj[5] = status;
				log(string.Concat(obj));
			}
			ZPackage val = new ZPackage();
			val.Write(request.Drop);
			val.Write(request.Token);
			val.Write(status);
			val.Write(amount);
			val.Write(chest);
			if (request.Report != null)
			{
				request.Report(val);
			}
		}

		internal unsafe static void Tick()
		{
			//IL_00a2: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			if (paused || Pending.Count == 0)
			{
				return;
			}
			foreach (Request item in new List<Request>(Pending.Values))
			{
				if (!StoreLease.IsLive(Now, item.Deadline))
				{
					Finish(item, "expired:" + item.LastWait, 0, ZDOID.None);
				}
				else if (!(Time.realtimeSinceStartup < item.NextAttempt))
				{
					item.NextAttempt = Time.realtimeSinceStartup + 0.25f;
					try
					{
						TryStore(item);
					}
					catch (Exception ex)
					{
						paused = true;
						Action<string> log = item.Log;
						ZDOID drop = item.Drop;
						log("AUTOSTORE PAUSED drop=" + ((object)(*(ZDOID*)(&drop))/*cast due to .constrained prefix*/).ToString() + ": " + ex);
						Finish(item, "paused", 0, ZDOID.None);
						Pending.Clear();
						break;
					}
				}
			}
		}

		private static string AccessBlock(Container chest)
		{
			//IL_0007: 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_0063: Invalid comparison between Unknown and I4
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Invalid comparison between Unknown and I4
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((int)chest.m_privacy == 0)
			{
				if ((Object)(object)localPlayer == (Object)null)
				{
					return "private_no_local_player";
				}
				if (ChestAccess == null)
				{
					return "private_access_api_missing";
				}
				if (!(bool)ChestAccess.Invoke(chest, new object[1] { localPlayer.GetPlayerID() }))
				{
					return "private_access_denied";
				}
			}
			else if ((int)chest.m_privacy != 1 && (int)chest.m_privacy != 2)
			{
				return "unknown_privacy";
			}
			if (chest.m_checkGuardStone)
			{
				if ((Object)(object)localPlayer == (Object)null)
				{
					return "ward_no_local_player";
				}
				if (!PrivateArea.CheckAccess(((Component)chest).transform.position, 0f, false, false))
				{
					return "ward_denied";
				}
			}
			return null;
		}

		private static void Count(SortedDictionary<string, int> reasons, string reason)
		{
			reasons.TryGetValue(reason, out var value);
			reasons[reason] = value + 1;
		}

		private static string Describe(SortedDictionary<string, int> reasons)
		{
			List<string> list = new List<string>();
			foreach (KeyValuePair<string, int> reason in reasons)
			{
				list.Add(reason.Key + "=" + reason.Value);
			}
			return string.Join(",", list.ToArray());
		}

		private unsafe static void TryStore(Request request)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Invalid comparison between Unknown and I4
			//IL_012c: 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_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: 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_03ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_047b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0480: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0502: Unknown result type (might be due to invalid IL or missing references)
			//IL_0507: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_038c: Unknown result type (might be due to invalid IL or missing references)
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer == (Object)null && (Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer())
			{
				request.LastWait = "local_player_loading";
				return;
			}
			GameObject val = Instance(request.Drop);
			ItemDrop val2 = (((Object)(object)val == (Object)null) ? null : val.GetComponent<ItemDrop>());
			ZNetView val3 = View(val);
			if ((Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null || !val3.IsValid())
			{
				request.LastWait = "drop_not_loaded";
				return;
			}
			if (LoadDrop == null || LoadChest == null || RequestOwn == null)
			{
				throw new InvalidOperationException("Vanilla load/ownership API unavailable.");
			}
			LoadDrop.Invoke(val2, null);
			ItemData itemData = val2.m_itemData;
			if (itemData == null || itemData.m_shared == null)
			{
				request.LastWait = "drop_data_unavailable";
				return;
			}
			request.Item = itemData.m_shared.m_name;
			if (itemData.m_stack <= 0)
			{
				Finish(request, "gone", 0, ZDOID.None);
				return;
			}
			if (!GroundStoreRules.IsEligible(val3.GetZDO().GetBool(ZDOVars.s_piece, false), itemData.m_shared.m_maxStackSize, (int)itemData.m_shared.m_itemType == 2))
			{
				Finish(request, "excluded", 0, ZDOID.None);
				return;
			}
			ZDOID val4 = ZDOID.None;
			float num = request.Range * request.Range;
			bool flag = false;
			SortedDictionary<string, int> reasons = new SortedDictionary<string, int>(StringComparer.Ordinal);
			foreach (ZDOID chest in request.Chests)
			{
				GameObject val5 = Instance(chest);
				if ((Object)(object)val5 == (Object)null)
				{
					flag = true;
					Count(reasons, "chest_not_loaded");
					continue;
				}
				Container component = val5.GetComponent<Container>();
				ZNetView val6 = View(val5);
				if ((Object)(object)component == (Object)null)
				{
					Count(reasons, "container_missing");
					continue;
				}
				if ((Object)(object)val6 == (Object)null || !val6.IsValid())
				{
					Count(reasons, "chest_view_invalid");
					continue;
				}
				if (!val6.IsOwner())
				{
					Count(reasons, "chest_not_owned");
					continue;
				}
				if (component.IsInUse() || val6.GetZDO().GetInt(ZDOVars.s_inUse, 0) != 0)
				{
					Count(reasons, "chest_in_use");
					continue;
				}
				if (!OwnerAutomation.EligibleChest(component, val6))
				{
					Count(reasons, "chest_excluded");
					continue;
				}
				string text = AccessBlock(component);
				if (text != null)
				{
					Count(reasons, text);
					continue;
				}
				Vector3 val7 = val5.transform.position - val.transform.position;
				float sqrMagnitude = ((Vector3)(ref val7)).sqrMagnitude;
				if (sqrMagnitude > request.Range * request.Range)
				{
					Count(reasons, "outside_range");
				}
				else if (!(sqrMagnitude > num))
				{
					LoadChest.Invoke(component, null);
					Inventory inventory = component.GetInventory();
					if (inventory == null)
					{
						Count(reasons, "inventory_unavailable");
						continue;
					}
					if (inventory.CountItems(itemData.m_shared.m_name, -1, true) <= 0)
					{
						Count(reasons, "no_matching_items");
						continue;
					}
					if (!inventory.CanAddItem(itemData, itemData.m_stack))
					{
						Count(reasons, "matching_chest_full");
						continue;
					}
					val4 = chest;
					num = sqrMagnitude;
				}
			}
			if (((ZDOID)(ref val4)).IsNone())
			{
				request.LastWait = "no_matching_chest:" + Describe(reasons);
				if (!flag)
				{
					Finish(request, request.LastWait, 0, ZDOID.None);
				}
			}
			else if (!val3.IsOwner())
			{
				RequestOwn.Invoke(val2, null);
				request.LastWait = "drop_owner_handoff";
			}
			else if (!val2.CanPickup(true))
			{
				request.LastWait = "vanilla_pickup_not_ready";
			}
			else if (StoreLease.IsLive(Now, request.Deadline))
			{
				int stack = itemData.m_stack;
				string lastWait = request.LastWait;
				request.LastWait = "transfer_rejected";
				if (OwnerAutomation.Store(request.Drop, val4, request.Range, request.Log, delegate(string reason)
				{
					request.LastWait = reason;
				}))
				{
					Finish(request, "stored", stack, val4);
				}
				else if (lastWait != request.LastWait && request.Log != null)
				{
					Action<string> log = request.Log;
					string[] obj = new string[6] { "TRANSFER WAIT drop=", null, null, null, null, null };
					ZDOID drop = request.Drop;
					obj[1] = ((object)(*(ZDOID*)(&drop))/*cast due to .constrained prefix*/).ToString();
					obj[2] = " item=";
					obj[3] = request.Item;
					obj[4] = " reason=";
					obj[5] = request.LastWait;
					log(string.Concat(obj));
				}
			}
		}
	}
	internal static class OwnerAutomation
	{
		internal const string ReadyRpc = "RHSQOL_AutomationReady_v2";

		internal const string JobRpc = "RHSQOL_AutomationJob_v2";

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

		private static readonly int GraveMarker = StringExtensionMethods.GetStableHashCode("RHSQOL_RustyBackpack_Grave");

		private static readonly Dictionary<ZDOID, float> NextJob = new Dictionary<ZDOID, float>();

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

		private static readonly List<ZDOID> EmptyDrops = new List<ZDOID>();

		private static bool emergencyPaused;

		private static readonly MethodInfo SaveContainer = AccessTools.Method(typeof(Container), "Save", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo LoadContainer = AccessTools.Method(typeof(Container), "CheckForChanges", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo SaveDrop = AccessTools.Method(typeof(ItemDrop), "Save", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo QueueOre = AccessTools.Method(typeof(Smelter), "QueueOre", new Type[2]
		{
			typeof(string),
			typeof(bool)
		}, (Type[])null);

		private static readonly MethodInfo SetFuel = AccessTools.Method(typeof(Smelter), "SetFuel", new Type[1] { typeof(float) }, (Type[])null);

		internal static void Clear()
		{
			NextJob.Clear();
			Blocked.Clear();
			EmptyDrops.Clear();
			emergencyPaused = false;
		}

		private static bool Owned(ZNetView view)
		{
			if ((Object)(object)view != (Object)null && view.IsValid())
			{
				return view.IsOwner();
			}
			return false;
		}

		private static ZNetView View(GameObject obj)
		{
			if (!((Object)(object)obj == (Object)null))
			{
				return obj.GetComponent<ZNetView>();
			}
			return null;
		}

		private static GameObject Instance(ZDOID id)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)ZNetScene.instance == (Object)null))
			{
				return ZNetScene.instance.FindInstance(id);
			}
			return null;
		}

		internal static bool EligibleChest(Container chest, ZNetView view)
		{
			if ((Object)(object)chest == (Object)null || !Owned(view) || (Object)(object)chest.m_wagon != (Object)null || chest.m_autoDestroyEmpty || chest.IsInUse())
			{
				return false;
			}
			ZDO zDO = view.GetZDO();
			if (zDO.GetInt(ZDOVars.s_inUse, 0) == 0 && !zDO.GetBool(BackpackMarker, false))
			{
				return !zDO.GetBool(GraveMarker, false);
			}
			return false;
		}

		internal unsafe static void Handle(ZPackage job, Action<string> log)
		{
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: 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_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: 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_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: 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)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			if (emergencyPaused || job == null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			job.SetPos(0);
			int num = job.ReadInt();
			ZDOID val = job.ReadZDOID();
			if (Blocked.Contains(val))
			{
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (NextJob.TryGetValue(val, out var value) && realtimeSinceStartup < value)
			{
				return;
			}
			if (NextJob.Count > 4096)
			{
				NextJob.Clear();
			}
			NextJob[val] = realtimeSinceStartup + ((num == 1) ? 1.8f : 0.5f);
			try
			{
				switch (num)
				{
				case 1:
				{
					float num3 = job.ReadSingle();
					int maxFuel = Math.Max(0, Math.Min(20, job.ReadInt()));
					int maxOre = Math.Max(0, Math.Min(20, job.ReadInt()));
					int reserveFuel = Math.Max(0, job.ReadInt());
					int reserveOre = Math.Max(0, job.ReadInt());
					int num4 = job.ReadInt();
					if (num4 >= 0 && num4 <= 64 && !(num3 <= 0f) && !(num3 > 64f))
					{
						List<ZDOID> list = new List<ZDOID>();
						for (int i = 0; i < num4; i++)
						{
							list.Add(job.ReadZDOID());
						}
						Process(val, list, num3, maxFuel, maxOre, reserveFuel, reserveOre, log);
					}
					break;
				}
				case 2:
				{
					ZDOID val2 = job.ReadZDOID();
					float num2 = job.ReadSingle();
					if (!(num2 <= 0f) && !(num2 > 64f) && !Blocked.Contains(val2))
					{
						Store(val, val2, num2, log);
					}
					break;
				}
				}
			}
			catch (Exception ex)
			{
				Blocked.Add(val);
				emergencyPaused = true;
				ZDOID val3 = val;
				log("PAUSED object=" + ((object)(*(ZDOID*)(&val3))/*cast due to .constrained prefix*/).ToString() + ": " + ex);
			}
		}

		internal static void Tick()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			for (int num = EmptyDrops.Count - 1; num >= 0; num--)
			{
				GameObject val = Instance(EmptyDrops[num]);
				if ((Object)(object)val == (Object)null)
				{
					EmptyDrops.RemoveAt(num);
				}
				else
				{
					ZNetView val2 = View(val);
					ItemDrop component = val.GetComponent<ItemDrop>();
					if (!Owned(val2) || (Object)(object)component == (Object)null || component.m_itemData.m_stack != 0)
					{
						EmptyDrops.RemoveAt(num);
					}
					else
					{
						try
						{
							val2.Destroy();
							EmptyDrops.RemoveAt(num);
						}
						catch
						{
						}
					}
				}
			}
		}

		private static byte[] Bytes(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();
		}

		private static bool Same(byte[] a, byte[] b)
		{
			if (a == null || b == null || a.Length != b.Length)
			{
				return false;
			}
			for (int i = 0; i < a.Length; i++)
			{
				if (a[i] != b[i])
				{
					return false;
				}
			}
			return true;
		}

		private static void Persist(Container chest, ZNetView view)
		{
			if (!Owned(view) || SaveContainer == null)
			{
				throw new InvalidOperationException("Container ownership/save unavailable.");
			}
			SaveContainer.Invoke(chest, null);
			if (!Same(Bytes(chest.GetInventory()), view.GetZDO().GetByteArray(ZDOVars.s_items, (byte[])null)))
			{
				throw new InvalidOperationException("Container inventory save was not verified.");
			}
		}

		private static void Restore(Container chest, ZNetView view, 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);
			chest.GetInventory().Load(val);
			Persist(chest, view);
		}

		private static bool Feed(Smelter smelter, ZNetView station, Container chest, ZNetView chestView, string sharedName, string prefabName, int reserve, bool fuel)
		{
			if (!Owned(station) || !EligibleChest(chest, chestView))
			{
				return false;
			}
			Inventory inv = chest.GetInventory();
			int beforeCount = inv.CountItems(sharedName, -1, true);
			if (beforeCount <= reserve)
			{
				return false;
			}
			ItemData item = inv.GetItem(sharedName, -1, false);
			if (item == null)
			{
				return false;
			}
			ZDO zdo = station.GetZDO();
			float beforeFuel = zdo.GetFloat(ZDOVars.s_fuel, 0f);
			int beforeQueue = zdo.GetInt(ZDOVars.s_queued, 0);
			if (fuel ? (Math.Ceiling(beforeFuel) >= (double)smelter.m_maxFuel) : (beforeQueue >= smelter.m_maxOre))
			{
				return false;
			}
			if ((fuel && SetFuel == null) || (!fuel && QueueOre == null))
			{
				return false;
			}
			string slotKey = "item" + beforeQueue;
			string oldSlot = zdo.GetString(slotKey, "");
			bool oldCheated = zdo.GetBool(ZDOVars.s_cheatedQueued, false);
			byte[] chestBefore = Bytes(inv);
			float expectedFuel = Math.Min(smelter.m_maxFuel, beforeFuel + 1f);
			return TransferSafety.Commit(delegate
			{
				if (!Owned(station) || !EligibleChest(chest, chestView))
				{
					throw new InvalidOperationException("Ownership changed.");
				}
				if (fuel)
				{
					SetFuel.Invoke(smelter, new object[1] { expectedFuel });
				}
				else
				{
					QueueOre.Invoke(smelter, new object[2] { prefabName, item.m_cheated });
				}
			}, () => Owned(station) && ((!fuel) ? (zdo.GetInt(ZDOVars.s_queued, 0) == beforeQueue + 1 && zdo.GetString(slotKey, "") == prefabName) : (Math.Abs(zdo.GetFloat(ZDOVars.s_fuel, 0f) - expectedFuel) < 0.001f)), delegate
			{
				if (!EligibleChest(chest, chestView) || !inv.RemoveItem(item, 1))
				{
					throw new InvalidOperationException("Source removal was rejected.");
				}
				Persist(chest, chestView);
			}, () => Owned(station) && Owned(chestView) && inv.CountItems(sharedName, -1, true) == beforeCount - 1, delegate
			{
				if (!Owned(station))
				{
					throw new InvalidOperationException("Cannot restore a processor owned by another peer.");
				}
				if (fuel)
				{
					SetFuel.Invoke(smelter, new object[1] { beforeFuel });
				}
				else
				{
					zdo.Set(slotKey, oldSlot);
					zdo.Set(ZDOVars.s_queued, beforeQueue, false);
					zdo.Set(ZDOVars.s_cheatedQueued, oldCheated);
				}
			}, delegate
			{
				Restore(chest, chestView, chestBefore);
			});
		}

		private unsafe static void Process(ZDOID stationId, List<ZDOID> chests, float range, int maxFuel, int maxOre, int reserveFuel, int reserveOre, Action<string> log)
		{
			//IL_0000: 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_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: 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_00e4: 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_0102: 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)
			GameObject val = Instance(stationId);
			ZNetView val2 = View(val);
			Smelter val3 = (((Object)(object)val == (Object)null) ? null : val.GetComponent<Smelter>());
			if (!Owned(val2) || (Object)(object)val3 == (Object)null)
			{
				return;
			}
			int i = 0;
			int j = 0;
			for (int k = 0; k < chests.Count; k++)
			{
				GameObject val4 = Instance(chests[k]);
				Container val5 = (((Object)(object)val4 == (Object)null) ? null : val4.GetComponent<Container>());
				ZNetView val6 = View(val4);
				if (!EligibleChest(val5, val6))
				{
					continue;
				}
				Vector3 val7 = val4.transform.position - val.transform.position;
				if (((Vector3)(ref val7)).sqrMagnitude > range * range)
				{
					continue;
				}
				Player localPlayer = Player.m_localPlayer;
				string text = ProcessChestHandoff.AccessBlock(val5, ((Object)(object)localPlayer == (Object)null) ? 0 : localPlayer.GetPlayerID());
				if (text != null)
				{
					string[] obj = new string[6] { "PROCESS WAIT station=", null, null, null, null, null };
					ZDOID val8 = stationId;
					obj[1] = ((object)(*(ZDOID*)(&val8))/*cast due to .constrained prefix*/).ToString();
					obj[2] = " chest=";
					obj[3] = ((object)chests[k]/*cast due to .constrained prefix*/).ToString();
					obj[4] = " reason=";
					obj[5] = text;
					log(string.Concat(obj));
					continue;
				}
				if (LoadContainer == null)
				{
					throw new InvalidOperationException("Container refresh API unavailable.");
				}
				LoadContainer.Invoke(val5, null);
				if (!EligibleChest(val5, val6))
				{
					continue;
				}
				for (; i < maxFuel; i++)
				{
					if (!((Object)(object)val3.m_fuelItem != (Object)null))
					{
						break;
					}
					if (!Feed(val3, val2, val5, val6, val3.m_fuelItem.m_itemData.m_shared.m_name, null, reserveFuel, fuel: true))
					{
						break;
					}
				}
				if (val3.m_conversion == null)
				{
					continue;
				}
				for (int l = 0; l < val3.m_conversion.Count; l++)
				{
					if (j >= maxOre)
					{
						break;
					}
					ItemConversion val9 = val3.m_conversion[l];
					if (val9 == null || (Object)(object)val9.m_from == (Object)null)
					{
						continue;
					}
					for (; j < maxOre; j++)
					{
						if (!Feed(val3, val2, val5, val6, val9.m_from.m_itemData.m_shared.m_name, ((Object)((Component)val9.m_from).gameObject).name, reserveOre, fuel: false))
						{
							break;
						}
					}
				}
			}
			if (i + j > 0)
			{
				string[] obj2 = new string[6] { "FED owner-verified station=", null, null, null, null, null };
				ZDOID val8 = stationId;
				obj2[1] = ((object)(*(ZDOID*)(&val8))/*cast due to .constrained prefix*/).ToString();
				obj2[2] = " fuel+=";
				obj2[3] = i.ToString();
				obj2[4] = " input+=";
				obj2[5] = j.ToString();
				log(string.Concat(obj2));
			}
		}

		internal static bool Store(ZDOID dropId, ZDOID targetId, float range, Action<string> log)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return Store(dropId, targetId, range, log, null);
		}

		private static bool RejectStore(Action<string> rejected, string stage)
		{
			rejected?.Invoke("transfer_rejected:" + stage);
			return false;
		}

		private static bool SavedDropStack(ZNetView view, ItemData data, int expected)
		{
			if (!Owned(view))
			{
				return false;
			}
			ZDO zDO = view.GetZDO();
			byte[] byteArray = zDO.GetByteArray(ZDOVars.s_itemData, (byte[])null);
			if (byteArray == null || byteArray.Length <= 2)
			{
				return false;
			}
			ItemData obj = data.Clone();
			obj.m_stack = -1;
			ItemDrop.LoadFromZDO(obj, zDO, -1);
			return obj.m_stack == expected;
		}

		internal unsafe static bool Store(ZDOID dropId, ZDOID targetId, float range, Action<string> log, Action<string> rejected)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Invalid comparison between Unknown and I4
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Instance(dropId);
			GameObject val2 = Instance(targetId);
			ItemDrop drop = (((Object)(object)val == (Object)null) ? null : val.GetComponent<ItemDrop>());
			Container chest = (((Object)(object)val2 == (Object)null) ? null : val2.GetComponent<Container>());
			ZNetView dropView = View(val);
			ZNetView chestView = View(val2);
			if (!Owned(dropView))
			{
				return RejectStore(rejected, "drop_not_owned");
			}
			if (!EligibleChest(chest, chestView))
			{
				return RejectStore(rejected, "chest_unavailable");
			}
			if ((Object)(object)drop == (Object)null || SaveDrop == null)
			{
				return RejectStore(rejected, "drop_save_unavailable");
			}
			ItemData data = drop.m_itemData;
			if (data == null || data.m_shared == null)
			{
				return RejectStore(rejected, "drop_data_unavailable");
			}
			if (data.m_stack <= 0)
			{
				dropView.Destroy();
				return false;
			}
			if (!GroundStoreRules.IsEligible(dropView.GetZDO().GetBool(ZDOVars.s_piece, false), data.m_shared.m_maxStackSize, (int)data.m_shared.m_itemType == 2))
			{
				return RejectStore(rejected, "drop_excluded");
			}
			Vector3 val3 = val.transform.position - val2.transform.position;
			if (((Vector3)(ref val3)).sqrMagnitude > range * range)
			{
				return RejectStore(rejected, "outside_range");
			}
			Inventory inv = chest.GetInventory();
			string name = data.m_shared.m_name;
			int beforeCount = inv.CountItems(name, -1, true);
			int stack = data.m_stack;
			if (beforeCount <= 0 || !inv.CanAddItem(data, stack))
			{
				return RejectStore(rejected, "chest_match_or_capacity_changed");
			}
			byte[] before = Bytes(inv);
			string stage = "destination_ownership";
			if (!TransferSafety.Commit(delegate
			{
				if (!Owned(dropView) || !EligibleChest(chest, chestView))
				{
					throw new InvalidOperationException("Ownership changed.");
				}
				ItemData val5 = data.Clone();
				val5.m_stack = stack;
				stage = "destination_add";
				if (!inv.AddItem(val5))
				{
					throw new InvalidOperationException("Target chest rejected the stack.");
				}
				stage = "destination_save";
				Persist(chest, chestView);
			}, delegate
			{
				stage = "destination_verify";
				return Owned(chestView) && inv.CountItems(name, -1, true) == beforeCount + stack;
			}, delegate
			{
				stage = "source_ownership_or_count";
				if (!Owned(dropView) || data.m_stack != stack)
				{
					throw new InvalidOperationException("Ground stack changed.");
				}
				stage = "source_save";
				data.m_stack = 0;
				SaveDrop.Invoke(drop, null);
			}, delegate
			{
				stage = "source_verify";
				return Owned(dropView) && data.m_stack == 0 && SavedDropStack(dropView, data, 0);
			}, delegate
			{
				Restore(chest, chestView, before);
			}, delegate
			{
				if (!Owned(dropView))
				{
					throw new InvalidOperationException("Cannot restore another peer's ground item.");
				}
				data.m_stack = stack;
				SaveDrop.Invoke(drop, null);
				if (!SavedDropStack(dropView, data, stack))
				{
					throw new InvalidOperationException("Ground item rollback save was not verified.");
				}
			}))
			{
				return RejectStore(rejected, stage);
			}
			try
			{
				dropView.Destroy();
			}
			catch
			{
				EmptyDrops.Add(dropId);
			}
			string[] obj2 = new string[8]
			{
				"STORED owner-verified item=",
				name,
				" count=",
				stack.ToString(),
				" drop=",
				null,
				null,
				null
			};
			ZDOID val4 = dropId;
			obj2[5] = ((object)(*(ZDOID*)(&val4))/*cast due to .constrained prefix*/).ToString();
			obj2[6] = " chest=";
			val4 = targetId;
			obj2[7] = ((object)(*(ZDOID*)(&val4))/*cast due to .constrained prefix*/).ToString();
			log(string.Concat(obj2));
			return true;
		}
	}
	internal static class ProcessChestHandoff
	{
		internal const string ReadyRpc = "RHSQOL_ProcessChestReady_v1";

		internal const string JobRpc = "RHSQOL_ProcessChestHandoff_v1";

		internal const string ResultRpc = "RHSQOL_ProcessChestResult_v1";

		private static readonly Dictionary<ZDOID, int> Seen = new Dictionary<ZDOID, int>();

		private static readonly MethodInfo LoadChest = AccessTools.Method(typeof(Container), "CheckForChanges", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo SaveChest = AccessTools.Method(typeof(Container), "Save", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo CheckAccess = AccessTools.Method(typeof(Container), "CheckAccess", new Type[1] { typeof(long) }, (Type[])null);

		private static readonly FieldInfo WardAreas = AccessTools.Field(typeof(PrivateArea), "m_allAreas");

		private static readonly MethodInfo WardEnabled = AccessTools.Method(typeof(PrivateArea), "IsEnabled", Type.EmptyTypes, (Type[])null);

		private static readonly MethodInfo WardInside = AccessTools.Method(typeof(PrivateArea), "IsInside", new Type[2]
		{
			typeof(Vector3),
			typeof(float)
		}, (Type[])null);

		private static readonly MethodInfo WardPermitted = AccessTools.Method(typeof(PrivateArea), "IsPermitted", new Type[1] { typeof(long) }, (Type[])null);

		internal static void Clear()
		{
			Seen.Clear();
		}

		internal static string AccessBlock(Container chest, long playerId)
		{
			//IL_0010: 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_005b: Invalid comparison between Unknown and I4
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Invalid comparison between Unknown and I4
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)chest == (Object)null)
			{
				return "container_missing";
			}
			if ((int)chest.m_privacy == 0)
			{
				if (playerId == 0L || CheckAccess == null)
				{
					return "private_access_unavailable";
				}
				if (!(bool)CheckAccess.Invoke(chest, new object[1] { playerId }))
				{
					return "private_access_denied";
				}
			}
			else if ((int)chest.m_privacy != 1 && (int)chest.m_privacy != 2)
			{
				return "unknown_privacy";
			}
			if (!chest.m_checkGuardStone)
			{
				return null;
			}
			if (WardAreas == null || WardEnabled == null || WardInside == null || WardPermitted == null)
			{
				return "ward_access_unavailable";
			}
			if (!(WardAreas.GetValue(null) is IEnumerable enumerable))
			{
				return "ward_access_unavailable";
			}
			bool flag = false;
			foreach (object item in enumerable)
			{
				PrivateArea val = (PrivateArea)((item is PrivateArea) ? item : null);
				if (!((Object)(object)val == (Object)null) && (bool)WardEnabled.Invoke(val, null) && (bool)WardInside.Invoke(val, new object[2]
				{
					((Component)chest).transform.position,
					0f
				}))
				{
					if (playerId == 0L)
					{
						return "ward_access_unavailable";
					}
					Piece component = ((Component)val).GetComponent<Piece>();
					if ((Object)(object)component == (Object)null)
					{
						return "ward_access_unavailable";
					}
					if (component.GetCreator() == playerId || (bool)WardPermitted.Invoke(val, new object[1] { playerId }))
					{
						return null;
					}
					flag = true;
				}
			}
			if (!flag)
			{
				return null;
			}
			return "ward_denied";
		}

		internal static bool HasInputs(Smelter smelter, ZDO station, Inventory inv, int reserveFuel, int reserveOre)
		{
			if ((Object)(object)smelter == (Object)null || station == null || inv == null)
			{
				return false;
			}
			if ((Object)(object)smelter.m_fuelItem != (Object)null && smelter.m_fuelItem.m_itemData != null && Math.Ceiling(station.GetFloat(ZDOVars.s_fuel, 0f)) < (double)smelter.m_maxFuel && inv.CountItems(smelter.m_fuelItem.m_itemData.m_shared.m_name, -1, true) > reserveFuel)
			{
				return true;
			}
			if (station.GetInt(ZDOVars.s_queued, 0) >= smelter.m_maxOre || smelter.m_conversion == null)
			{
				return false;
			}
			foreach (ItemConversion item in smelter.m_conversion)
			{
				if (item != null && (Object)(object)item.m_from != (Object)null && item.m_from.m_itemData != null && inv.CountItems(item.m_from.m_itemData.m_shared.m_name, -1, true) > reserveOre)
				{
					return true;
				}
			}
			return false;
		}

		private static bool ReadyToGrant(Container chest, ZNetView chestView, ZNetView stationView, long recipient, long playerId, float range, long deadline)
		{
			//IL_0040: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			if (StoreLease.IsLive(ZNet.instance.GetTime().Ticks, deadline) && OwnerAutomation.EligibleChest(chest, chestView) && stationView.IsValid() && stationView.GetZDO().GetOwner() == recipient)
			{
				Vector3 val = ((Component)stationView).transform.position - ((Component)chestView).transform.position;
				if (((Vector3)(ref val)).sqrMagnitude <= range * range)
				{
					return AccessBlock(chest, playerId) == null;
				}
			}
			return false;
		}

		internal static string Handle(ZPackage pkg, Action<long, ZDOID> replicate, out ZDOID chestId, out int token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_0044: 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_004c: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: 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_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_036b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Expected O, but got Unknown
			//IL_03fb: Unknown result type (might be due to invalid IL or missing references)
			chestId = ZDOID.None;
			token = 0;
			try
			{
				if (pkg == null || (Object)(object)ZNet.instance == (Object)null || (Object)(object)ZNetScene.instance == (Object)null)
				{
					return "not_loaded";
				}
				pkg.SetPos(0);
				ZDOID val = pkg.ReadZDOID();
				chestId = pkg.ReadZDOID();
				token = pkg.ReadInt();
				long num = pkg.ReadLong();
				long num2 = pkg.ReadLong();
				long playerId = pkg.ReadLong();
				float num3 = pkg.ReadSingle();
				int num4 = pkg.ReadInt();
				int num5 = pkg.ReadInt();
				long ticks = ZNet.instance.GetTime().Ticks;
				if (((ZDOID)(ref val)).IsNone() || ((ZDOID)(ref chestId)).IsNone() || val == chestId || token <= 0 || num2 == 0L || float.IsNaN(num3) || float.IsInfinity(num3) || num3 <= 0f || num3 > 64f || num4 < 0 || num4 > 999 || num5 < 0 || num5 > 999 || !StoreLease.IsLive(ticks, num) || num - ticks > 100000000)
				{
					return "invalid_or_expired";
				}
				if (Seen.TryGetValue(chestId, out var value) && value >= token)
				{
					return "replayed";
				}
				if (Seen.Count > 4096)
				{
					Seen.Clear();
				}
				Seen[chestId] = token;
				GameObject val2 = ZNetScene.instance.FindInstance(val);
				GameObject val3 = ZNetScene.instance.FindInstance(chestId);
				ZNetView val4 = (((Object)(object)val2 == (Object)null) ? null : val2.GetComponent<ZNetView>());
				ZNetView val5 = (((Object)(object)val3 == (Object)null) ? null : val3.GetComponent<ZNetView>());
				Smelter val6 = (((Object)(object)val2 == (Object)null) ? null : val2.GetComponent<Smelter>());
				Container val7 = (((Object)(object)val3 == (Object)null) ? null : val3.GetComponent<Container>());
				if ((Object)(object)val4 == (Object)null || !val4.IsValid() || (Object)(object)val6 == (Object)null)
				{
					return "station_not_loaded";
				}
				if (val4.GetZDO().GetOwner() != num2)
				{
					return "station_owner_changed";
				}
				if (!OwnerAutomation.EligibleChest(val7, val5))
				{
					return "chest_unavailable";
				}
				if ((Object)(object)((Component)val7).GetComponent<TombStone>() != (Object)null || ((Object)val3).name.IndexOf("private", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return "chest_excluded";
				}
				if (val5.GetZDO().GetOwner() == num2)
				{
					return "already_owned";
				}
				Vector3 val8 = val2.transform.position - val3.transform.position;
				if (((Vector3)(ref val8)).sqrMagnitude > num3 * num3)
				{
					return "outside_range";
				}
				string text = AccessBlock(val7, playerId);
				if (text != null)
				{
					return text;
				}
				if (LoadChest == null || SaveChest == null || replicate == null)
				{
					return "handoff_api_unavailable";
				}
				LoadChest.Invoke(val7, null);
				if (!OwnerAutomation.EligibleChest(val7, val5))
				{
					return "chest_changed";
				}
				Inventory inventory = val7.GetInventory();
				if (!HasInputs(val6, val4.GetZDO(), inventory, num4, num5))
				{
					return "no_needed_inputs";
				}
				SaveChest.Invoke(val7, null);
				ZPackage val9 = new ZPackage();
				inventory.Save(val9);
				byte[] array = val9.GetArray();
				byte[] byteArray = val5.GetZDO().GetByteArray(ZDOVars.s_items, (byte[])null);
				if (byteArray == null || array.Length != byteArray.Length)
				{
					return "save_not_verified";
				}
				for (int i = 0; i < byteArray.Length; i++)
				{
					if (byteArray[i] != array[i])
					{
						return "save_not_verified";
					}
				}
				if (!ReadyToGrant(val7, val5, val4, num2, playerId, num3, num))
				{
					return "state_changed";
				}
				replicate(num2, chestId);
				if (!ReadyToGrant(val7, val5, val4, num2, playerId, num3, num))
				{
					return "state_changed";
				}
				val5.GetZDO().SetOwner(num2);
				return (val5.GetZDO().GetOwner() == num2) ? "granted" : "grant_not_verified";
			}
			catch (Exception ex)
			{
				return "handoff_error:" + ex.GetType().Name;
			}
		}
	}
	internal static class StoreLease
	{
		internal const long DurationTicks = 100000000L;

		internal const long QuietTicks = 30000000L;

		internal static bool IsLive(long now, long deadline)
		{
			if (deadline > 0)
			{
				return now < deadline;
			}
			return false;
		}

		internal static bool CanDispatch(long now, long previousDeadline)
		{
			if (previousDeadline > 0)
			{
				return now >= previousDeadline + 30000000;
			}
			return true;
		}

		internal static bool Matches(int token, long owner, int reportedToken, long sender)
		{
			if (token > 0 && token == reportedToken)
			{
				return owner == sender;
			}
			return false;
		}
	}
	internal static class TransferSafety
	{
		internal static bool Commit(Action destination, Func<bool> destinationAccepted, Action source, Func<bool> sourceCommitted, Action restoreDestination, Action restoreSource)
		{
			bool flag = false;
			bool flag2 = false;
			try
			{
				flag = true;
				destination();
				if (!destinationAccepted())
				{
					throw new InvalidOperationException("Destination did not accept the transfer.");
				}
				flag2 = true;
				source();
				if (!sourceCommitted())
				{
					throw new InvalidOperationException("Source did not commit the transfer.");
				}
				return true;
			}
			catch (Exception ex)
			{
				Exception ex2 = null;
				if (flag2)
				{
					try
					{
						restoreSource();
					}
					catch (Exception ex3)
					{
						ex2 = ex3;
					}
				}
				if (flag)
				{
					try
					{
						restoreDestination();
					}
					catch (Exception ex4)
					{
						if (ex2 == null)
						{
							ex2 = ex4;
						}
					}
				}
				if (ex2 != null)
				{
					throw new InvalidOperationException("Transfer rollback failed; automation is paused for these objects.", new AggregateException(ex, ex2));
				}
				return false;
			}
		}
	}
}
namespace RustyHeathens.Backpacks
{
	internal sealed class BackpackDeathLocation
	{
		internal Vector3 DeathPoint;

		internal ZDOID GraveId = ZDOID.None;

		internal Vector3 GravePoint;
	}
	internal enum DeathLocationRead
	{
		Legacy,
		Valid,
		Invalid
	}
	internal static class BackpackDeathPlacement
	{
		internal const string AnchorKey = "RHSQOL_RustyBackpack_DeathAnchor";

		internal const float GraveSpacing = 1.25f;

		private const int WireMarker = 1380467249;

		internal static bool Finite(Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if (Coordinate(point.x) && Coordinate(point.y))
			{
				return Coordinate(point.z);
			}
			return false;
		}

		private static bool Coordinate(float value)
		{
			if (!float.IsNaN(value) && !float.IsInfinity(value))
			{
				return Math.Abs(value) < 100000f;
			}
			return false;
		}

		internal static Vector3 Beside(Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			return point + Vector3.right * 1.25f;
		}

		internal static void Write(ZPackage report, ZDOID character, BackpackDeathLocation location)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			report.Write(1380467249);
			report.Write(character);
			report.Write(location.DeathPoint);
			report.Write(location.GraveId);
			report.Write(location.GravePoint);
		}

		internal static DeathLocationRead Read(ZPackage report, ZDOID character, out BackpackDeathLocation location)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: 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_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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
			location = null;
			if (report.GetPos() == report.Size())
			{
				return DeathLocationRead.Legacy;
			}
			try
			{
				if (report.ReadInt() != 1380467249 || report.ReadZDOID() != character)
				{
					return DeathLocationRead.Invalid;
				}
				BackpackDeathLocation backpackDeathLocation = new BackpackDeathLocation
				{
					DeathPoint = report.ReadVector3(),
					GraveId = report.ReadZDOID(),
					GravePoint = report.ReadVector3()
				};
				if (report.GetPos() != report.Size() || !Finite(backpackDeathLocation.DeathPoint) || !Finite(backpackDeathLocation.GravePoint))
				{
					return DeathLocationRead.Invalid;
				}
				if (!((ZDOID)(ref backpackDeathLocation.GraveId)).IsNone())
				{
					Vector3 val = backpackDeathLocation.GravePoint - backpackDeathLocation.DeathPoint;
					if (((Vector3)(ref val)).sqrMagnitude > 16f)
					{
						return DeathLocationRead.Invalid;
					}
				}
				location = backpackDeathLocation;
				return DeathLocationRead.Valid;
			}
			catch
			{
				return DeathLocationRead.Invalid;
			}
		}

		internal static bool IsInventoryGrave(ZDO grave, long playerId)
		{
			if (grave != null && grave.IsValid() && playerId != 0L && grave.GetPrefab() == StringExtensionMethods.GetStableHashCode("Player_tombstone") && grave.GetLong(ZDOVars.s_owner, 0L) == playerId && !grave.GetBool("RHSQOL_RustyBackpack_Grave", false))
			{
				return !grave.GetString(ZDOVars.s_ownerName, "").EndsWith(" - Rusty Backpack", StringComparison.Ordinal);
			}
			return false;
		}

		internal static Vector3 Resolve(BackpackDeathLocation location, Vector3 frozenDeathPoint, ZDO grave, long playerId, out ZDOID anchor)
		{
			//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_000f: 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_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_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_0029: 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_0052: 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_005b: 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_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)
			anchor = ZDOID.None;
			if (location == null)
			{
				return frozenDeathPoint;
			}
			if (((ZDOID)(ref location.GraveId)).IsNone())
			{
				return location.DeathPoint;
			}
			if (grave != null)
			{
				if (grave.m_uid != location.GraveId || !IsInventoryGrave(grave, playerId) || !Finite(grave.GetPosition()))
				{
					return location.DeathPoint;
				}
				anchor = grave.m_uid;
				return Beside(grave.GetPosition());
			}
			anchor = location.GraveId;
			return Beside(location.GravePoint);
		}
	}
}
namespace RustyHeathens.ServerQoL
{
	internal static class AutoDoorsModule
	{
		private sealed class TrackedDoor
		{
			internal ZDO Zdo;

			internal float CloseAt;
		}

		private static readonly HashSet<int> DoorPrefabHashes = new HashSet<int>();

		private static readonly Dictionary<ZDOID, TrackedDoor> Tracked = new Dictionary<ZDOID, TrackedDoor>();

		private static readonly List<ZDOID> ScratchKeys = new List<ZDOID>();

		private static bool prefabRegistryReady;

		private static float nextTick;

		internal static void Clear()
		{
			DoorPrefabHashes.Clear();
			Tracked.Clear();
			ScratchKeys.Clear();
			prefabRegistryReady = false;
			nextTick = 0f;
		}

		internal static void Tick()
		{
			//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_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if (!Plugin.IsServer() || !instance.DoorsEnabled)
			{
				if (Tracked.Count > 0)
				{
					Tracked.Clear();
				}
				return;
			}
			EnsurePrefabRegistry();
			if (!prefabRegistryReady)
			{
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup < nextTick)
			{
				return;
			}
			nextTick = realtimeSinceStartup + 0.2f;
			ScratchKeys.Clear();
			foreach (KeyValuePair<ZDOID, TrackedDoor> item in Tracked)
			{
				ScratchKeys.Add(item.Key);
			}
			for (int i = 0; i < ScratchKeys.Count; i++)
			{
				ZDOID key = ScratchKeys[i];
				if (!Tracked.TryGetValue(key, out var value))
				{
					continue;
				}
				ZDO zdo = value.Zdo;
				if (zdo == null || !zdo.IsValid())
				{
					Tracked.Remove(key);
					continue;
				}
				if (!DoorPrefabHashes.Contains(zdo.GetPrefab()))
				{
					Tracked.Remove(key);
					continue;
				}
				int num = zdo.GetInt(ZDOVars.s_state, 0);
				if (num == 0)
				{
					Tracked.Remove(key);
				}
				else
				{
					if (realtimeSinceStartup < value.CloseAt)
					{
						continue;
					}
					try
					{
						zdo.Set(ZDOVars.s_state, 0, true);
						if (ZDOMan.instance != null)
						{
							ZDOMan.instance.ForceSendZDO(zdo.m_uid);
						}
						instance.LogDoorEvent("CLOSED", zdo, num);
						Tracked.Remove(key);
					}
					catch (Exception ex)
					{
						instance.LogDoorError("Close failed for " + SafeZdoId(zdo) + ": " + ex.Message);
						value.CloseAt = realtimeSinceStartup + 2f;
					}
				}
			}
		}

		internal static void ObserveZdo(ZDO zdo)
		{
			//IL_0073: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance == (Object)null || zdo == null || !Plugin.IsServer() || !instance.DoorsEnabled)
			{
				return;
			}
			EnsurePrefabRegistry();
			if (prefabRegistryReady && zdo.IsValid() && DoorPrefabHashes.Contains(zdo.GetPrefab()))
			{
				int num = zdo.GetInt(ZDOVars.s_state, 0);
				if (num == 0)
				{
					Tracked.Remove(zdo.m_uid);
					return;
				}
				if (Tracked.TryGetValue(zdo.m_uid, out var value))
				{
					value.Zdo = zdo;
					return;
				}
				TrackedDoor trackedDoor = new TrackedDoor();
				trackedDoor.Zdo = zdo;
				trackedDoor.CloseAt = Time.realtimeSinceStartup + instance.DoorDelay;
				Tracked[zdo.m_uid] = trackedDoor;
				instance.LogDoorEvent("OPEN", zdo, num);
			}
		}

		internal static void ObserveDoor(Door door)
		{
			if ((Object)(object)door == (Object)null)
			{
				return;
			}
			try
			{
				ZNetView component = ((Component)door).GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && component.IsValid())
				{
					ObserveZdo(component.GetZDO());
				}
			}
			catch
			{
			}
		}

		private static void EnsurePrefabRegistry()
		{
			if (prefabRegistryReady || (Object)(object)ZNetScene.instance == (Object)null || ZNetScene.instance.m_prefabs == null)
			{
				return;
			}
			DoorPrefabHashes.Clear();
			List<GameObject> prefabs = ZNetScene.instance.m_prefabs;
			for (int i = 0; i < prefabs.Count; i++)
			{
				GameObject val = prefabs[i];
				if (!((Object)(object)val == (Object)null))
				{
					Door val2 = null;
					try
					{
						val2 = val.GetComponentInChildren<Door>();
					}
					catch
					{
					}
					if (!((Object)(object)val2 == (Object)null) && !val2.m_canNotBeClosed && !((Object)(object)val2.m_keyItem != (Object)null))
					{
						DoorPrefabHashes.Add(StringExtensionMethods.GetStableHashCode(((Object)val).name));
					}
				}
			}
			if (DoorPrefabHashes.Count > 0)
			{
				prefabRegistryReady = true;
				Plugin instance = Plugin.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.LogDoorRegistry(DoorPrefabHashes.Count);
				}
			}
		}

		private static string SafeZdoId(ZDO zdo)
		{
			try
			{
				return (zdo == null) ? "unknown" : ((object)Unsafe.As<ZDOID, ZDOID>(ref zdo.m_uid)/*cast due to .constrained prefix*/).ToString();
			}
			catch
			{
				return "unknown";
			}
		}
	}
	[HarmonyPatch(typeof(ZDO), "Deserialize")]
	internal static class AutoDoorsZdoDeserializePatch
	{
		private static void Postfix(ZDO __instance)
		{
			AutoDoorsModule.ObserveZdo(__instance);
		}
	}
	[HarmonyPatch(typeof(Door), "RPC_UseDoor")]
	internal static class AutoDoorsRpcPatch
	{
		private static void Postfix(Door __instance)
		{
			AutoDoorsModule.ObserveDoor(__instance);
		}
	}
	[HarmonyPatch(typeof(Door), "UpdateState")]
	internal static class AutoDoorsUpdateStatePatch
	{
		private static void Postfix(Door __instance)
		{
			AutoDoorsModule.ObserveDoor(__instance);
		}
	}
	internal static class AutoProcessModule
	{
		private sealed class Handoff
		{
			internal int Token;

			internal long Owner;

			internal long Deadline;

			internal ZDOID Station;
		}

		private static readonly Dictionary<ZDOID, Handoff> Handoffs = new Dictionary<ZDOID, Handoff>();

		private static int nextHandoffToken;

		private static readonly Dictionary<int, Container> BuildableContainerPrefabs = new Dictionary<int, Container>();

		private static readonly Dictionary<int, Smelter> ProcessorPrefabs = new Dictionary<int, Smelter>();

		private static readonly List<ZDO> DiscoveryObjects = new List<ZDO>();

		private static readonly List<ZDO> SectorObjects = new List<ZDO>();

		private static readonly List<ZDO> Nearby = new List<ZDO>();

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

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

		private static readonly HashSet<int> LoggedProcessorPrefabs = new HashSet<int>();

		private static readonly Dictionary<ZDOID, float> LastWaitLog = new Dictionary<ZDOID, float>();

		private static bool prefabMapsReady;

		private static bool registryLogged;

		private static float nextTick;

		private static float nextDiscoveryLog;

		internal static void Clear()
		{
			Handoffs.Clear();
			nextHandoffToken = 0;
			BuildableContainerPrefabs.Clear();
			ProcessorPrefabs.Clear();
			DiscoveryObjects.Clear();
			SectorObjects.Clear();
			Nearby.Clear();
			SeenStations.Clear();
			DiscoverySectorKeys.Clear();
			LoggedProcessorPrefabs.Clear();
			LastWaitLog.Clear();
			prefabMapsReady = false;
			registryLogged = false;
			nextTick = 0f;
			nextDiscoveryLog = 0f;
		}

		internal static void Tick()
		{
			//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_00c1: 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_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance == (Object)null || !Plugin.IsServer() || !instance.AutoProcessEnabledValue || !EnsurePrefabMaps() || ZDOMan.instance == null || (Object)(object)ZoneSystem.instance == (Object)null || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup < nextTick)
			{
				return;
			}
			nextTick = realtimeSinceStartup + 2f;
			List<ZNetPeer> peers = ZNet.instance.GetPeers();
			int peerCount = peers?.Count ?? 0;
			int num = 0;
			int num2 = 0;
			SeenStations.Clear();
			DiscoverySectorKeys.Clear();
			if (peers != null)
			{
				for (int i = 0; i < peers.Count; i++)
				{
					ZNetPeer val = peers[i];
					if (val == null)
					{
						continue;
					}
					Vector2s zone = ZoneSystem.GetZone(val.m_refPos);
					long item = ((long)zone.x << 32) ^ (uint)zone.y;
					if (!DiscoverySectorKeys.Add(item))
					{
						continue;
					}
					DiscoveryObjects.Clear();
					ZDOMan.instance.FindSectorObjects(zone, new SimulationDistance(1, 0, false), DiscoveryObjects, (List<ZDO>)null);
					num += DiscoveryObjects.Count;
					for (int j = 0; j < DiscoveryObjects.Count; j++)
					{
						ZDO val2 = DiscoveryObjects[j];
						if (val2 != null && val2.IsValid() && ProcessorPrefabs.TryGetValue(val2.GetPrefab(), out var value) && !((Object)(object)value == (Object)null) && SeenStations.Add(val2.m_uid))
						{
							num2++;
							try
							{
								ProcessStation(value, val2, instance);
							}
							catch (Exception ex)
							{
								instance.LogAutoProcessError("Dedicated-server processor pass failed: " + ex.Message);
							}
						}
					}
				}
			}
			DiscoveryObjects.Clear();
			DiscoverySectorKeys.Clear();
			if (realtimeSinceStartup >= nextDiscoveryLog)
			{
				nextDiscoveryLog = realtimeSinceStartup + 10f;
				instance.LogAutoProcessDiscovery(peerCount, num, num2);
			}
		}

		internal static void ProcessSmelter(Smelter smelter)
		{
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)smelter == (Object)null || !Plugin.IsServer() || !instance.AutoProcessEnabledValue || !EnsurePrefabMaps())
			{
				return;
			}
			ZNetView stationNetView = GetStationNetView(smelter);
			if (!((Object)(object)stationNetView == (Object)null) && stationNetView.IsValid())
			{
				ZDO zDO = stationNetView.GetZDO();
				if (zDO != null && zDO.IsValid())
				{
					ProcessStation(smelter, zDO, instance);
				}
			}
		}

		private static void ProcessStation(Smelter smelter, ZDO stationZdo, Plugin plugin)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			//IL_0142: 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_019f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)smelter == (Object)null || stationZdo == null || (Object)(object)plugin == (Object)null)
			{
				return;
			}
			try
			{
				int prefab = stationZdo.GetPrefab();
				if (LoggedProcessorPrefabs.Add(prefab))
				{
					plugin.LogAutoProcessStation(smelter, prefab);
				}
			}
			catch
			{
			}
			float autoProcessRangeValue = plugin.AutoProcessRangeValue;
			if (autoProcessRangeValue <= 0f)
			{
				return;
			}
			long stationCreator = stationZdo.GetLong(ZDOVars.s_creator, 0L);
			BuildNearbyList(stationZdo.GetPosition(), autoProcessRangeValue, stationCreator);
			if (Nearby.Count == 0)
			{
				LogWaitRateLimited(plugin, stationZdo, "no eligible buildable source chest within " + autoProcessRangeValue.ToString("0.#") + "m");
				return;
			}
			long owner = stationZdo.GetOwner();
			if (!OwnerAutomationBridge.CanRun(owner))
			{
				LogWaitRateLimited(plugin, stationZdo, "waiting for updated QoL on the processor owner; no items removed");
				return;
			}
			List<ZDOID> list = new List<ZDOID>();
			int num = 0;
			for (int i = 0; i < Nearby.Count; i++)
			{
				if (list.Count >= 64)
				{
					break;
				}
				ZDO val = Nearby[i];
				if (val.GetOwner() == owner)
				{
					list.Add(val.m_uid);
				}
				else if (num < 2 && RequestHandoff(stationZdo, val, autoProcessRangeValue, plugin))
				{
					num++;
				}
			}
			if (list.Count == 0)
			{
				LogWaitRateLimited(plugin, stationZdo, "waiting for a closed source chest handoff; updated QoL and loaded station/chest required on both owners; no items removed");
				return;
			}
			ZPackage val2 = new ZPackage();
			val2.Write(1);
			val2.Write(stationZdo.m_uid);
			val2.Write(autoProcessRangeValue);
			val2.Write(plugin.MaxFuelTransfersPerTickValue);
			val2.Write(plugin.MaxOreTransfersPerTickValue);
			val2.Write(plugin.LeaveAtLeastFuelValue);
			val2.Write(plugin.LeaveAtLeastOreValue);
			val2.Write(list.Count);
			for (int j = 0; j < list.Count; j++)
			{
				val2.Write(list[j]);
			}
			OwnerAutomationBridge.Dispatch(stationZdo, val2);
		}

		private static bool OwnerCanLoad(long owner, ZDO station, ZDO chest)
		{
			//IL_001b: 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_005f: 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_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			if (owner == ZDOMan.GetSessionID())
			{
				if ((Object)(object)ZNetScene.instance != (Object)null && (Object)(object)ZNetScene.instance.FindInstance(station.m_uid) != (Object)null)
				{
					return (Object)(object)ZNetScene.instance.FindInstance(chest.m_uid) != (Object)null;
				}
				return false;
			}
			ZNetPeer val = OwnerAutomationBridge.FindPeer(owner);
			if (val != null && val.IsReady() && ZNetScene.InActiveArea(station.GetPosition(), val.GetRefPos()))
			{
				return ZNetScene.InActiveArea(chest.GetPosition(), val.GetRefPos());
			}
			return false;
		}

		private static bool RequestHandoff(ZDO station, ZDO chest, float range, Plugin plugin)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: 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_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Expected O, but got Unknown
			//IL_013d: 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)
			long owner = station.GetOwner();
			long owner2 = chest.GetOwner();
			if (!OwnerAutomationBridge.CanHandoff(owner2) || !OwnerAutomationBridge.CanHandoff(owner) || !OwnerCanLoad(owner2, station, chest) || !OwnerCanLoad(owner, station, chest))
			{
				return false;
			}
			if (Math.Ceiling(station.GetFloat(ZDOVars.s_fuel, 0f)) >= (double)ProcessorPrefabs[station.GetPrefab()].m_maxFuel && station.GetInt(ZDOVars.s_queued, 0) >= ProcessorPrefabs[station.GetPrefab()].m_maxOre)
			{
				return false;
			}
			long ticks = ZNet.instance.GetTime().Ticks;
			if (Handoffs.TryGetValue(chest.m_uid, out var value) && !StoreLease.CanDispatch(ticks, value.Deadline))
			{
				return false;
			}
			if (nextHandoffToken == int.MaxValue)
			{
				return false;
			}
			long num = OwnerAutomationBridge.FindPeer(owner)?.m_playerID ?? 0;
			Handoff handoff = new Handoff
			{
				Token = ++nextHandoffToken,
				Owner = owner2,
				Deadline = ticks + 100000000,
				Station = station.m_uid
			};
			Handoffs[chest.m_uid] = handoff;
			ZPackage val = new ZPackage();
			val.Write(station.m_uid);
			val.Write(chest.m_uid);
			val.Write(handoff.Token);
			val.Write(handoff.Deadline);
			val.Write(owner);
			val.Write(num);
			val.Write(range);
			val.Write(plugin.LeaveAtLeastFuelValue);
			val.Write(plugin.LeaveAtLeastOreValue);
			if (OwnerAutomationBridge.DispatchHandoff(owner2, val))
			{
				return true;
			}
			handoff.Deadline = 0L;
			return false;
		}

		internal unsafe static void OnHandoffResult(long sender, ZPackage result)
		{
			//IL_0021: 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_003a: 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_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.IsServer() || (Object)(object)Plugin.Instance == (Object)null || result == null)
			{
				return;
			}
			try
			{
				result.SetPos(0);
				ZDOID val = result.ReadZDOID();
				int reportedToken = result.ReadInt();
				string text = result.ReadString();
				if (Handoffs.TryGetValue(val, out var value) && StoreLease.Matches(value.Token, value.Owner, reportedToken, sender))
				{
					ZDO val2 = ((ZDOMan.instance == null) ? null : ZDOMan.instance.GetZDO(value.Station));
					if (val2 != null)
					{
						Plugin instance = Plugin.Instance;
						ZDOID val3 = val;
						LogWaitRateLimited(instance, val2, "source chest " + ((object)(*(ZDOID*)(&val3))/*cast due to .constrained prefix*/).ToString() + " handoff=" + text);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Instance.LogAutoProcessError("Invalid chest handoff result: " + ex.Message);
			}
		}

		private static void BuildNearbyList(Vector3 stationPosition, float range, long stationCreator)
		{
			//IL_0029: 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_0035: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			Nearby.Clear();
			SectorObjects.Clear();
			if (ZDOMan.instance == null || (Object)(object)ZoneSystem.instance == (Object)null)
			{
				return;
			}
			Vector2s zone = ZoneSystem.GetZone(stationPosition);
			ZDOMan.instance.FindSectorObjects(zone, new SimulationDistance(1, 0, false), SectorObjects, (List<ZDO>)null);
			float num = range * range;
			for (int i = 0; i < SectorObjects.Count; i++)
			{
				ZDO val = SectorObjects[i];
				if (val == null || !val.IsValid() || !BuildableContainerPrefabs.TryGetValue(val.GetPrefab(), out var value) || (Object)(object)value == (Object)null || val.GetInt(ZDOVars.s_inUse, 0) != 0 || val.GetBool("RHSQOL_RustyBackpack", false) || val.GetBool("RHSQOL_RustyBackpack_Grave", false))
				{
					continue;
				}
				Vector3 val2 = val.GetPosition() - stationPosition;
				if (!(((Vector3)(ref val2)).sqrMagnitude > num))
				{
					long chestCreator = val.GetLong(ZDOVars.s_creator, 0L);
					if (CanUseContainer(value, stationCreator, chestCreator))
					{
						Nearby.Add(val);
					}
				}
			}
			SectorObjects.Clear();
		}

		private static bool CanUseContainer(Container prefab, long stationCreator, long chestCreator)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)prefab == (Object)null)
			{
				return false;
			}
			if ((int)prefab.m_privacy == 0)
			{
				if (stationCreator != 0L)
				{
					return chestCreator == stationCreator;
				}
				return false;
			}
			return true;
		}

		private static bool EnsurePrefabMaps()
		{
			if (prefabMapsReady)
			{
				return true;
			}
			if ((Object)(object)ZNetScene.instance == (Object)null || ZNetScene.instance.m_prefabs == null || ZNetScene.instance.m_prefabs.Count == 0)
			{
				return false;
			}
			if ((Object)(object)ObjectDB.instance == (Object)null || ObjectDB.instance.m_items == null || ObjectDB.instance.m_items.Count == 0)
			{
				return false;
			}
			ProcessorPrefabs.Clear();
			BuildableContainerPrefabs.Clear();
			for (int i = 0; i < ZNetScene.instance.m_prefabs.Count; i++)
			{
				GameObject val = ZNetScene.instance.m_prefabs[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Smelter val2 = val.GetComponent<Smelter>();
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = val.GetComponentInChildren<Smelter>();
				}
				if (!((Object)(object)val2 == (Object)null))
				{
					int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val).name);
					if (!ProcessorPrefabs.ContainsKey(stableHashCode))
					{
						ProcessorPrefabs.Add(stableHashCode, val2);
					}
				}
			}
			for (int j = 0; j < ObjectDB.instance.m_items.Count; j++)
			{
				GameObject val3 = ObjectDB.instance.m_items[j];
				if ((Object)(object)val3 == (Object)null)
				{
					continue;
				}
				ItemDrop component = val3.GetComponent<ItemDrop>();
				if ((Object)(object)component == (Object)null || component.m_itemData == null || component.m_itemData.m_shared == null)
				{
					continue;
				}
				PieceTable buildPieces = component.m_itemData.m_shared.m_buildPieces;
				if ((Object)(object)buildPieces == (Object)null || buildPieces.m_pieces == null)
				{
					continue;
				}
				for (int k = 0; k < buildPieces.m_pieces.Count; k++)
				{
					GameObject val4 = buildPieces.m_pieces[k];
					if ((Object)(object)val4 == (Object)null)
					{
						continue;
					}
					Container val5 = val4.GetComponent<Container>();
					if ((Object)(object)val5 == (Object)null)
					{
						val5 = val4.GetComponentInChildren<Container>();
					}
					if ((Object)(object)val5 == (Object)null || (Object)(object)val5.m_wagon != (Object)null || val5.m_autoDestroyEmpty)
					{
						continue;
					}
					string text = ((((Object)val4).name == null) ? "" : ((Object)val4).name);
					if (text.IndexOf("private", StringComparison.OrdinalIgnoreCase) < 0)
					{
						int stableHashCode2 = StringExtensionMethods.GetStableHashCode(text);
						if (!BuildableContainerPrefabs.ContainsKey(stableHashCode2))
						{
							BuildableContainerPrefabs.Add(stableHashCode2, val5);
						}
					}
				}
			}
			prefabMapsReady = ProcessorPrefabs.Count > 0 && BuildableContainerPrefabs.Count > 0;
			if (prefabMapsReady && !registryLogged)
			{
				registryLogged = true;
				Plugin instance = Plugin.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.LogAutoProcessRegistry(ProcessorPrefabs.Count, BuildableContainerPrefabs.Count);
				}
			}
			return prefabMapsReady;
		}

		private static void LogWaitRateLimited(Plugin plugin, ZDO stationZdo, string reason)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)plugin == (Object)null) && stationZdo != null)
			{
				float realtimeSinceStartup = Time.realtimeSinceStartup;
				if (!LastWaitLog.TryGetValue(stationZdo.m_uid, out var value) || !(realtimeSinceStartup - value < 10f))
				{
					LastWaitLog[stationZdo.m_uid] = realtimeSinceStartup;
					plugin.LogAutoProcessWait(stationZdo, reason);
				}
			}
		}

		private static ZNetView GetStationNetView(Smelter smelter)
		{
			if ((Object)(object)smelter == (Object)null)
			{
				return null;
			}
			ZNetView val = null;
			try
			{
				val = ((Component)smelter).GetComponent<ZNetView>();
				if ((Object)(object)val == (Object)null)
				{
					val = ((Component)smelter).GetComponentInParent<ZNetView>();
				}
			}
			catch
			{
			}
			return val;
		}
	}
	internal static class AutoStoreModule
	{
		private sealed class DropEntry
		{
			internal ZDOID Id;

			internal float RegisteredAt;

			internal float EarliestAttempt;

			internal int OwnerCursor;

			internal int PendingToken;

			internal long PendingOwner;

			internal long PendingDeadline;
		}

		private sealed class ChestSectorCacheEntry
		{
			internal float ExpiresAt;

			internal readonly List<ZDOID> ChestIds = new List<ZDOID>();
		}

		private static readonly List<DropEntry> Drops = new List<DropEntry>();

		private static readonly Dictionary<int, ItemDrop> ItemPrefabs = new Dictionary<int, ItemDrop>();

		private static readonly Dictionary<int, Container> BuildableContainerPrefabs = new Dictionary<int, Container>();

		private static readonly List<ZDO> SectorObjects = new List<ZDO>();

		private static readonly Dictionary<string, float> LastWaitLogByItem = new Dictionary<string, float>();

		private static readonly Dictionary<long, ChestSectorCacheEntry> ChestSectorCache = new Dictionary<long, ChestSectorCacheEntry>();

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

		private static float nextTick;

		private static float nextDiscovery;

		private static float nextDiscoveryLog;

		private static float nextPrune;

		private static int cursor;

		private static bool prefabMapsReady;

		private static bool registryLogged;

		private static int nextToken;

		internal static void Clear()
		{
			Drops.Clear();
			ItemPrefabs.Clear();
			BuildableContainerPrefabs.Clear();
			SectorObjects.Clear();
			LastWaitLogByItem.Clear();
			ChestSectorCache.Clear();
			DiscoverySectorKeys.Clear();
			nextTick = 0f;
			nextDiscovery = 0f;
			nextDiscoveryLog = 0f;
			nextPrune = 0f;
			cursor = 0;
			prefabMapsReady = false;
			registryLogged = false;
			nextToken = 0;
		}

		internal static void ObserveZdo(ZDO zdo)
		{
			if (zdo != null && EnsurePrefabMaps() && ItemPrefabs.ContainsKey(zdo.GetPrefab()))
			{
				RegisterDrop(zdo);
			}
		}

		internal static void RegisterDrop(ItemDrop drop)
		{
			if ((Object)(object)drop == (Object)null)
			{
				return;
			}
			try
			{
				ZNetView component = ((Component)drop).GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && component.IsValid())
				{
					ObserveZdo(component.GetZDO());
				}
			}
			catch
			{
			}
		}

		private static void RegisterDrop(ZDO zdo)
		{
			//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)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if (zdo == null || !zdo.IsValid() || !IsRecentGroundDrop(zdo))
			{
				return;
			}
			ZDOID uid = zdo.m_uid;
			for (int i = 0; i < Drops.Count; i++)
			{
				if (Drops[i] != null && Drops[i].Id == uid)
				{
					return;
				}
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			DropEntry dropEntry = new DropEntry();
			dropEntry.Id = uid;
			dropEntry.RegisteredAt = realtimeSinceStartup;
			dropEntry.EarliestAttempt = realtimeSinceStartup + 1f;
			Drops.Add(dropEntry);
		}

		internal static void Tick()
		{
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance == (Object)null || !Plugin.IsServer() || !instance.AutoStoreEnabledValue || !EnsurePrefabMaps())
			{
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup >= nextDiscovery)
			{
				nextDiscovery = realtimeSinceStartup + 8f;
				DiscoverNearbyDrops();
			}
			if (realtimeSinceStartup < nextTick)
			{
				return;
			}
			nextTick = realtimeSinceStartup + 0.5f;
			Prune(realtimeSinceStartup);
			if (Drops.Count == 0)
			{
				return;
			}
			int num = instance.AutoStoreMaxDropsPerTickValue;
			if (num > Drops.Count)
			{
				num = Drops.Count;
			}
			int count = Drops.Count;
			int num2 = 0;
			int num3 = 0;
			long now = (((Object)(object)ZNet.instance == (Object)null) ? 0 : ZNet.instance.GetTime().Ticks);
			while (num2 < count && num3 < num && Drops.Count > 0)
			{
				if (cursor >= Drops.Count)
				{
					cursor = 0;
				}
				DropEntry dropEntry = Drops[cursor];
				cursor++;
				num2++;
				if (dropEntry == null || realtimeSinceStartup < dropEntry.EarliestAttempt || !StoreLease.CanDispatch(now, dropEntry.PendingDeadline))
				{
					continue;
				}
				ZDO val = ((ZDOMan.instance == null) ? null : ZDOMan.instance.GetZDO(dropEntry.Id));
				if (val == null || !val.IsValid() || !HasActiveStoreClient(val))
				{
					continue;
				}
				num3++;
				bool flag = false;
				try
				{
					flag = TryStore(dropEntry, val, instance, realtimeSinceStartup);
				}
				catch (Exception ex)
				{
					instance.LogAutoStoreError("Ground-drop transfer failed: " + ex.Message);
				}
				if (flag)
				{
					int num4 = Drops.IndexOf(dropEntry);
					if (num4 >= 0)
					{
						if (num4 < cursor)
						{
							cursor--;
						}
						Drops.RemoveAt(num4);
						if (cursor < 0)
						{
							cursor = 0;
						}
					}
				}
				else
				{
					dropEntry.EarliestAttempt = Math.Max(dropEntry.EarliestAttempt, realtimeSinceStartup + 1f);
				}
			}
		}

		private static bool HasActiveStoreClient(ZDO drop)
		{
			if (CanOwnerLoad(drop, ZDOMan.GetSessionID()))
			{
				return true;
			}
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return false;
			}
			List<ZNetPeer> peers = ZNet.instance.GetPeers();
			if (peers == null)
			{
				return false;
			}
			for (int i = 0; i < peers.Count; i++)
			{
				ZNetPeer val = peers[i];
				if (val != null && OwnerAutomationBridge.CanStore(val.m_uid) && CanOwnerLoad(drop, val.m_uid))
				{
					return true;
				}
			}
			return false;
		}

		private static bool CanOwnerLoad(ZDO zdo, long owner)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (zdo == null)
			{
				return false;
			}
			if (owner == ZDOMan.GetSessionID())
			{
				if ((Object)(object)ZNetScene.instance != (Object)null)
				{
					return (Object)(object)ZNetScene.instance.FindInstance(zdo.m_uid) != (Object)null;
				}
				return false;
			}
			ZNetPeer val = OwnerAutomationBridge.FindPeer(owner);
			if (val != null && val.IsReady())
			{
				return ZNetScene.InActiveArea(zdo.GetPosition(), val.GetRefPos());
			}
			return false;
		}

		private static bool EnsurePrefabMaps()
		{
			if (prefabMapsReady)
			{
				return true;
			}
			if ((Object)(object)ZNetScene.instance == (Object)null || ZNetScene.instance.m_prefabs == null || ZNetScene.instance.m_prefabs.Count == 0)
			{
				return false;
			}
			if ((Object)(object)ObjectDB.instance == (Object)null || ObjectDB.instance.m_items == null || ObjectDB.instance.m_items.Count == 0)
			{
				return false;
			}
			ItemPrefabs.Clear();
			BuildableContainerPrefabs.Clear();
			for (int i = 0; i < ZNetScene.instance.m_prefabs.Count; i++)
			{
				GameObject val = ZNetScene.instance.m_prefabs[i];
				if (!((Object)(object)val == (Object)null))
				{
					int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val).name);
					ItemDrop val2 = val.GetComponent<ItemDrop>();
					if ((Object)(object)val2 == (Object)null)
					{
						val2 = val.GetComponentInChildren<ItemDrop>();
					}
					if ((Object)(object)val2 != (Object)null && !ItemPrefabs.ContainsKey(stableHashCode))
					{
						ItemPrefabs.Add(stableHashCode, val2);
					}
				}
			}
			for (int j = 0; j < ObjectDB.instance.m_items.Count; j++)
			{
				GameObject val3 = ObjectDB.instance.m_items[j];
				if ((Object)(object)val3 == (Object)null)
				{
					continue;
				}
				ItemDrop component = val3.GetComponent<ItemDrop>();
				if ((Object)(object)component == (Object)null || component.m_itemData == null || component.m_itemData.m_shared == null)
				{
					continue;
				}
				PieceTable buildPieces = component.m_itemData.m_shared.m_buildPieces;
				if ((Object)(object)buildPieces == (Object)null || buildPieces.m_pieces == null)
				{
					continue;
				}
				for (int k = 0; k < buildPieces.m_pieces.Count; k++)
				{
					GameObject val4 = buildPieces.m_pieces[k];
					if ((Object)(object)val4 == (Object)null)
					{
						continue;
					}
					Container val5 = val4.GetComponent<Container>();
					if ((Object)(object)val5 == (Object)null)
					{
						val5 = val4.GetComponentInChildren<Container>();
					}
					if ((Object)(object)val5 == (Object)null || (Object)(object)val5.m_wagon != (Object)null || val5.m_autoDestroyEmpty)
					{
						continue;
					}
					string text = ((((Object)val4).name == null) ? "" : ((Object)val4).name);
					if (text.IndexOf("private", StringComparison.OrdinalIgnoreCase) < 0)
					{
						int stableHashCode2 = StringExtensionMethods.GetStableHashCode(text);
						if (!BuildableContainerPrefabs.ContainsKey(stableHashCode2))
						{
							BuildableContainerPrefabs.Add(stableHashCode2, val5);
						}
					}
				}
			}
			if (BuildableContainerPrefabs.Count == 0)
			{
				for (int l = 0; l < ZNetScene.instance.m_prefabs.Count; l++)
				{
					GameObject val6 = ZNetScene.instance.m_prefabs[l];
					if ((Object)(object)val6 == (Object)null)
					{
						continue;
					}
					Piece val7 = val6.GetComponent<Piece>();
					if ((Object)(object)val7 == (Object)null)
					{
						val7 = val6.GetComponentInChildren<Piece>();
					}
					if ((Object)(object)val7 == (Object)null)
					{
						continue;
					}
					Container val8 = val6.GetComponent<Container>();
					if ((Object)(object)val8 == (Object)null)
					{
						val8 = val6.GetComponentInChildren<Container>();
					}
					if ((Object)(object)val8 == (Object)null || (Object)(object)val8.m_wagon != (Object)null || val8.m_autoDestroyEmpty)
					{
						continue;
					}
					string text2 = ((((Object)val6).name == null) ? "" : ((Object)val6).name);
					if (text2.IndexOf("private", StringComparison.OrdinalIgnoreCase) < 0)
					{
						int stableHashCode3 = StringExtensionMethods.GetStableHashCode(text2);
						if (!BuildableContainerPrefabs.ContainsKey(stableHashCode3))
						{
							BuildableContainerPrefabs.Add(stableHashCode3, val8);
						}
					}
				}
			}
			prefabMapsReady = ItemPrefabs.Count > 0 && BuildableContainerPrefabs.Count > 0;
			if (prefabMapsReady && !registryLogged)
			{
				registryLogged = true;
				Plugin instance = Plugin.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.LogAutoStoreRegistry(ItemPrefabs.Count, BuildableContainerPrefabs.Count);
				}
			}
			return prefabMapsReady;
		}

		private static void DiscoverNearbyDrops()
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: 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_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			if (ZDOMan.instance == null || (Object)(object)ZoneSystem.instance == (Object)null || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			List<ZNetPeer> peers = ZNet.instance.GetPeers();
			int peerCount = peers?.Count ?? 0;
			int num = 0;
			int num2 = 0;
			DiscoverySectorKeys.Clear();
			if (peers != null)
			{
				for (int i = 0; i < peers.Count; i++)
				{
					ZNetPeer val = peers[i];
					if (val == null)
					{
						continue;
					}
					Vector2s zone = ZoneSystem.GetZone(val.m_refPos);
					long item = SectorKey(zone);
					if (!DiscoverySectorKeys.Add(item))
					{
						continue;
					}
					SectorObjects.Clear();
					ZDOMan.instance.FindSectorObjects(zone, new SimulationDistance(1, 0, false), SectorObjects, (List<ZDO>)null);
					num += SectorObjects.Count;
					for (int j = 0; j < SectorObjects.Count; j++)
					{
						ZDO val2 = SectorObjects[j];
						if (val2 != null && val2.IsValid() && ItemPrefabs.ContainsKey(val2.GetPrefab()))
						{
							num2++;
							RegisterDrop(val2);
						}
					}
				}
			}
			SectorObjects.Clear();
			DiscoverySectorKeys.Clear();
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup >= nextDiscoveryLog)
			{
				nextDiscoveryLog = realtimeSinceStartup + 10f;
				Plugin instance = Plugin.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.LogAutoStoreDiscovery(peerCount, num, num2, Drops.Count);
				}
			}
		}

		private static bool TryStore(DropEntry entry, ZDO dropZdo, Plugin plugin, float now)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Invalid comparison between Unknown and I4
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: 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_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Expected O, but got Unknown
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: 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_01c7: Unknown result type (might be due to invalid IL or missing references)
			if (entry == null || dropZdo == null || (Object)(object)plugin == (Object)null)
			{
				return false;
			}
			long num = (((Object)(object)ZNet.instance == (Object)null) ? 0 : ZNet.instance.GetTime().Ticks);
			if (!StoreLease.CanDispatch(num, entry.PendingDeadline))
			{
				return false;
			}
			if (!ItemPrefabs.TryGetValue(dropZdo.GetPrefab(), out var value) || (Object)(object)value == (Object)null)
			{
				return false;
			}
			ItemData val = LoadItemData(value, dropZdo);
			if (val == null || val.m_shared == null)
			{
				return false;
			}
			bool isPiece = dropZdo.GetBool(ZDOVars.s_piece, false);
			bool isConsumable = (int)val.m_shared.m_itemType == 2;
			if (!ServerQoLRules.ShouldAutoStoreItem(plugin.AutoStoreEnabledValue, autoPickup: true, isPiece, val.m_shared.m_maxStackSize, isConsumable))
			{
				return false;
			}
			if (val.m_stack <= 0)
			{
				return false;
			}
			Vector3 position = dropZdo.GetPosition();
			float autoStoreMinPlayerDistanceValue = plugin.AutoStoreMinPlayerDistanceValue;
			bool playerInRange = autoStoreMinPlayerDistanceValue > 0f && IsAnyPeerInRange(position, autoStoreMinPlayerDistanceValue);
			if (ServerQoLRules.IsPlayerProtectionActive(now - entry.RegisteredAt, plugin.AutoStorePlayerProtectionSecondsValue, playerInRange))
			{
				return false;
			}
			if (!FindTargetDirect(entry, dropZdo, position, plugin.AutoStoreRangeValue, out var owner, out var candidates, out var diagnostic))
			{
				LogWaitRateLimited(plugin, val.m_shared.m_name, diagnostic, now);
				return false;
			}
			if (nextToken == int.MaxValue)
			{
				nextToken = 0;
			}
			entry.PendingToken = ++nextToken;
			entry.PendingOwner = owner;
			entry.PendingDeadline = num + 100000000;
			ZPackage val2 = new ZPackage();
			val2.Write(dropZdo.m_uid);
			val2.Write(entry.PendingToken);
			val2.Write(entry.PendingDeadline);
			val2.Write(plugin.AutoStoreRangeValue);
			val2.Write(candidates.Count);
			foreach (ZDOID item in candidates)
			{
				val2.Write(item);
			}
			if (!OwnerAutomationBridge.DispatchStore(owner, val2))
			{
				entry.PendingDeadline = 0L;
				LogWaitRateLimited(plugin, val.m_shared.m_name, "waiting for a connected AutoStore v3 chest owner", now);
			}
			entry.EarliestAttempt = now + 1f;
			return false;
		}

		private static bool FindTargetDirect(DropEntry entry, ZDO drop, Vector3 position, float range, out long owner, out List<ZDOID> candidates, out string diagnostic)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00af: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			owner = 0L;
			candidates = null;
			diagnostic = "no nearby eligible buildable chest";
			if (ZDOMan.instance == null || (Object)(object)ZoneSystem.instance == (Object)null || range <= 0f)
			{
				return false;
			}
			List<ZDO> list = new List<ZDO>();
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			foreach (ZDOID cachedChestId in GetCachedChestIds(ZoneSystem.GetZone(position), Time.realtimeSinceStartup))
			{
				ZDO zDO = ZDOMan.instance.GetZDO(cachedChestId);
				if (zDO == null || !zDO.IsValid() || !BuildableContainerPrefabs.ContainsKey(zDO.GetPrefab()))
				{
					continue;
				}
				Vector3 val = zDO.GetPosition() - position;
				if (((Vector3)(ref val)).sqrMagnitude > range * range)
				{
					continue;
				}
				num++;
				if (!zDO.GetBool("RHSQOL_RustyBackpack", false) && !zDO.GetBool("RHSQOL_RustyBackpack_Grave", false))
				{
					if (zDO.GetInt(ZDOVars.s_inUse, 0) != 0)
					{
						num2++;
					}
					else if (!OwnerAutomationBridge.CanStore(zDO.GetOwner()))
					{
						num3++;
					}
					else if (!CanOwnerLoad(drop, zDO.GetOwner()) || !CanOwnerLoad(zDO, zDO.GetOwner()))
					{
						num4++;
					}
					else
					{
						list.Add(zDO);
					}
				}
			}
			list.Sort(delegate(ZDO a, ZDO b)
			{
				//IL_0001: 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_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val2 = a.GetPosition() - position;
				float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
				val2 = b.GetPosition() - position;
				return sqrMagnitude.CompareTo(((Vector3)(ref val2)).sqrMagnitude);
			});
			List<long> list2 = new List<long>();
			foreach (ZDO item in list)
			{
				if (item.GetOwner() == drop.GetOwner())
				{
					list2.Add(drop.GetOwner());
					break;
				}
			}
			foreach (ZDO item2 in list)
			{
				if (!list2.Contains(item2.GetOwner()))
				{
					list2.Add(item2.GetOwner());
				}
			}
			if (list2.Count == 0)
			{
				diagnostic = "nearbyChests=" + num + " openChests=" + num2 + " ownersWithoutAutoStoreV3=" + num3 + " ownersOutsideLoadedArea=" + num4 + " range=" + range.ToString("0.#") + "m";
				return false;
			}
			owner = list2[entry.OwnerCursor % list2.Count];
			entry.OwnerCursor = (entry.OwnerCursor + 1) % list2.Count;
			candidates = new List<ZDOID>();
			foreach (ZDO item3 in list)
			{
				if (item3.GetOwner() == owner && candidates.Count < 64)
				{
					candidates.Add(item3.m_uid);
				}
			}
			return candidates.Count > 0;
		}

		internal unsafe static void OnResult(long sender, ZPackage result)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)