Decompiled source of AdvancedWard v0.3.2

BepInEx/plugins/AdvancedWard/AdvancedWard.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn.Extensions;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("AdvancedWard")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.3.2.0")]
[assembly: AssemblyInformationalVersion("0.3.2")]
[assembly: AssemblyProduct("AdvancedWard")]
[assembly: AssemblyTitle("AdvancedWard")]
[assembly: AssemblyVersion("0.3.2.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 AdvancedWard
{
	internal static class AreaMarker
	{
		private sealed class Owner
		{
			internal PrivateArea Ward;

			internal float Spacing;
		}

		private const int MaxSegments = 400;

		private static readonly FieldInfo SegmentsField = AccessTools.Field(typeof(CircleProjector), "m_segments");

		private static readonly MethodInfo CreateSegmentsMethod = AccessTools.Method(typeof(CircleProjector), "CreateSegments", (Type[])null, (Type[])null);

		private static readonly Dictionary<CircleProjector, Owner> Owners = new Dictionary<CircleProjector, Owner>();

		internal static PrivateArea PreviewWard;

		internal static WardState PreviewState;

		internal static IEnumerable<string> MissingMembers()
		{
			if (SegmentsField == null)
			{
				yield return "CircleProjector.m_segments";
			}
			if (CreateSegmentsMethod == null)
			{
				yield return "CircleProjector.CreateSegments()";
			}
		}

		internal static bool Draw(CircleProjector projector)
		{
			//IL_0185: 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_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)projector == (Object)null)
			{
				return true;
			}
			if (!Owners.TryGetValue(projector, out var value))
			{
				if (Owners.Count > 256)
				{
					CleanUp();
				}
				PrivateArea componentInParent = ((Component)projector).GetComponentInParent<PrivateArea>();
				value = new Owner
				{
					Ward = componentInParent,
					Spacing = Mathf.Max(0.5f, MathF.PI * 2f * Mathf.Max(1f, projector.m_radius) / (float)Mathf.Max(8, projector.m_nrOfSegments))
				};
				Owners[projector] = value;
			}
			WardInfo wardInfo = (((Object)(object)value.Ward != (Object)null) ? WardAccess.Get(value.Ward) : null);
			if (wardInfo == null)
			{
				return true;
			}
			WardInfo.Extents(((Object)(object)PreviewWard == (Object)(object)value.Ward && PreviewState != null) ? PreviewState : wardInfo.State, wardInfo.BaseRadius, out var shape, out var halfX, out var halfZ);
			if (shape == WardShape.Circle || SegmentsField == null || CreateSegmentsMethod == null)
			{
				projector.m_radius = halfX;
				projector.m_nrOfSegments = Mathf.Clamp(Mathf.RoundToInt(MathF.PI * 2f * halfX / value.Spacing), 8, 400);
				return true;
			}
			float num = 4f * (halfX + halfZ);
			projector.m_nrOfSegments = Mathf.Clamp(Mathf.RoundToInt(num / value.Spacing), 8, 400);
			try
			{
				CreateSegmentsMethod.Invoke(projector, null);
				if (!(SegmentsField.GetValue(projector) is List<GameObject> list))
				{
					return true;
				}
				Vector3 position = ((Component)projector).transform.position;
				Quaternion rotation = wardInfo.Rotation;
				int num2 = Mathf.Min(projector.m_nrOfSegments, list.Count);
				float num3 = num / (float)num2;
				float num4 = Mathf.Repeat(Time.time * projector.m_speed * wardInfo.BaseRadius, num);
				RaycastHit val4 = default(RaycastHit);
				for (int i = 0; i < num2; i++)
				{
					GameObject val = list[i];
					if (!((Object)(object)val == (Object)null))
					{
						Vector3 tangent;
						Vector3 val2 = PointOnRectangle(Mathf.Repeat((float)i * num3 + num4, num), halfX, halfZ, out tangent);
						Vector3 val3 = position + rotation * val2;
						if (Physics.Raycast(val3 + Vector3.up * 500f, Vector3.down, ref val4, 1000f, ((LayerMask)(ref projector.m_mask)).value))
						{
							val3.y = ((RaycastHit)(ref val4)).point.y;
						}
						val.transform.position = val3;
						val.transform.rotation = Quaternion.LookRotation(rotation * tangent, Vector3.up);
					}
				}
				return false;
			}
			catch (Exception ex)
			{
				Plugin.LogWarning("Ward marker drawing failed: " + ex.GetBaseException().Message);
				return true;
			}
		}

		private static Vector3 PointOnRectangle(float d, float hx, float hz, out Vector3 tangent)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			float num = 2f * hx;
			float num2 = 2f * hz;
			if (d < num)
			{
				tangent = Vector3.right;
				return new Vector3(0f - hx + d, 0f, hz);
			}
			d -= num;
			if (d < num2)
			{
				tangent = Vector3.back;
				return new Vector3(hx, 0f, hz - d);
			}
			d -= num2;
			if (d < num)
			{
				tangent = Vector3.left;
				return new Vector3(hx - d, 0f, 0f - hz);
			}
			d -= num;
			tangent = Vector3.forward;
			return new Vector3(0f - hx, 0f, 0f - hz + Mathf.Min(d, num2));
		}

		private static void CleanUp()
		{
			List<CircleProjector> list = new List<CircleProjector>();
			foreach (CircleProjector key in Owners.Keys)
			{
				if ((Object)(object)key == (Object)null)
				{
					list.Add(key);
				}
			}
			foreach (CircleProjector item in list)
			{
				Owners.Remove(item);
			}
		}
	}
	internal sealed class FuelType
	{
		internal string Prefab;

		internal string DisplayName;
	}
	internal static class FuelKeeper
	{
		private static readonly List<Component> Burners = new List<Component>();

		private static void CollectBurners()
		{
			Burners.Clear();
			Burners.AddRange((IEnumerable<Component>)(object)Object.FindObjectsByType<Fireplace>((FindObjectsSortMode)0));
			Burners.AddRange((IEnumerable<Component>)(object)Object.FindObjectsByType<CookingStation>((FindObjectsSortMode)0));
			Burners.AddRange((IEnumerable<Component>)(object)Object.FindObjectsByType<Smelter>((FindObjectsSortMode)0));
		}

		internal static bool UsesFuel(Component burner)
		{
			if ((Object)(object)burner == (Object)null || MaxFuel(burner) <= 0f)
			{
				return false;
			}
			Fireplace val = (Fireplace)(object)((burner is Fireplace) ? burner : null);
			if (val != null)
			{
				if (!val.m_infiniteFuel)
				{
					return val.m_secPerFuel > 0f;
				}
				return false;
			}
			CookingStation val2 = (CookingStation)(object)((burner is CookingStation) ? burner : null);
			if (val2 != null)
			{
				if (val2.m_useFuel)
				{
					return (Object)(object)val2.m_fuelItem != (Object)null;
				}
				return false;
			}
			Smelter val3 = (Smelter)(object)((burner is Smelter) ? burner : null);
			if (val3 != null)
			{
				return (Object)(object)val3.m_fuelItem != (Object)null;
			}
			return false;
		}

		private static float MaxFuel(Component burner)
		{
			Fireplace val = (Fireplace)(object)((burner is Fireplace) ? burner : null);
			if (val == null)
			{
				CookingStation val2 = (CookingStation)(object)((burner is CookingStation) ? burner : null);
				if (val2 == null)
				{
					Smelter val3 = (Smelter)(object)((burner is Smelter) ? burner : null);
					if (val3 != null)
					{
						return val3.m_maxFuel;
					}
					return 0f;
				}
				return val2.m_maxFuel;
			}
			return val.m_maxFuel;
		}

		private static ZNetView View(Component burner)
		{
			if (!((Object)(object)burner != (Object)null))
			{
				return null;
			}
			return burner.GetComponentInParent<ZNetView>();
		}

		private static string PrefabOf(Component burner)
		{
			ZNetView val = View(burner);
			if (!((Object)(object)val != (Object)null))
			{
				return GameAccess.PrefabName(burner);
			}
			return GameAccess.PrefabName((Component)(object)val);
		}

		internal static bool IsInfinite(Component burner)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)burner == (Object)null || Plugin.EnableInfiniteFire == null || !Plugin.EnableInfiniteFire.Value)
			{
				return false;
			}
			string prefab = PrefabOf(burner);
			foreach (WardInfo item in WardAccess.ActiveWardsAt(burner.transform.position))
			{
				if (item.State.HasInfiniteFuelFor(prefab))
				{
					return true;
				}
			}
			return false;
		}

		internal static void Tick()
		{
			if (Plugin.EnableInfiniteFire == null || !Plugin.EnableInfiniteFire.Value)
			{
				return;
			}
			bool flag = false;
			foreach (WardInfo item in WardAccess.Known())
			{
				if (item.Enabled && item.State.AnyInfiniteFuel)
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				return;
			}
			CollectBurners();
			foreach (Component burner in Burners)
			{
				if ((Object)(object)burner == (Object)null || !UsesFuel(burner))
				{
					continue;
				}
				ZNetView val = View(burner);
				if (!((Object)(object)val == (Object)null) && val.IsValid() && val.IsOwner() && IsInfinite(burner))
				{
					float num = MaxFuel(burner);
					ZDO zDO = val.GetZDO();
					if (zDO.GetFloat(ZDOVars.s_fuel, 0f) < num)
					{
						zDO.Set(ZDOVars.s_fuel, num);
					}
				}
			}
		}

		internal static void ClearSuppliedFuel(Component burner)
		{
			if (UsesFuel(burner) && IsInfinite(burner))
			{
				ZNetView val = View(burner);
				if ((Object)(object)val != (Object)null && val.IsValid() && val.IsOwner())
				{
					val.GetZDO().Set(ZDOVars.s_fuel, 0f);
				}
			}
		}

		internal static List<FuelType> TypesInside(WardInfo ward, WardState state)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, FuelType> dictionary = new Dictionary<string, FuelType>(StringComparer.OrdinalIgnoreCase);
			CollectBurners();
			foreach (Component burner in Burners)
			{
				if (!((Object)(object)burner == (Object)null) && UsesFuel(burner) && ward.Covers(burner.transform.position))
				{
					string text = PrefabOf(burner);
					if (!string.IsNullOrEmpty(text) && !dictionary.ContainsKey(text))
					{
						string text2 = GameAccess.GetField(burner, "m_name") as string;
						dictionary[text] = new FuelType
						{
							Prefab = text,
							DisplayName = (string.IsNullOrEmpty(text2) ? text : (GameAccess.Localize(text2) + "  (" + text + ")"))
						};
					}
				}
			}
			string[] array = state.infiniteFuelStructures ?? Array.Empty<string>();
			foreach (string text3 in array)
			{
				if (!dictionary.ContainsKey(text3))
				{
					dictionary[text3] = new FuelType
					{
						Prefab = text3,
						DisplayName = text3 + "  (none inside the Ward now)"
					};
				}
			}
			List<FuelType> list = new List<FuelType>(dictionary.Values);
			list.Sort((FuelType a, FuelType b) => string.Compare(a.DisplayName, b.DisplayName, StringComparison.CurrentCultureIgnoreCase));
			return list;
		}
	}
	internal static class GameAccess
	{
		private static readonly FieldInfo ContainerViewField = AccessTools.Field(typeof(Container), "m_nview");

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

		private static readonly FieldInfo PlacementGhostField = AccessTools.Field(typeof(Player), "m_placementGhost");

		private static readonly FieldInfo CraftUpgradeItemField = AccessTools.Field(typeof(InventoryGui), "m_craftUpgradeItem");

		private static readonly Dictionary<string, FieldInfo> FieldCache = new Dictionary<string, FieldInfo>(StringComparer.Ordinal);

		internal static IEnumerable<string> MissingMembers()
		{
			if (ContainerViewField == null)
			{
				yield return "Container.m_nview";
			}
			if (ContainerLoadMethod == null)
			{
				yield return "Container.Load()";
			}
			if (PlacementGhostField == null)
			{
				yield return "Player.m_placementGhost";
			}
			if (CraftUpgradeItemField == null)
			{
				yield return "InventoryGui.m_craftUpgradeItem";
			}
		}

		internal static ZNetView ContainerView(Container container)
		{
			if ((Object)(object)container == (Object)null)
			{
				return null;
			}
			object? obj = ContainerViewField?.GetValue(container);
			ZNetView val = (ZNetView)((obj is ZNetView) ? obj : null);
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			if (!((Object)(object)container.m_rootObjectOverride != (Object)null))
			{
				return ((Component)container).GetComponentInParent<ZNetView>();
			}
			return container.m_rootObjectOverride;
		}

		internal static bool ContainerInUse(Container container)
		{
			if ((Object)(object)container == (Object)null)
			{
				return true;
			}
			if (container.IsInUse())
			{
				return true;
			}
			if ((Object)(object)container.m_wagon != (Object)null && container.m_wagon.InUse())
			{
				return true;
			}
			ZNetView val = ContainerView(container);
			if ((Object)(object)val != (Object)null && val.IsValid() && !val.IsOwner())
			{
				return val.GetZDO().GetInt(ZDOVars.s_inUse, 0) == 1;
			}
			return false;
		}

		internal static void RefreshContainer(Container container)
		{
			try
			{
				ContainerLoadMethod?.Invoke(container, null);
			}
			catch (Exception ex)
			{
				Plugin.LogWarning("Container refresh failed: " + ex.GetBaseException().Message);
			}
		}

		internal static Vector3? PlacementGhostPosition(Player player)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			object? obj = PlacementGhostField?.GetValue(player);
			GameObject val = (GameObject)((obj is GameObject) ? obj : null);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return val.transform.position;
		}

		internal static Quaternion? PlacementGhostRotation(Player player)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			object? obj = PlacementGhostField?.GetValue(player);
			GameObject val = (GameObject)((obj is GameObject) ? obj : null);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return val.transform.rotation;
		}

		internal static bool IsUpgradeSelected()
		{
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)instance != (Object)null)
			{
				return CraftUpgradeItemField?.GetValue(instance) is ItemData;
			}
			return false;
		}

		internal static string PrefabName(Component component)
		{
			if (!((Object)(object)component != (Object)null))
			{
				return string.Empty;
			}
			return ((Object)component.gameObject).name.Replace("(Clone)", string.Empty).Trim();
		}

		internal static string Localize(string token)
		{
			try
			{
				return (Localization.instance != null) ? Localization.instance.Localize(token) : token;
			}
			catch
			{
				return token;
			}
		}

		internal static object GetField(object target, string name)
		{
			if (target == null)
			{
				return null;
			}
			Type type = target.GetType();
			string key = type.FullName + "::" + name;
			if (!FieldCache.TryGetValue(key, out var value))
			{
				value = AccessTools.Field(type, name);
				FieldCache[key] = value;
			}
			try
			{
				return value?.GetValue(target);
			}
			catch
			{
				return null;
			}
		}

		internal static float GetFloatField(object target, string name)
		{
			object field = GetField(target, name);
			if (field == null)
			{
				return 0f;
			}
			try
			{
				return Convert.ToSingle(field, CultureInfo.InvariantCulture);
			}
			catch
			{
				return 0f;
			}
		}

		internal static MethodInfo[] DeclaredMethods(Type type)
		{
			return type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		}
	}
	internal static class Net
	{
		internal const string RpcSetWardState = "AdvancedWard_SetWardState";

		internal const string RpcRequestContainer = "AdvancedWard_RequestContainer";

		internal const string RpcHandOverContainer = "AdvancedWard_HandOverContainer";

		internal const string RpcNotice = "AdvancedWard_Notice";

		internal static bool IsServer
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return ZNet.instance.IsServer();
				}
				return false;
			}
		}

		internal static bool IsDedicated
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return ZNet.instance.IsDedicated();
				}
				return false;
			}
		}

		internal static void Notify(long peer, string message)
		{
			if (ZRoutedRpc.instance != null && peer != 0L)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(peer, "AdvancedWard_Notice", new object[1] { message ?? string.Empty });
			}
		}

		internal static void OnNotice(long sender, string message)
		{
			if (sender == ServerUid() && !((Object)(object)Player.m_localPlayer == (Object)null) && !string.IsNullOrEmpty(message))
			{
				((Character)Player.m_localPlayer).Message((MessageType)2, (message.Length > 200) ? message.Substring(0, 200) : message, 0, (Sprite)null, false);
			}
		}

		internal static long ServerUid()
		{
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return 0L;
			}
			if (ZNet.instance.IsServer())
			{
				return ZNet.GetUID();
			}
			return ZNet.instance.GetServerPeer()?.m_uid ?? 0;
		}

		internal static void SendToServer(string method, params object[] parameters)
		{
			if (ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(method, parameters);
			}
		}

		internal static long PlayerIdOf(long senderUid)
		{
			//IL_0073: 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)
			if (senderUid == 0L || (Object)(object)ZNet.instance == (Object)null)
			{
				return 0L;
			}
			if (senderUid == ZNet.GetUID())
			{
				if (!((Object)(object)Player.m_localPlayer != (Object)null))
				{
					return 0L;
				}
				return Player.m_localPlayer.GetPlayerID();
			}
			if (ZNet.instance.IsServer())
			{
				ZNetPeer peer = ZNet.instance.GetPeer(senderUid);
				if (peer == null)
				{
					return 0L;
				}
				if (peer.m_playerID != 0L)
				{
					return peer.m_playerID;
				}
				ZDO val = ((ZDOMan.instance != null) ? ZDOMan.instance.GetZDO(peer.m_characterID) : null);
				if (val == null)
				{
					return 0L;
				}
				return val.GetLong(ZDOVars.s_playerID, 0L);
			}
			if (ZDOMan.instance == null)
			{
				return 0L;
			}
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (!((Object)(object)allPlayer == (Object)null))
				{
					ZDO zDO = ZDOMan.instance.GetZDO(((Character)allPlayer).GetZDOID());
					if (zDO != null && zDO.GetOwner() == senderUid)
					{
						return allPlayer.GetPlayerID();
					}
				}
			}
			return 0L;
		}

		internal static Vector3? PositionOf(long senderUid)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return null;
			}
			if (senderUid == ZNet.GetUID())
			{
				if (!((Object)(object)Player.m_localPlayer != (Object)null))
				{
					return null;
				}
				return ((Component)Player.m_localPlayer).transform.position;
			}
			ZNetPeer peer = ZNet.instance.GetPeer(senderUid);
			if (peer == null || ZDOMan.instance == null)
			{
				return null;
			}
			ZDO zDO = ZDOMan.instance.GetZDO(peer.m_characterID);
			if (zDO == null)
			{
				return null;
			}
			return zDO.GetPosition();
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	internal static class RoutedRpcRegistrationPatch
	{
		private static void Postfix(ZRoutedRpc __instance)
		{
			__instance.Register<ZDOID, string>("AdvancedWard_SetWardState", (Action<long, ZDOID, string>)WardState.OnServerSetState);
			__instance.Register<ZDOID>("AdvancedWard_RequestContainer", (Action<long, ZDOID>)SharedStorage.OnServerRequestContainer);
			__instance.Register<string>("AdvancedWard_Notice", (Action<long, string>)Net.OnNotice);
		}
	}
	[HarmonyPatch(typeof(ZRoutedRpc), "RPC_RoutedRPC")]
	internal static class RoutedRpcConnectionPatch
	{
		[ThreadStatic]
		internal static ZRpc Current;

		private static void Prefix(ZRpc __0)
		{
			Current = __0;
		}

		private static Exception Finalizer(Exception __exception)
		{
			Current = null;
			return __exception;
		}
	}
	[HarmonyPatch(typeof(RoutedRPCData), "Deserialize")]
	internal static class RoutedRpcSenderPatch
	{
		private static readonly MethodInfo GetPeerByRpc = AccessTools.Method(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null);

		private static void Postfix(RoutedRPCData __instance)
		{
			ZRpc current = RoutedRpcConnectionPatch.Current;
			if (current != null && __instance != null && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && !(GetPeerByRpc == null))
			{
				object? obj = GetPeerByRpc.Invoke(ZNet.instance, new object[1] { current });
				ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
				if (val != null && val.m_uid != __instance.m_senderPeerID)
				{
					Plugin.LogWarning($"Routed RPC from peer {val.m_uid} claimed sender {__instance.m_senderPeerID}; sender corrected.");
					__instance.m_senderPeerID = val.m_uid;
				}
			}
		}
	}
	internal static class PatchArgs
	{
		internal static T Get<T>(object[] args, int index, T fallback)
		{
			if (args != null && index >= 0 && index < args.Length)
			{
				object obj = args[index];
				if (obj is T)
				{
					return (T)obj;
				}
			}
			return fallback;
		}

		internal static T First<T>(object[] args) where T : class
		{
			if (args == null)
			{
				return null;
			}
			for (int i = 0; i < args.Length; i++)
			{
				if (args[i] is T result)
				{
					return result;
				}
			}
			return null;
		}

		internal static int Index(MethodBase method, int fallback, params string[] names)
		{
			ParameterInfo[] parameters = method?.GetParameters() ?? Array.Empty<ParameterInfo>();
			int i;
			for (i = 0; i < parameters.Length; i++)
			{
				if (names.Any((string name) => string.Equals(parameters[i].Name, name, StringComparison.OrdinalIgnoreCase)))
				{
					return i;
				}
			}
			if (fallback >= parameters.Length)
			{
				return -1;
			}
			return fallback;
		}

		internal static IEnumerable<MethodBase> Methods(Type type, string name, Func<MethodInfo, bool> filter)
		{
			return (from method in GameAccess.DeclaredMethods(type)
				where method.Name == name && !method.IsAbstract && filter(method)
				select method).Cast<MethodBase>();
		}

		internal static bool FirstParameterIs(MethodInfo method, Type type)
		{
			ParameterInfo[] parameters = method.GetParameters();
			if (parameters.Length != 0)
			{
				return parameters[0].ParameterType == type;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(PrivateArea), "Awake")]
	internal static class PrivateAreaAwakePatch
	{
		private static void Postfix(PrivateArea __instance)
		{
			WardAccess.Register(__instance);
		}
	}
	[HarmonyPatch(typeof(PrivateArea), "OnDestroy")]
	internal static class PrivateAreaDestroyPatch
	{
		private static void Postfix(PrivateArea __instance)
		{
			WardAccess.Unregister(__instance);
		}
	}
	[HarmonyPatch(typeof(PrivateArea), "IsInside", new Type[]
	{
		typeof(Vector3),
		typeof(float)
	})]
	internal static class PrivateAreaShapePatch
	{
		private static bool Prefix(PrivateArea __instance, Vector3 __0, float __1, ref bool __result)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			WardInfo wardInfo = WardAccess.Get(__instance);
			if (wardInfo == null)
			{
				return true;
			}
			__result = wardInfo.Covers(__0, __1);
			return false;
		}
	}
	[HarmonyPatch(typeof(CircleProjector), "Update")]
	internal static class AreaMarkerPatch
	{
		private static bool Prefix(CircleProjector __instance)
		{
			return AreaMarker.Draw(__instance);
		}
	}
	[HarmonyPatch(typeof(PrivateArea), "Interact", new Type[]
	{
		typeof(Humanoid),
		typeof(bool),
		typeof(bool)
	})]
	internal static class WardPanelInteractPatch
	{
		private static bool Prefix(PrivateArea __instance, Humanoid __0, bool __1, bool __2, ref bool __result)
		{
			if (__1 || !__2 || (Object)(object)__0 == (Object)null || (Object)(object)__0 != (Object)(object)Player.m_localPlayer || (Object)(object)Plugin.Instance == (Object)null)
			{
				return true;
			}
			if (!Plugin.Instance.TryOpenPanel(__instance))
			{
				return true;
			}
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(PrivateArea), "GetHoverText")]
	internal static class WardHoverTextPatch
	{
		private static void Postfix(PrivateArea __instance, ref string __result)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && !string.IsNullOrEmpty(__result) && WardAccess.CanOpenPanel(WardAccess.Get(__instance), localPlayer.GetPlayerID()))
			{
				__result += "\n[<color=yellow><b>Shift + E</b></color>] Advanced Ward";
			}
		}
	}
	[HarmonyPatch(typeof(Container), "Awake")]
	internal static class ContainerAwakePatch
	{
		private static void Postfix(Container __instance)
		{
			if ((Object)(object)__instance != (Object)null)
			{
				SharedStorage.RegisterContainer(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Container), "CheckAccess", new Type[] { typeof(long) })]
	internal static class ContainerAccessPatch
	{
		private static void Postfix(Container __instance, long __0, ref bool __result)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if (__result && !((Object)(object)__instance == (Object)null) && SharedStorage.IsCandidate(__instance) && !WardAccess.AllowedAt(((Component)__instance).transform.position, __0, (MemberPermission permission) => permission.openContainers))
			{
				__result = false;
			}
		}
	}
	[HarmonyPatch(typeof(Inventory), "CountItems", new Type[]
	{
		typeof(string),
		typeof(int),
		typeof(bool)
	})]
	internal static class InventoryCountItemsPatch
	{
		private static void Postfix(Inventory __instance, string __0, int __1, bool __2, ref int __result)
		{
			SharedStorage.CountContext active = SharedStorage.Active;
			if (active == null || __instance != active.PlayerInventory)
			{
				return;
			}
			foreach (Container source in active.Sources)
			{
				Inventory val = (((Object)(object)source != (Object)null) ? source.GetInventory() : null);
				if (val != null && val != __instance)
				{
					__result += val.CountItems(__0, __1, __2);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
	{
		typeof(Piece),
		typeof(RequirementMode)
	})]
	internal static class BuildRequirementsPatch
	{
		private static void Postfix(Player __instance, MethodBase __originalMethod, object[] __args, ref bool __result)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: 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)
			if (!__result && !SharedStorage.Reentrant && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && __args[1] is RequirementMode val && (int)val == 0)
			{
				__result = SharedStorage.RecheckWithSharedStock(__originalMethod, __instance, __args, ResourceOperation.Build);
			}
		}
	}
	[HarmonyPatch(typeof(Player), "HaveRequirementItems", new Type[]
	{
		typeof(Recipe),
		typeof(bool),
		typeof(int),
		typeof(int)
	})]
	internal static class RecipeRequirementsPatch
	{
		private static void Postfix(Player __instance, MethodBase __originalMethod, object[] __args, ref bool __result)
		{
			if (!__result && !SharedStorage.Reentrant && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && !PatchArgs.Get(__args, 1, fallback: false))
			{
				ResourceOperation operation = (GameAccess.IsUpgradeSelected() ? ResourceOperation.Upgrade : ResourceOperation.Craft);
				__result = SharedStorage.RecheckWithSharedStock(__originalMethod, __instance, __args, operation);
			}
		}
	}
	[HarmonyPatch(typeof(Player), "ConsumeResources", new Type[]
	{
		typeof(Requirement[]),
		typeof(int),
		typeof(int),
		typeof(int)
	})]
	internal static class ConsumeResourcesPatch
	{
		private static void Prefix(Player __instance, Requirement[] __0, int __1, int __2, int __3, ref ShortfallPlan __state)
		{
			__state = SharedStorage.Plan(__instance, __0, __1, __2, __3);
		}

		private static void Postfix(Player __instance, ShortfallPlan __state)
		{
			SharedStorage.Pay(__instance, __state);
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
	internal static class RequirementDisplayPatch
	{
		private static void Prefix(Player __2, bool __3, ref SharedStorage.CountContext __state)
		{
			__state = SharedStorage.Active;
			if (SharedStorage.Enabled && !((Object)(object)__2 == (Object)null) && !((Object)(object)__2 != (Object)(object)Player.m_localPlayer) && !SharedStorage.Reentrant)
			{
				ResourceOperation operation = ((!__3) ? ResourceOperation.Build : (GameAccess.IsUpgradeSelected() ? ResourceOperation.Upgrade : ResourceOperation.Craft));
				List<Container> list = SharedStorage.UsableNow(__2, operation);
				if (list.Count > 0)
				{
					SharedStorage.Active = new SharedStorage.CountContext
					{
						PlayerInventory = ((Humanoid)__2).GetInventory(),
						Sources = new List<Container>(list)
					};
				}
			}
		}

		private static Exception Finalizer(Exception __exception, SharedStorage.CountContext __state)
		{
			SharedStorage.Active = __state;
			return __exception;
		}
	}
	[HarmonyPatch(typeof(Player), "UpdatePlacement")]
	internal static class PlacementScopePatch
	{
		private static void Prefix(ref ResourceOperationScope __state)
		{
			__state = SharedStorage.Enter(ResourceOperation.Build);
		}

		private static Exception Finalizer(Exception __exception, ResourceOperationScope __state)
		{
			__state?.Dispose();
			return __exception;
		}
	}
	[HarmonyPatch(typeof(Player), "TryPlacePiece", new Type[] { typeof(Piece) })]
	internal static class PlacePieceGatePatch
	{
		private static bool Prefix(Player __instance, Piece __0, ref bool __result)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: 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_00cc: 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_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
			{
				return true;
			}
			Vector3 val = (Vector3)(((??)GameAccess.PlacementGhostPosition(__instance)) ?? ((Component)__instance).transform.position);
			if (!WardAccess.AllowedAt(val, __instance.GetPlayerID(), (MemberPermission permission) => permission.build))
			{
				((Character)__instance).Message((MessageType)2, "Advanced Ward: você não tem permissão para construir aqui", 0, (Sprite)null, false);
				__result = false;
				return false;
			}
			PrivateArea val2 = (((Object)(object)__0 != (Object)null) ? ((Component)__0).GetComponent<PrivateArea>() : null);
			if ((Object)(object)val2 != (Object)null && (int)val2.m_ownerFaction == 0)
			{
				WardInfo wardInfo = WardAccess.ForeignWardOverlapping(new WardInfo
				{
					Position = val,
					Rotation = WardInfo.Yaw((Quaternion)(((??)GameAccess.PlacementGhostRotation(__instance)) ?? Quaternion.identity)),
					BaseRadius = val2.m_radius,
					Override = new WardState()
				}, __instance.GetPlayerID());
				if (wardInfo != null)
				{
					((Character)__instance).Message((MessageType)2, "Advanced Ward: muito perto da Ward de " + wardInfo.CreatorName, 0, (Sprite)null, false);
					__result = false;
					return false;
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "DoCrafting", new Type[] { typeof(Player) })]
	internal static class CraftingGatePatch
	{
		[HarmonyPriority(800)]
		private static bool Prefix(ref ResourceOperationScope __state)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			ResourceOperation operation = (GameAccess.IsUpgradeSelected() ? ResourceOperation.Upgrade : ResourceOperation.Craft);
			__state = SharedStorage.Enter(operation);
			Player localPlayer = Player.m_localPlayer;
			CraftingStation val = (((Object)(object)localPlayer != (Object)null) ? localPlayer.GetCurrentCraftingStation() : null);
			if ((Object)(object)val == (Object)null)
			{
				return true;
			}
			if (WardAccess.AllowedAt(((Component)val).transform.position, localPlayer.GetPlayerID(), (MemberPermission permission) => WardAccess.OperationAllowed(permission, operation)))
			{
				return true;
			}
			((Character)localPlayer).Message((MessageType)2, (operation == ResourceOperation.Upgrade) ? "Advanced Ward: you are not allowed to upgrade items here" : "Advanced Ward: you are not allowed to craft here", 0, (Sprite)null, false);
			return false;
		}

		private static Exception Finalizer(Exception __exception, ResourceOperationScope __state)
		{
			__state?.Dispose();
			return __exception;
		}
	}
	[HarmonyPatch(typeof(Player), "CheckCanRemovePiece", new Type[] { typeof(Piece) })]
	internal static class RemovePieceCheckPatch
	{
		private static void Postfix(Player __instance, Piece __0, ref bool __result)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if (__result && !((Object)(object)__instance == (Object)null) && !((Object)(object)__0 == (Object)null) && !WardAccess.AllowedAt(((Component)__0).transform.position, __instance.GetPlayerID(), (MemberPermission permission) => permission.demolish))
			{
				__result = false;
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					((Character)__instance).Message((MessageType)2, "Advanced Ward: you are not allowed to demolish here", 0, (Sprite)null, false);
				}
			}
		}
	}
	[HarmonyPatch(typeof(WearNTear), "RPC_Remove", new Type[]
	{
		typeof(long),
		typeof(bool)
	})]
	internal static class WearNTearRemoveRpcPatch
	{
		private static bool Prefix(WearNTear __instance, long __0)
		{
			//IL_000f: 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)
			if ((Object)(object)__instance == (Object)null || WardAccess.ActiveWardsAt(((Component)__instance).transform.position).Count == 0)
			{
				return true;
			}
			long num = Net.PlayerIdOf(__0);
			if (num == 0L)
			{
				Plugin.LogWarning($"Refused piece removal inside a Ward from unidentified peer {__0}.");
				return false;
			}
			if (WardAccess.AllowedAt(((Component)__instance).transform.position, num, (MemberPermission permission) => permission.demolish))
			{
				return true;
			}
			Plugin.LogDebug($"Refused piece removal by player {num}: no demolish right.");
			return false;
		}
	}
	internal static class Protection
	{
		internal static bool IsProtected(Vector3 position)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.EnableWardProtection == null || !Plugin.EnableWardProtection.Value)
			{
				return false;
			}
			foreach (WardInfo item in WardAccess.ActiveWardsAt(position))
			{
				if (item.State.protectStructures)
				{
					return true;
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(WearNTear), "RPC_Damage", new Type[]
	{
		typeof(long),
		typeof(HitData)
	})]
	internal static class WearNTearDamageRpcPatch
	{
		private static bool Prefix(WearNTear __instance)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)__instance == (Object)null))
			{
				return !Protection.IsProtected(((Component)__instance).transform.position);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(WearNTear), "ApplyDamage", new Type[]
	{
		typeof(float),
		typeof(HitData)
	})]
	internal static class WearNTearApplyDamagePatch
	{
		private static readonly MethodInfo HaveSupportMethod = AccessTools.Method(typeof(WearNTear), "HaveSupport", Type.EmptyTypes, (Type[])null);

		private static bool Prefix(WearNTear __instance, HitData __1, ref bool __result)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || !Protection.IsProtected(((Component)__instance).transform.position))
			{
				return true;
			}
			if (__1 == null && __instance.m_noSupportWear && HaveSupportMethod != null)
			{
				try
				{
					if (!(bool)HaveSupportMethod.Invoke(__instance, null))
					{
						return true;
					}
				}
				catch
				{
				}
			}
			__result = false;
			return false;
		}
	}
	[HarmonyPatch(typeof(Destructible), "RPC_Damage", new Type[]
	{
		typeof(long),
		typeof(HitData)
	})]
	internal static class DestructibleDamageRpcPatch
	{
		private static bool Prefix(Destructible __instance)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null)
			{
				return true;
			}
			ZNetView componentInParent = ((Component)__instance).GetComponentInParent<ZNetView>();
			if ((Object)(object)componentInParent == (Object)null || !componentInParent.IsValid() || componentInParent.GetZDO().GetLong(ZDOVars.s_creator, 0L) == 0L)
			{
				return true;
			}
			return !Protection.IsProtected(((Component)__instance).transform.position);
		}
	}
	[HarmonyPatch(typeof(Smelter), "DropAllItems")]
	internal static class SmelterDropFuelPatch
	{
		private static void Prefix(Smelter __instance)
		{
			FuelKeeper.ClearSuppliedFuel((Component)(object)__instance);
		}
	}
	[HarmonyPatch(typeof(CookingStation), "DropAllItems")]
	internal static class CookingStationDropFuelPatch
	{
		private static void Prefix(CookingStation __instance)
		{
			FuelKeeper.ClearSuppliedFuel((Component)(object)__instance);
		}
	}
	[BepInPlugin("codex.advancedward", "Advanced Ward", "0.3.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "codex.advancedward";

		public const string PluginName = "Advanced Ward";

		public const string PluginVersion = "0.3.2";

		internal static Plugin Instance;

		internal static ConfigEntry<bool> EnableWardProtection;

		internal static ConfigEntry<bool> EnableInfiniteFire;

		internal static ConfigEntry<bool> EnableSharedStorage;

		internal static ConfigEntry<bool> DebugLogging;

		internal static ConfigEntry<float> MaxWardSize;

		private static readonly string[] SharedStorageRequiredPatches = new string[9] { "InventoryCountItemsPatch", "BuildRequirementsPatch", "RecipeRequirementsPatch", "ConsumeResourcesPatch", "PlacementScopePatch", "CraftingGatePatch", "ContainerAwakePatch", "RoutedRpcRegistrationPatch", "PrivateAreaAwakePatch" };

		private Harmony harmony;

		private readonly WardPanel panel = new WardPanel();

		private bool inputBlocked;

		private float nextFuelTick;

		private float nextOwnershipTick;

		private float nextRemoteScan;

		private void Awake()
		{
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			Instance = this;
			EnableWardProtection = ConfigFileExtensions.BindConfig<bool>(((BaseUnityPlugin)this).Config, "General", "WardProtection", true, "Enable Advanced Ward structure protection (blocks all damage inside protecting wards).", true, (int?)null, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null);
			EnableInfiniteFire = ConfigFileExtensions.BindConfig<bool>(((BaseUnityPlugin)this).Config, "General", "InfiniteFire", true, "Allow wards to configure infinite fuel per structure type.", true, (int?)null, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null);
			EnableSharedStorage = ConfigFileExtensions.BindConfig<bool>(((BaseUnityPlugin)this).Config, "General", "SharedStorage", true, "Enable the Ward shared-storage feature.", true, (int?)null, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null);
			DebugLogging = ConfigFileExtensions.BindConfig<bool>(((BaseUnityPlugin)this).Config, "General", "DebugLogging", false, "Write detailed Advanced Ward diagnostics to the BepInEx log.", false, (int?)null, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null);
			ConfigFile config = ((BaseUnityPlugin)this).Config;
			AcceptableValueBase val = (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 100f);
			MaxWardSize = ConfigFileExtensions.BindConfig<float>(config, "Area", "MaxWardSize", 100f, "Largest distance in metres from a Ward to the edge of its area (circle radius, half side of a square, half length of each rectangle axis).", true, (int?)null, val, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null);
			harmony = new Harmony("codex.advancedward");
			ApplyPatches();
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Advanced Ward 0.3.2 loaded for Valheim " + Version.GetVersionString(false) + "."));
		}

		private void ApplyPatches()
		{
			HashSet<string> applied = new HashSet<string>(StringComparer.Ordinal);
			List<Type> list = (from t in typeof(Plugin).Assembly.GetTypes()
				where t.GetCustomAttributes(typeof(HarmonyPatch), inherit: false).Length != 0
				select t).ToList();
			foreach (Type item in list)
			{
				try
				{
					harmony.CreateClassProcessor(item).Patch();
					applied.Add(item.Name);
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Patch " + item.Name + " could not be applied: " + ex.GetBaseException().Message));
				}
			}
			foreach (string item2 in AreaMarker.MissingMembers())
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Ward marker falls back to circles; missing member " + item2));
			}
			if (!applied.Contains("PrivateAreaShapePatch"))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"PrivateArea.IsInside patch failed: vanilla checks will keep the circular 32 m area.");
			}
			string[] array = SharedStorageRequiredPatches.Where((string name) => !applied.Contains(name)).Concat(from member in GameAccess.MissingMembers()
				select "member " + member).ToArray();
			SharedStorage.PatchesReady = array.Length == 0;
			if (array.Length != 0)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Shared Ward storage is DISABLED for safety because these patches/members are missing: " + string.Join(", ", array)));
			}
			if (!applied.Contains("RoutedRpcSenderPatch") || !applied.Contains("RoutedRpcConnectionPatch"))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Routed RPC sender verification is not active: on a server, peers could impersonate others.");
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Applied {applied.Count} of {list.Count} patch classes.");
		}

		private void OnDestroy()
		{
			ClosePanel();
			panel.Destroy();
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}

		private void Update()
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime >= nextFuelTick)
			{
				nextFuelTick = unscaledTime + 2f;
				try
				{
					FuelKeeper.Tick();
				}
				catch (Exception ex)
				{
					LogWarning("Infinite fuel tick failed: " + ex.GetBaseException().Message);
				}
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				ClosePanel();
				return;
			}
			if (unscaledTime >= nextRemoteScan)
			{
				nextRemoteScan = unscaledTime + 2f;
				try
				{
					WardAccess.RefreshRemote(((Component)localPlayer).transform.position);
				}
				catch (Exception ex2)
				{
					LogWarning("Ward scan failed: " + ex2.GetBaseException().Message);
				}
			}
			if (unscaledTime >= nextOwnershipTick)
			{
				nextOwnershipTick = unscaledTime + 1f;
				if (panel.IsOpen || ((Character)localPlayer).InPlaceMode() || InventoryGui.IsVisible())
				{
					try
					{
						SharedStorage.RequestNearbyOwnership(localPlayer);
					}
					catch (Exception ex3)
					{
						LogWarning("Ownership request failed: " + ex3.GetBaseException().Message);
					}
				}
			}
			if (!panel.IsOpen)
			{
				if (inputBlocked)
				{
					ClosePanel();
				}
				return;
			}
			PrivateArea ward = panel.Ward;
			WardInfo wardInfo = WardAccess.Get(ward);
			if (Input.GetKeyDown((KeyCode)27) || wardInfo == null || Vector3.Distance(((Component)localPlayer).transform.position, ((Component)ward).transform.position) > wardInfo.BoundingRadius + 10f || !WardAccess.CanOpenPanel(wardInfo, localPlayer.GetPlayerID()))
			{
				ClosePanel();
				return;
			}
			try
			{
				panel.EveryFrame();
				panel.Update();
			}
			catch (Exception ex4)
			{
				LogWarning("Panel update failed: " + ex4.GetBaseException());
				ClosePanel();
			}
		}

		internal bool TryOpenPanel(PrivateArea ward)
		{
			Player localPlayer = Player.m_localPlayer;
			WardInfo ward2 = WardAccess.Get(ward);
			if ((Object)(object)localPlayer == (Object)null || !WardAccess.CanOpenPanel(ward2, localPlayer.GetPlayerID()))
			{
				return false;
			}
			SharedStorage.Invalidate();
			bool flag;
			try
			{
				flag = panel.Open(ward, WardAccess.IsCreator(ward2, localPlayer.GetPlayerID()));
			}
			catch (Exception ex)
			{
				LogWarning("Could not open the Ward panel: " + ex.GetBaseException());
				flag = false;
			}
			if (flag && !inputBlocked)
			{
				inputBlocked = true;
				GUIManager.BlockInput(true);
			}
			return flag;
		}

		internal void ClosePanel()
		{
			panel.Close();
			if (inputBlocked)
			{
				inputBlocked = false;
				GUIManager.BlockInput(false);
			}
		}

		internal static void LogDebug(string message)
		{
			if (DebugLogging != null && DebugLogging.Value)
			{
				Plugin instance = Instance;
				if (instance != null)
				{
					((BaseUnityPlugin)instance).Logger.LogInfo((object)("[AdvancedWard] " + message));
				}
			}
		}

		internal static void LogWarning(string message)
		{
			Plugin instance = Instance;
			if (instance != null)
			{
				((BaseUnityPlugin)instance).Logger.LogWarning((object)("[AdvancedWard] " + message));
			}
		}
	}
	internal sealed class StorageSource
	{
		internal Container Container;

		internal string Key;

		internal string Label;

		internal bool Excluded;

		internal bool UsableByViewer;

		internal bool Ready;
	}
	internal sealed class Shortfall
	{
		internal string Name;

		internal int Amount;

		internal int ItemQuality;
	}
	internal sealed class ShortfallPlan
	{
		internal ResourceOperation Operation;

		internal readonly List<Shortfall> Items = new List<Shortfall>();
	}
	internal sealed class ResourceOperationScope : IDisposable
	{
		private readonly ResourceOperation previous;

		private bool disposed;

		internal ResourceOperationScope(ResourceOperation operation)
		{
			previous = SharedStorage.CurrentOperation;
			SharedStorage.CurrentOperation = operation;
		}

		public void Dispose()
		{
			if (!disposed)
			{
				SharedStorage.CurrentOperation = previous;
				disposed = true;
			}
		}
	}
	internal static class SharedStorage
	{
		internal sealed class CountContext
		{
			internal Inventory PlayerInventory;

			internal List<Container> Sources;
		}

		private const string ContainerIdKey = "AdvancedWard.cid";

		private const float RescanInterval = 1f;

		private const float OwnershipRequestCooldown = 4f;

		private const float LocalUseGrace = 6f;

		private const float PlayerInsideMargin = 4f;

		internal static bool PatchesReady;

		internal static ResourceOperation CurrentOperation;

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

		private static float nextScan;

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

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

		private static int usableFrame = -1;

		private static ResourceOperation usableOperation;

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

		private static PrivateArea totalsWard;

		private static float totalsUntil;

		private static readonly List<StorageSource> SourcesCache = new List<StorageSource>();

		private static readonly Dictionary<string, int> TotalsCache = new Dictionary<string, int>(StringComparer.Ordinal);

		internal static readonly Dictionary<string, Sprite> Icons = new Dictionary<string, Sprite>(StringComparer.Ordinal);

		internal static bool Enabled
		{
			get
			{
				if (PatchesReady && Plugin.EnableSharedStorage != null)
				{
					return Plugin.EnableSharedStorage.Value;
				}
				return false;
			}
		}

		internal static CountContext Active { get; set; }

		internal static bool Reentrant { get; private set; }

		internal static ResourceOperationScope Enter(ResourceOperation operation)
		{
			return new ResourceOperationScope(operation);
		}

		private static List<Container> AllContainers()
		{
			if (Time.unscaledTime >= nextScan)
			{
				nextScan = Time.unscaledTime + 1f;
				Containers.Clear();
				Containers.AddRange(Object.FindObjectsByType<Container>((FindObjectsSortMode)0));
			}
			Containers.RemoveAll((Container container) => (Object)(object)container == (Object)null);
			return Containers;
		}

		internal static void Invalidate()
		{
			totalsUntil = 0f;
			usableFrame = -1;
		}

		private static long CreatorOf(ZDO zdo)
		{
			if (zdo == null)
			{
				return 0L;
			}
			return zdo.GetLong(ZDOVars.s_creator, 0L);
		}

		internal static bool IsCandidate(Container container)
		{
			if ((Object)(object)container == (Object)null || !((Behaviour)container).isActiveAndEnabled || container.GetInventory() == null)
			{
				return false;
			}
			ZNetView val = GameAccess.ContainerView(container);
			if ((Object)(object)val == (Object)null || !val.IsValid() || CreatorOf(val.GetZDO()) == 0L)
			{
				return false;
			}
			if ((Object)(object)((Component)val).GetComponent<Ship>() == (Object)null)
			{
				return (Object)(object)((Component)val).GetComponent<Piece>() != (Object)null;
			}
			return false;
		}

		internal static string Key(ZDO zdo)
		{
			if (zdo == null)
			{
				return string.Empty;
			}
			return zdo.GetString("AdvancedWard.cid", string.Empty);
		}

		internal static void EnsureKey(Container container)
		{
			ZNetView val = GameAccess.ContainerView(container);
			if (!((Object)(object)val == (Object)null) && val.IsValid() && val.IsOwner() && string.IsNullOrEmpty(Key(val.GetZDO())))
			{
				val.GetZDO().Set("AdvancedWard.cid", Guid.NewGuid().ToString("N"));
			}
		}

		internal static bool RuleAllows(List<WardInfo> coveringWards, ZDO containerZdo, PrivacySetting privacy, long playerId, ResourceOperation operation)
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Invalid comparison between Unknown and I4
			if (playerId == 0L || containerZdo == null || coveringWards == null || coveringWards.Count == 0)
			{
				return false;
			}
			long num = CreatorOf(containerZdo);
			if (num == 0L)
			{
				return false;
			}
			string key = Key(containerZdo);
			foreach (WardInfo coveringWard in coveringWards)
			{
				WardState state = coveringWard.State;
				if (!state.sharedStorage || state.IsContainerExcluded(key))
				{
					return false;
				}
				if (!WardAccess.Has(coveringWard, playerId, (MemberPermission p) => p.useMaterials && WardAccess.OperationAllowed(p, operation)))
				{
					return false;
				}
			}
			if ((int)privacy != 0)
			{
				if ((int)privacy == 2)
				{
					return true;
				}
				return false;
			}
			return num == playerId;
		}

		internal static bool CanPlayerUseContainer(Container container, long playerId, ResourceOperation operation)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (!Enabled || playerId == 0L || !IsCandidate(container))
			{
				return false;
			}
			ZNetView val = GameAccess.ContainerView(container);
			return RuleAllows(new List<WardInfo>(WardAccess.ActiveWardsAt(((Component)container).transform.position)), val.GetZDO(), container.m_privacy, playerId, operation);
		}

		private static List<WardInfo> WardsServingPlayer(Player player, ResourceOperation operation)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			long playerID = player.GetPlayerID();
			List<WardInfo> list = new List<WardInfo>(WardAccess.ActiveWardsAt(((Component)player).transform.position));
			foreach (WardInfo item in list)
			{
				if (!item.State.sharedStorage || !WardAccess.Has(item, playerID, (MemberPermission p) => p.useMaterials && WardAccess.OperationAllowed(p, operation)))
				{
					return new List<WardInfo>();
				}
			}
			return list;
		}

		internal static List<Container> UsableNow(Player player, ResourceOperation operation)
		{
			if (usableFrame == Time.frameCount && usableOperation == operation)
			{
				return UsableCache;
			}
			usableFrame = Time.frameCount;
			usableOperation = operation;
			UsableCache.Clear();
			if (!Enabled || (Object)(object)player == (Object)null || operation == ResourceOperation.None)
			{
				return UsableCache;
			}
			List<WardInfo> list = WardsServingPlayer(player, operation);
			if (list.Count == 0)
			{
				return UsableCache;
			}
			long playerID = player.GetPlayerID();
			foreach (Container container in AllContainers())
			{
				if (list.Any((WardInfo ward) => ward.Covers(((Component)container).transform.position)))
				{
					ZNetView val = GameAccess.ContainerView(container);
					if (!((Object)(object)val == (Object)null) && val.IsValid() && val.IsOwner() && !GameAccess.ContainerInUse(container) && CanPlayerUseContainer(container, playerID, operation))
					{
						GameAccess.RefreshContainer(container);
						UsableCache.Add(container);
					}
				}
			}
			return UsableCache;
		}

		internal static void RequestNearbyOwnership(Player player)
		{
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			if (!Enabled || (Object)(object)player == (Object)null)
			{
				return;
			}
			List<WardInfo> list = WardsServingPlayer(player, ResourceOperation.None);
			if (list.Count == 0)
			{
				return;
			}
			long playerID = player.GetPlayerID();
			float unscaledTime = Time.unscaledTime;
			foreach (Container container in AllContainers())
			{
				if (!list.Any((WardInfo ward) => ward.Covers(((Component)container).transform.position)))
				{
					continue;
				}
				ZNetView val = GameAccess.ContainerView(container);
				if ((Object)(object)val == (Object)null || !val.IsValid())
				{
					continue;
				}
				if (val.IsOwner())
				{
					EnsureKey(container);
					continue;
				}
				ZDOID uid = val.GetZDO().m_uid;
				if ((!LastRequest.TryGetValue(uid, out var value) || !(unscaledTime - value < 4f)) && !GameAccess.ContainerInUse(container) && CanPlayerUseContainer(container, playerID, ResourceOperation.None))
				{
					LastRequest[uid] = unscaledTime;
					Net.SendToServer("AdvancedWard_RequestContainer", uid);
				}
			}
		}

		internal static void OnServerRequestContainer(long sender, ZDOID containerId)
		{
			//IL_002e: 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_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			if (!Net.IsServer || !Enabled || ZDOMan.instance == null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			ZDO zDO = ZDOMan.instance.GetZDO(containerId);
			if (zDO == null || !zDO.IsValid())
			{
				return;
			}
			long owner = zDO.GetOwner();
			if (owner == sender)
			{
				return;
			}
			long num = Net.PlayerIdOf(sender);
			Vector3? playerPosition = Net.PositionOf(sender);
			GameObject prefab = ZNetScene.instance.GetPrefab(zDO.GetPrefab());
			Container val = (((Object)(object)prefab != (Object)null) ? prefab.GetComponentInChildren<Container>(true) : null);
			if (num == 0L || !playerPosition.HasValue || (Object)(object)val == (Object)null || (Object)(object)prefab.GetComponent<Ship>() != (Object)null || (Object)(object)prefab.GetComponent<Piece>() == (Object)null)
			{
				Plugin.LogDebug($"Container request from peer {sender} refused: unknown player or not a player-built container.");
				return;
			}
			List<WardInfo> list = WardAccess.ActiveWardsFromZdos(zDO.GetPosition());
			if (!list.Any((WardInfo ward) => ward.Covers(playerPosition.Value, 4f)))
			{
				Plugin.LogDebug($"Container request from player {num} refused: player is not inside the Ward.");
			}
			else if (!RuleAllows(list, zDO, val.m_privacy, num, ResourceOperation.None))
			{
				Plugin.LogDebug($"Container request from player {num} refused by Ward rules.");
			}
			else
			{
				if (zDO.GetInt(ZDOVars.s_inUse, 0) == 1)
				{
					return;
				}
				if (owner == 0L || (owner != ZNet.GetUID() && !ZNet.instance.IsConnected(owner)))
				{
					Transfer(zDO, sender);
				}
				else if (owner == ZNet.GetUID())
				{
					GameObject val2 = ZNetScene.instance.FindInstance(containerId);
					Container val3 = (((Object)(object)val2 != (Object)null) ? val2.GetComponentInChildren<Container>() : null);
					if ((Object)(object)val3 == (Object)null)
					{
						Transfer(zDO, sender);
					}
					else
					{
						HandOver(val3, sender);
					}
				}
				else
				{
					ZRoutedRpc.instance.InvokeRoutedRPC(owner, containerId, "AdvancedWard_HandOverContainer", new object[1] { sender });
				}
			}
		}

		internal static void RegisterContainer(Container container)
		{
			ZNetView val = GameAccess.ContainerView(container);
			if ((Object)(object)val == (Object)null || val.GetZDO() == null)
			{
				return;
			}
			val.Register<long>("AdvancedWard_HandOverContainer", (Action<long, long>)delegate(long sender, long requester)
			{
				if (sender != Net.ServerUid())
				{
					Plugin.LogWarning($"Ignored container hand-over ordered by peer {sender} (not the server).");
				}
				else
				{
					HandOver(container, requester);
				}
			});
			EnsureKey(container);
		}

		private static void HandOver(Container container, long requester)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			ZNetView val = GameAccess.ContainerView(container);
			if (!((Object)(object)val == (Object)null) && val.IsValid() && val.IsOwner() && requester != ZNet.GetUID() && !container.IsInUse() && (!((Object)(object)container.m_wagon != (Object)null) || !container.m_wagon.InUse()) && (!LastLocalUse.TryGetValue(val.GetZDO().m_uid, out var value) || !(Time.unscaledTime - value < 6f)))
			{
				EnsureKey(container);
				Transfer(val.GetZDO(), requester);
			}
		}

		private static void Transfer(ZDO zdo, long peer)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			ZDOMan.instance.ForceSendZDO(peer, zdo.m_uid);
			zdo.SetOwner(peer);
			Plugin.LogDebug($"Container {zdo.m_uid} handed to peer {peer} for shared Ward materials.");
		}

		internal static bool RecheckWithSharedStock(MethodBase original, Player player, object[] args, ResourceOperation operation)
		{
			if (Reentrant || !Enabled || original == null || (Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer)
			{
				return false;
			}
			List<Container> list = UsableNow(player, operation);
			if (list.Count == 0)
			{
				return false;
			}
			CountContext active = Active;
			Active = new CountContext
			{
				PlayerInventory = ((Humanoid)player).GetInventory(),
				Sources = new List<Container>(list)
			};
			Reentrant = true;
			try
			{
				object obj = original.Invoke(player, args);
				bool flag = default(bool);
				int num;
				if (obj is bool)
				{
					flag = (bool)obj;
					num = 1;
				}
				else
				{
					num = 0;
				}
				return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			}
			catch (Exception ex)
			{
				Plugin.LogWarning("Shared requirement check failed: " + ex.GetBaseException().Message);
				return false;
			}
			finally
			{
				Active = active;
				Reentrant = false;
			}
		}

		internal static ShortfallPlan Plan(Player player, Requirement[] requirements, int qualityLevel, int itemQuality, int multiplier)
		{
			ResourceOperation currentOperation = CurrentOperation;
			if (!Enabled || currentOperation == ResourceOperation.None || (Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || requirements == null || player.NoCostCheat())
			{
				return null;
			}
			CraftingStation currentCraftingStation = player.GetCurrentCraftingStation();
			Inventory inventory = ((Humanoid)player).GetInventory();
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
			foreach (Requirement val in requirements)
			{
				if (val != null && !((Object)(object)val.m_resItem == (Object)null) && val.m_resItem.m_itemData?.m_shared != null && !(((Object)(object)currentCraftingStation != (Object)null) ? (currentCraftingStation.m_upgrader != val.m_upgraderResource) : val.m_upgraderResource))
				{
					int num = val.GetAmount(qualityLevel) * multiplier;
					if (num > 0)
					{
						string name = val.m_resItem.m_itemData.m_shared.m_name;
						dictionary.TryGetValue(name, out var value);
						dictionary[name] = value + num;
					}
				}
			}
			ShortfallPlan shortfallPlan = new ShortfallPlan
			{
				Operation = currentOperation
			};
			foreach (KeyValuePair<string, int> item in dictionary)
			{
				int num2 = inventory.CountItems(item.Key, itemQuality, true);
				if (num2 < item.Value)
				{
					shortfallPlan.Items.Add(new Shortfall
					{
						Name = item.Key,
						Amount = item.Value - num2,
						ItemQuality = itemQuality
					});
				}
			}
			if (shortfallPlan.Items.Count <= 0)
			{
				return null;
			}
			return shortfallPlan;
		}

		internal static void Pay(Player player, ShortfallPlan plan)
		{
			if (plan == null || (Object)(object)player == (Object)null)
			{
				return;
			}
			List<Container> sources = new List<Container>(UsableNow(player, plan.Operation));
			foreach (Shortfall item in plan.Items)
			{
				int num = RemoveFromContainers(sources, item.Name, item.Amount, item.ItemQuality);
				if (num > 0)
				{
					Plugin.LogWarning($"Shared Ward storage was {num} x {item.Name} short when paying ({plan.Operation}).");
				}
			}
			Invalidate();
		}

		private static int RemoveFromContainers(List<Container> sources, string name, int amount, int itemQuality)
		{
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			foreach (Container source in sources)
			{
				if (amount <= 0)
				{
					break;
				}
				Inventory val = (((Object)(object)source != (Object)null) ? source.GetInventory() : null);
				ZNetView val2 = GameAccess.ContainerView(source);
				if (val == null || (Object)(object)val2 == (Object)null || !val2.IsValid() || !val2.IsOwner() || GameAccess.ContainerInUse(source))
				{
					continue;
				}
				bool flag = false;
				ItemData[] array = val.GetAllItems().ToArray();
				foreach (ItemData val3 in array)
				{
					if (amount <= 0)
					{
						break;
					}
					if (val3?.m_shared != null && val3.m_stack > 0 && string.Equals(val3.m_shared.m_name, name, StringComparison.Ordinal) && (itemQuality < 0 || val3.m_quality == itemQuality) && val3.m_worldLevel >= Game.m_worldLevel)
					{
						int num = Math.Min(amount, val3.m_stack);
						if (val.RemoveItem(val3, num))
						{
							amount -= num;
							flag = true;
						}
					}
				}
				if (flag)
				{
					LastLocalUse[val2.GetZDO().m_uid] = Time.unscaledTime;
				}
			}
			return amount;
		}

		internal static void Snapshot(PrivateArea ward, long viewerId, out List<StorageSource> sources, out Dictionary<string, int> totals)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ward != (Object)(object)totalsWard || Time.unscaledTime >= totalsUntil)
			{
				totalsWard = ward;
				totalsUntil = Time.unscaledTime + 0.75f;
				SourcesCache.Clear();
				TotalsCache.Clear();
				WardInfo wardInfo = WardAccess.Get(ward);
				if (wardInfo != null)
				{
					WardState state = wardInfo.State;
					foreach (Container item in AllContainers())
					{
						if (!IsCandidate(item) || !wardInfo.Covers(((Component)item).transform.position))
						{
							continue;
						}
						ZNetView val = GameAccess.ContainerView(item);
						string key = Key(val.GetZDO());
						StorageSource storageSource = new StorageSource
						{
							Container = item,
							Key = key,
							Label = Label(item),
							Excluded = state.IsContainerExcluded(key),
							UsableByViewer = CanPlayerUseContainer(item, viewerId, ResourceOperation.None),
							Ready = (val.IsOwner() && !GameAccess.ContainerInUse(item))
						};
						SourcesCache.Add(storageSource);
						if (storageSource.Excluded || !storageSource.UsableByViewer)
						{
							continue;
						}
						foreach (ItemData allItem in item.GetInventory().GetAllItems())
						{
							if (allItem?.m_shared == null || allItem.m_stack <= 0 || string.IsNullOrEmpty(allItem.m_shared.m_name) || allItem.m_worldLevel < Game.m_worldLevel)
							{
								continue;
							}
							TotalsCache.TryGetValue(allItem.m_shared.m_name, out var value);
							TotalsCache[allItem.m_shared.m_name] = value + allItem.m_stack;
							if (!Icons.ContainsKey(allItem.m_shared.m_name))
							{
								try
								{
									Icons[allItem.m_shared.m_name] = allItem.GetIcon();
								}
								catch
								{
									Icons[allItem.m_shared.m_name] = null;
								}
							}
						}
					}
				}
			}
			sources = SourcesCache;
			totals = TotalsCache;
		}

		private static string Label(Container container)
		{
			//IL_0041: 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_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			string text = (string.IsNullOrWhiteSpace(container.m_name) ? GameAccess.PrefabName((Component)(object)container) : GameAccess.Localize(container.m_name));
			if ((Object)(object)container.m_wagon != (Object)null)
			{
				text += " (cart)";
			}
			Vector3 position = ((Component)container).transform.position;
			return string.Format(CultureInfo.InvariantCulture, "{0}  @ {1:0}, {2:0}, {3:0}", text, position.x, position.y, position.z);
		}
	}
	internal enum ResourceOperation
	{
		None,
		Build,
		Craft,
		Upgrade
	}
	internal enum WardShape
	{
		Circle,
		Square,
		Rectangle
	}
	internal sealed class WardInfo
	{
		internal ZDO Zdo;

		internal Vector3 Position;

		internal Quaternion Rotation = Quaternion.identity;

		internal float BaseRadius;

		internal PrivateArea Instance;

		internal WardState Override;

		internal bool Valid
		{
			get
			{
				if (Zdo != null)
				{
					return Zdo.IsValid();
				}
				return false;
			}
		}

		internal bool Enabled
		{
			get
			{
				if (Valid)
				{
					return Zdo.GetBool(ZDOVars.s_enabled, false);
				}
				return false;
			}
		}

		internal long Creator
		{
			get
			{
				if (!Valid)
				{
					return 0L;
				}
				return Zdo.GetLong(ZDOVars.s_creator, 0L);
			}
		}

		internal WardState State => Override ?? WardState.Read(Zdo);

		internal string CreatorName
		{
			get
			{
				if (!Valid)
				{
					return "?";
				}
				return Zdo.GetString(ZDOVars.s_creatorName, "");
			}
		}

		internal float BoundingRadius
		{
			get
			{
				Extents(out var shape, out var halfX, out var halfZ);
				if (shape != WardShape.Circle)
				{
					return Mathf.Sqrt(halfX * halfX + halfZ * halfZ);
				}
				return halfX;
			}
		}

		internal static Quaternion Yaw(Quaternion rotation)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			return Quaternion.Euler(0f, ((Quaternion)(ref rotation)).eulerAngles.y, 0f);
		}

		internal static WardInfo FromZdo(ZDO zdo, WardState overrideState = null)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			return new WardInfo
			{
				Zdo = zdo,
				Position = zdo.GetPosition(),
				Rotation = Yaw(zdo.GetRotation()),
				BaseRadius = WardAccess.WardPrefabRadius(zdo.GetPrefab()),
				Override = overrideState
			};
		}

		internal static void Extents(WardState state, float baseRadius, out WardShape shape, out float halfX, out float halfZ)
		{
			shape = (WardShape)state.shape;
			if (shape == WardShape.Rectangle)
			{
				halfX = ((state.sizeX > 0f) ? state.sizeX : baseRadius);
				halfZ = ((state.sizeZ > 0f) ? state.sizeZ : baseRadius);
			}
			else
			{
				halfX = (halfZ = ((state.radius > 0f) ? state.radius : baseRadius));
			}
		}

		internal void Extents(out WardShape shape, out float halfX, out float halfZ)
		{
			Extents(State, BaseRadius, out shape, out halfX, out halfZ);
		}

		internal bool Covers(Vector3 point, float extra = 0f)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_004f: 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)
			Extents(out var shape, out var halfX, out var halfZ);
			Vector3 val = point - Position;
			val.y = 0f;
			if (shape == WardShape.Circle)
			{
				float num = halfX + extra;
				return ((Vector3)(ref val)).sqrMagnitude < num * num;
			}
			Vector3 val2 = Quaternion.Inverse(Rotation) * val;
			if (Mathf.Abs(val2.x) < halfX + extra)
			{
				return Mathf.Abs(val2.z) < halfZ + extra;
			}
			return false;
		}

		internal string Describe()
		{
			Extents(out var shape, out var halfX, out var halfZ);
			return shape switch
			{
				WardShape.Square => $"quadrada {halfX * 2f:0} × {halfZ * 2f:0} m", 
				WardShape.Rectangle => $"retangular {halfX * 2f:0} × {halfZ * 2f:0} m (X × Z)", 
				_ => $"circular, raio {halfX:0} m", 
			};
		}

		internal bool IsPermitted(long playerId)
		{
			if (!Valid || playerId == 0L)
			{
				return false;
			}
			int num = Zdo.GetInt(ZDOVars.s_permitted, 0);
			for (int i = 0; i < num; i++)
			{
				if (Zdo.GetLong("pu_id" + i, 0L) == playerId)
				{
					return true;
				}
			}
			return false;
		}

		internal List<KeyValuePair<long, string>> PermittedPlayers()
		{
			List<KeyValuePair<long, string>> list = new List<KeyValuePair<long, string>>();
			if (!Valid)
			{
				return list;
			}
			int num = Zdo.GetInt(ZDOVars.s_permitted, 0);
			for (int i = 0; i < num; i++)
			{
				long num2 = Zdo.GetLong("pu_id" + i, 0L);
				if (num2 != 0L)
				{
					list.Add(new KeyValuePair<long, string>(num2, Zdo.GetString("pu_name" + i, "")));
				}
			}
			return list;
		}
	}
	internal static class WardAccess
	{
		private const float ZoneSize = 64f;

		private static readonly Dictionary<PrivateArea, WardInfo> Instances = new Dictionary<PrivateArea, WardInfo>();

		internal static readonly List<WardInfo> Wards = new List<WardInfo>();

		private static readonly Dictionary<ZDOID, WardInfo> Remote = new Dictionary<ZDOID, WardInfo>();

		private static readonly List<WardInfo> Scratch = new List<WardInfo>();

		private static readonly Dictionary<int, float> PrefabRadius = new Dictionary<int, float>();

		internal static float MaxBoundingRadius => WardState.MaxSize * 1.4143f;

		internal static void Register(PrivateArea ward)
		{
			//IL_000a: 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)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)ward == (Object)null) && (int)ward.m_ownerFaction == 0 && !Instances.ContainsKey(ward))
			{
				ZNetView component = ((Component)ward).GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && component.IsValid())
				{
					WardInfo wardInfo = new WardInfo
					{
						Zdo = component.GetZDO(),
						Position = ((Component)ward).transform.position,
						Rotation = WardInfo.Yaw(((Component)ward).transform.rotation),
						BaseRadius = ward.m_radius,
						Instance = ward
					};
					Instances[ward] = wardInfo;
					Wards.Add(wardInfo);
					Remote.Remove(wardInfo.Zdo.m_uid);
				}
			}
		}

		internal static void Unregister(PrivateArea ward)
		{
			if (!((Object)(object)ward == (Object)null) && Instances.TryGetValue(ward, out var value))
			{
				Instances.Remove(ward);
				Wards.Remove(value);
			}
		}

		internal static WardInfo Get(PrivateArea ward)
		{
			if ((Object)(object)ward == (Object)null || !Instances.TryGetValue(ward, out var value))
			{
				return null;
			}
			if (!value.Valid)
			{
				return null;
			}
			return value;
		}

		internal static IEnumerable<WardInfo> Known()
		{
			for (int i = Wards.Count - 1; i >= 0; i--)
			{
				WardInfo wardInfo = Wards[i];
				if ((Object)(object)wardInfo.Instance == (Object)null)
				{
					Wards.RemoveAt(i);
				}
				else if (wardInfo.Valid)
				{
					yield return wardInfo;
				}
			}
			foreach (WardInfo value in Remote.Values)
			{
				if (value.Valid)
				{
					yield return value;
				}
			}
		}

		internal static void RefreshRemote(Vector3 around)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: 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_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			HashSet<ZDOID> hashSet = new HashSet<ZDOID>();
			foreach (WardInfo ward in Wards)
			{
				if ((Object)(object)ward.Instance != (Object)null && ward.Valid)
				{
					hashSet.Add(ward.Zdo.m_uid);
				}
			}
			HashSet<ZDOID> hashSet2 = new HashSet<ZDOID>();
			foreach (ZDO item in WardZdosNear(around, MaxBoundingRadius))
			{
				if (!hashSet.Contains(item.m_uid))
				{
					hashSet2.Add(item.m_uid);
					if (!Remote.TryGetValue(item.m_uid, out var value) || value.Zdo != item)
					{
						Remote[item.m_uid] = WardInfo.FromZdo(item);
					}
				}
			}
			List<ZDOID> list = new List<ZDOID>();
			foreach (KeyValuePair<ZDOID, WardInfo> item2 in Remote)
			{
				if (!hashSet2.Contains(item2.Key) || !item2.Value.Valid)
				{
					list.Add(item2.Key);
				}
			}
			foreach (ZDOID item3 in list)
			{
				Remote.Remove(item3);
			}
		}

		internal static List<WardInfo> ActiveWardsAt(Vector3 point)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			Scratch.Clear();
			foreach (WardInfo item in Known())
			{
				if (item.Enabled && item.Covers(point))
				{
					Scratch.Add(item);
				}
			}
			return Scratch;
		}

		internal static float WardPrefabRadius(int prefabHash)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (PrefabRadius.TryGetValue(prefabHash, out var value))
			{
				return value;
			}
			value = 0f;
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(prefabHash) : null);
			PrivateArea val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<PrivateArea>() : null);
			if ((Object)(object)val2 != (Object)null && (int)val2.m_ownerFaction == 0)
			{
				value = val2.m_radius;
			}
			if ((Object)(object)ZNetScene.instance != (Object)null)
			{
				PrefabRadius[prefabHash] = value;
			}
			return value;
		}

		private static List<ZDO> WardZdosNear(Vector3 point, float range)
		{
			//IL_0043: 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_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			List<ZDO> list = new List<ZDO>();
			if (ZDOMan.instance == null || (Object)(object)ZoneSystem.instance == (Object)null)
			{
				return list;
			}
			int num = Mathf.Clamp(Mathf.CeilToInt(range / 64f) + 1, 1, 8);
			List<ZDO> list2 = new List<ZDO>();
			List<ZDO> list3 = new List<ZDO>();
			ZDOMan.instance.FindSectorObjects(ZoneSystem.GetZone(point), new SimulationDistance(num, 0, true), list2, list3);
			list2.AddRange(list3);
			HashSet<ZDOID> hashSet = new HashSet<ZDOID>();
			foreach (ZDO item in list2)
			{
				if (item != null && item.IsValid() && hashSet.Add(item.m_uid) && !(WardPrefabRadius(item.GetPrefab()) <= 0f))
				{
					Vector3 val = item.GetPosition() - point;
					val.y = 0f;
					if (((Vector3)(ref val)).magnitude <= range)
					{
						list.Add(item);
					}
				}
			}
			return list;
		}

		internal static List<WardInfo> ActiveWardsFromZdos(Vector3 point)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			List<WardInfo> list = new List<WardInfo>();
			foreach (ZDO item in WardZdosNear(point, MaxBoundingRadius))
			{
				WardInfo wardInfo = WardInfo.FromZdo(item);
				if (wardInfo.Enabled && wardInfo.Covers(point))
				{
					list.Add(wardInfo);
				}
			}
			return list;
		}

		internal static WardInfo ForeignWardOverlapping(WardInfo candidate, long playerId)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			IEnumerable<WardInfo> enumerable;
			if (Net.IsServer)
			{
				List<WardInfo> list = new List<WardInfo>();
				foreach (ZDO item in WardZdosNear(candidate.Position, candidate.BoundingRadius + MaxBoundingRadius))
				{
					list.Add(WardInfo.FromZdo(item));
				}
				enumerable = list;
			}
			else
			{
				enumerable = new List<WardInfo>(Known());
			}
			foreach (WardInfo item2 in enumerable)
			{
				if ((candidate.Zdo == null || item2.Zdo == null || !(item2.Zdo.m_uid == candidate.Zdo.m_uid)) && item2.Creator != playerId && !item2.IsPermitted(playerId) && Overlap(candidate, item2))
				{
					return item2;
				}
			}
			return null;
		}

		internal static bool Overlap(WardInfo a, WardInfo b)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0082: 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_0088: 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_00b2: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			a.Extents(out var shape, out var halfX, out var halfZ);
			b.Extents(out var shape2, out var halfX2, out var halfZ2);
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(a.Position.x, a.Position.z);
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(b.Position.x, b.Position.z);
			bool flag = shape == WardShape.Circle;
			bool flag2 = shape2 == WardShape.Circle;
			if (flag && flag2)
			{
				Vector2 val3 = val - val2;
				return ((Vector2)(ref val3)).magnitude < halfX + halfX2;
			}
			if (flag)
			{
				return CircleBox(val, halfX, val2, b.Rotation, halfX2, halfZ2);
			}
			if (flag2)
			{
				return CircleBox(val2, halfX2, val, a.Rotation, halfX, halfZ);
			}
			return BoxBox(val, a.Rotation, halfX, halfZ, val2, b.Rotation, halfX2, halfZ2);
		}

		private static void Axes(Quaternion rotation, out Vector2 x, out Vector2 z)
		{
			//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_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_0025: 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_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: 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_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = rotation * Vector3.right;
			Vector3 val2 = rotation * Vector3.forward;
			Vector2 val3 = new Vector2(val.x, val.z);
			x = ((Vector2)(ref val3)).normalized;
			val3 = new Vector2(val2.x, val2.z);
			z = ((Vector2)(ref val3)).normalized;
		}

		private static bool CircleBox(Vector2 circle, float r, Vector2 box, Quaternion rotation, float hx, float hz)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: 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_0012: 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_0034: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: 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_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_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			Axes(rotation, out var x, out var z);
			Vector2 val = circle - box;
			float num = Mathf.Clamp(Vector2.Dot(val, x), 0f - hx, hx);
			float num2 = Mathf.Clamp(Vector2.Dot(val, z), 0f - hz, hz);
			Vector2 val2 = box + x * num + z * num2;
			Vector2 val3 = circle - val2;
			return ((Vector2)(ref val3)).magnitude < r;
		}

		private static bool BoxBox(Vector2 ca, Quaternion ra, float ax, float az, Vector2 cb, Quaternion rb, float bx, float bz)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_0028: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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_0040: 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)
			//IL_0058: 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_0067: 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_007a: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			Axes(ra, out var x, out var z);
			Axes(rb, out var x2, out var z2);
			Vector2 val = cb - ca;
			Vector2[] array = (Vector2[])(object)new Vector2[4] { x, z, x2, z2 };
			foreach (Vector2 val2 in array)
			{
				float num = ax * Mathf.Abs(Vector2.Dot(x, val2)) + az * Mathf.Abs(Vector2.Dot(z, val2));
				float num2 = bx * Mathf.Abs(Vector2.Dot(x2, val2)) + bz * Mathf.Abs(Vector2.Dot(z2, val2));
				if (Mathf.Abs(Vector2.Dot(val, val2)) >= num + num2)
				{
					return false;
				}
			}
			return true;
		}

		internal static bool IsCreator(WardInfo ward, long playerId)
		{
			if (ward != null && playerId != 0L)
			{
				return ward.Creator == playerId;
			}
			return false;
		}

		internal static MemberPermission Permissions(WardInfo ward, long playerId)
		{
			if (ward == null || !ward.Valid || playerId == 0L)
			{
				return MemberPermission.None();
			}
			if (IsCreator(ward, playerId))
			{
				return MemberPermission.All();
			}
			if (!ward.IsPermitted(playerId))
			{
				return MemberPermission.None();
			}
			return ward.State.GetPermission(playerId);
		}

		internal static bool Has(WardInfo ward, long playerId, Func<MemberPermission, bool> check)
		{
			return check(Permissions(ward, playerId));
		}

		internal static bool AllowedAt(Vector3 point, long playerId, Func<MemberPermission, bool> check)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			foreach (WardInfo item in ActiveWardsAt(point))
			{
				if (!Has(item, playerId, check))
				{
					return false;
				}
			}
			return true;
		}

		internal static bool OperationAllowed(MemberPermission permission, ResourceOperation operation)
		{
			return operation switch
			{
				ResourceOperation.Build => permission.build, 
				ResourceOperation.Craft => permission.craft, 
				ResourceOperation.Upgrade => permission.upgrade, 
				_ => true, 
			};
		}

		internal static bool CanOpenPanel(WardInfo ward, long playerId)
		{
			if (ward == null || !ward.Valid || playerId == 0L)
			{
				return false;
			}
			if (IsCreator(ward, playerId))
			{
				return true;
			}
			if (SharedStorage.Enabled && ward.State.sharedStorage)
			{
				return Has(ward, playerId, (MemberPermission p) => p.useMaterials);
			}
			return false;
		}
	}
	internal sealed class WardPanel
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<KeyValuePair<string, int>, string> <>9__41_0;

			public static UnityAction <>9__43_0;

			public static Func<KeyValuePair<string, int>, string> <>9__48_1;

			internal string <Signature>b__41_0(KeyValuePair<string, int> t)
			{
				return t.Key;
			}

			internal void <Build>b__43_0()
			{
				Plugin.Instance?.ClosePanel();
			}

			internal string <FillMaterials>b__48_1(KeyValuePair<string, int> entry)
			{
				return GameAccess.Localize(entry.Key);
			}
		}

		private const float PanelWidth = 980f;

		private const float PanelHeight = 680f;

		private const float RowHeight = 34f;

		private static readonly string[] RightNames = new string[6] { "Usar materiais", "Abrir baús", "Construir", "Craftar", "Melhorar", "Demolir" };

		private GameObject root;

		private RectTransform body;

		private Text title;

		private Text status;

		private readonly List<Button> tabs = new List<Button>();

		private PrivateArea ward;

		private bool admin;

		private int page;

		private WardState pending;

		private float pendingUntil;

		private string search = string.Empty;

		private string signature;

		private float nextCheck;

		private List<FuelType> fuelTypes;

		private float fuelTypesUntil;

		private RectTransform materialContent;

		private readonly Dictionary<string, ScrollRect> scrolls = new Dictionary<string, ScrollRect>();

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

		private WardShape draftShape;

		private float draftRadius;

		private float draftX;

		private float draftZ;

		private bool draftDirty;

		private Text draftLabel1;

		private Text draftLabel2;

		private const int AreaPage = 3;

		internal bool IsOpen
		{
			get
			{
				if ((Object)(object)ward != (Object)null && (Object)(object)root != (Object)null)
				{
					return root.activeSelf;
				}
				return false;
			}
		}

		internal PrivateArea Ward => ward;

		internal bool Open(PrivateArea target, bool isAdmin)
		{
			if ((Object)(object)GUIManager.CustomGUIFront == (Object)null)
			{
				return false;
			}
			if ((Object)(object)root == (Object)null)
			{
				tabs.Clear();
				scrolls.Clear();
				Build();
			}
			ward = target;
			admin = isAdmin;
			pending = null;
			fuelTypes = null;
			search = string.Empty;
			scrollPositions.Clear();
			((Component)tabs[0]).gameObject.SetActive(admin);
			((Component)tabs[2]).gameObject.SetActive(admin);
			((Component)tabs[3]).gameObject.SetActive(admin);
			draftDirty = false;
			root.SetActive(true);
			SelectPage((!admin) ? 1 : 0);
			return true;
		}

		internal void Close()
		{
			if ((Object)(object)root != (Object)null)
			{
				root.SetActive(false);
			}
			ward = null;
			pending = null;
			AreaMarker.PreviewWard = null;
			AreaMarker.PreviewState = null;
		}

		internal void EveryFrame()
		{
			if (!IsOpen || page != 3 || !admin)
			{
				AreaMarker.PreviewWard = null;
				AreaMarker.PreviewState = null;
				return;
			}
			WardInfo wardInfo = WardAccess.Get(ward);
			if (wardInfo != null)
			{
				AreaMarker.PreviewWard = ward;
				AreaMarker.PreviewState = DraftState(wardInfo);
				ward.ShowAreaMarker();
			}
		}

		internal void Destroy()
		{
			if ((Object)(object)root != (Object)null)
			{
				Object.Destroy((Object)(object)root);
			}
			root = null;
			tabs.Clear();
		}

		internal void Update()
		{
			if (!IsOpen || Time.unscaledTime < nextCheck)
			{
				return;
			}
			nextCheck = Time.unscaledTime + 0.5f;
			WardInfo wardInfo = WardAccess.Get(ward);
			if (wardInfo != null)
			{
				status.text = "Ward de " + wardInfo.CreatorName + "   ·   área " + wardInfo.Describe() + "   ·   " + (wardInfo.Enabled ? "<color=#7CFC00>ATIVA</color>" : "<color=#FF6060>DESLIGADA — as regras só valem com a Ward ativa</color>");
				string text = Signature(wardInfo);
				if (text != signature)
				{
					Rebuild(wardInfo, text);
				}
			}
		}

		private WardState UiState(WardInfo info)
		{
			WardState state = info.State;
			if (pending != null && Time.unscaledTime < pendingUntil && JsonUtility.ToJson((object)state) != JsonUtility.ToJson((object)pending))
			{
				return pending;
			}
			pending = null;
			return state;
		}

		private void Edit(Action<WardState> change)
		{
			WardInfo wardInfo = WardAccess.Get(ward);
			if (admin && wardInfo != null)
			{
				WardState wardState = UiState(wardInfo).Clone();
				change(wardState);
				pending = wardState;
				pendingUntil = Time.unscaledTime + 3f;
				WardState.Submit(wardInfo, wardState);
				SharedStorage.Invalidate();
				fuelTypesUntil = 0f;
			}
		}

		private string Signature(WardInfo info)
		{
			WardState wardState = UiState(info);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(page).Append('|').Append(JsonUtility.ToJson((object)wardState))
				.Append('|')
				.Append(info.Enabled);
			switch (page)
			{
			case 0:
				foreach (KeyValuePair<long, string> item in info.PermittedPlayers())
				{
					stringBuilder.Append(item.Key).Append(':').Append(item.Value)
						.Append(';');
				}
				break;
			case 1:
			{
				Player localPlayer = Player.m_localPlayer;
				if (!((Object)(object)localPlayer != (Object)null) || !SharedStorage.Enabled)
				{
					break;
				}
				SharedStorage.Snapshot(ward, localPlayer.GetPlayerID(), out var so