Decompiled source of LinkedLightsCraft v1.2.4

plugins/LinkedLightsCraft.dll

Decompiled 4 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("LinkedLightsCraft")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LinkedLightsCraft")]
[assembly: AssemblyTitle("LinkedLightsCraft")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LinkedLightsCraft
{
	internal static class ValheimAccess
	{
		private static readonly FieldInfo CraftingStationAllStationsField = AccessTools.Field(typeof(CraftingStation), "m_allStations");

		private static readonly MethodInfo UITooltipUpdateTextElementsMethod = AccessTools.Method(typeof(UITooltip), "UpdateTextElements", (Type[])null, (Type[])null);

		private static readonly MethodInfo ZNetGetPeerByRpcMethod = AccessTools.Method(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null);

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

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

		private static readonly MethodInfo PrivateAreaHaveLocalAccessMethod = AccessTools.Method(typeof(PrivateArea), "HaveLocalAccess", (Type[])null, (Type[])null);

		private static readonly MethodInfo PrivateAreaFlashShieldMethod = AccessTools.Method(typeof(PrivateArea), "FlashShield", new Type[1] { typeof(bool) }, (Type[])null);

		private static readonly MethodInfo DlcManIsDlcInstalledMethod = AccessTools.Method(typeof(DLCMan), "IsDLCInstalled", new Type[1] { typeof(string) }, (Type[])null);

		private static readonly FieldInfo InventoryGuiCraftRecipeField = AccessTools.Field(typeof(InventoryGui), "m_craftRecipe");

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

		private static readonly FieldInfo InventoryGuiMultiCraftingField = AccessTools.Field(typeof(InventoryGui), "m_multiCrafting");

		private static readonly MethodInfo SmelterGetFuelMethod = AccessTools.Method(typeof(Smelter), "GetFuel", (Type[])null, (Type[])null);

		private static readonly MethodInfo SmelterGetQueueSizeMethod = AccessTools.Method(typeof(Smelter), "GetQueueSize", (Type[])null, (Type[])null);

		private static readonly MethodInfo SmelterOnAddFuelMethod = AccessTools.Method(typeof(Smelter), "OnAddFuel", new Type[3]
		{
			typeof(Switch),
			typeof(Humanoid),
			typeof(ItemData)
		}, (Type[])null);

		private static readonly MethodInfo SmelterOnAddOreMethod = AccessTools.Method(typeof(Smelter), "OnAddOre", new Type[3]
		{
			typeof(Switch),
			typeof(Humanoid),
			typeof(ItemData)
		}, (Type[])null);

		private static readonly MethodInfo CharacterMessageMethod = typeof(Character).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault(delegate(MethodInfo m)
		{
			if (m.Name != "Message")
			{
				return false;
			}
			ParameterInfo[] parameters = m.GetParameters();
			return parameters.Length >= 2 && parameters[0].ParameterType == typeof(MessageType) && parameters[1].ParameterType == typeof(string);
		});

		private static readonly ParameterInfo[] CharacterMessageParams = CharacterMessageMethod?.GetParameters();

		public static List<CraftingStation> GetAllCraftingStations()
		{
			return CraftingStationAllStationsField?.GetValue(null) as List<CraftingStation>;
		}

		public static void UpdateTooltipTextElements(UITooltip tooltip)
		{
			if ((Object)(object)tooltip != (Object)null)
			{
				UITooltipUpdateTextElementsMethod?.Invoke(tooltip, null);
			}
		}

		public static ZNetPeer GetPeer(ZNet znet, ZRpc rpc)
		{
			if (!((Object)(object)znet != (Object)null) || rpc == null)
			{
				return null;
			}
			object? obj = ZNetGetPeerByRpcMethod?.Invoke(znet, new object[1] { rpc });
			return (ZNetPeer)((obj is ZNetPeer) ? obj : null);
		}

		public static ZNetPeer GetPeer(ZNet znet, long uid)
		{
			if (!((Object)(object)znet != (Object)null))
			{
				return null;
			}
			object? obj = ZNetGetPeerByUidMethod?.Invoke(znet, new object[1] { uid });
			return (ZNetPeer)((obj is ZNetPeer) ? obj : null);
		}

		public static bool IsWardEnabled(PrivateArea ward)
		{
			if ((Object)(object)ward != (Object)null && PrivateAreaIsEnabledMethod != null)
			{
				return (bool)PrivateAreaIsEnabledMethod.Invoke(ward, null);
			}
			return false;
		}

		public static bool HaveLocalAccess(PrivateArea ward)
		{
			if ((Object)(object)ward != (Object)null && PrivateAreaHaveLocalAccessMethod != null)
			{
				return (bool)PrivateAreaHaveLocalAccessMethod.Invoke(ward, null);
			}
			return false;
		}

		public static void FlashShield(PrivateArea ward, bool flashConnected)
		{
			if ((Object)(object)ward != (Object)null)
			{
				PrivateAreaFlashShieldMethod?.Invoke(ward, new object[1] { flashConnected });
			}
		}

		public static bool IsDlcInstalled(DLCMan dlcMan, string dlc)
		{
			if (!((Object)(object)dlcMan == (Object)null) && !(DlcManIsDlcInstalledMethod == null))
			{
				return (bool)DlcManIsDlcInstalledMethod.Invoke(dlcMan, new object[1] { dlc });
			}
			return true;
		}

		public static Recipe GetCraftRecipe(InventoryGui gui)
		{
			if (!((Object)(object)gui != (Object)null))
			{
				return null;
			}
			object? obj = InventoryGuiCraftRecipeField?.GetValue(gui);
			return (Recipe)((obj is Recipe) ? obj : null);
		}

		public static ItemData GetCraftUpgradeItem(InventoryGui gui)
		{
			if (!((Object)(object)gui != (Object)null))
			{
				return null;
			}
			object? obj = InventoryGuiCraftUpgradeItemField?.GetValue(gui);
			return (ItemData)((obj is ItemData) ? obj : null);
		}

		public static bool IsMultiCrafting(InventoryGui gui)
		{
			if ((Object)(object)gui != (Object)null && InventoryGuiMultiCraftingField != null)
			{
				return (bool)InventoryGuiMultiCraftingField.GetValue(gui);
			}
			return false;
		}

		public static float GetSmelterFuel(Smelter smelter)
		{
			if (!((Object)(object)smelter != (Object)null) || !(SmelterGetFuelMethod != null))
			{
				return 0f;
			}
			return (float)SmelterGetFuelMethod.Invoke(smelter, null);
		}

		public static int GetSmelterQueueSize(Smelter smelter)
		{
			if (!((Object)(object)smelter != (Object)null) || !(SmelterGetQueueSizeMethod != null))
			{
				return 0;
			}
			return (int)SmelterGetQueueSizeMethod.Invoke(smelter, null);
		}

		public static void InvokeSmelterAddFuel(Smelter smelter, Switch sw, Humanoid user, ItemData item)
		{
			if ((Object)(object)smelter != (Object)null)
			{
				SmelterOnAddFuelMethod?.Invoke(smelter, new object[3] { sw, user, item });
			}
		}

		public static void InvokeSmelterAddOre(Smelter smelter, Switch sw, Humanoid user, ItemData item)
		{
			if ((Object)(object)smelter != (Object)null)
			{
				SmelterOnAddOreMethod?.Invoke(smelter, new object[3] { sw, user, item });
			}
		}

		public static void ShowCharacterMessage(Character character, MessageType type, string msg)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)character == (Object)null) && !(CharacterMessageMethod == null) && CharacterMessageParams != null)
			{
				object[] array = new object[CharacterMessageParams.Length];
				array[0] = type;
				array[1] = msg;
				for (int i = 2; i < CharacterMessageParams.Length; i++)
				{
					ParameterInfo parameterInfo = CharacterMessageParams[i];
					array[i] = (parameterInfo.HasDefaultValue ? parameterInfo.DefaultValue : (parameterInfo.ParameterType.IsValueType ? Activator.CreateInstance(parameterInfo.ParameterType) : null));
				}
				CharacterMessageMethod.Invoke(character, array);
			}
		}
	}
	[BepInPlugin("com.tingits.linkedlightscraft", "LinkedLightsCraft", "1.2.4")]
	public class LinkedLightsPlugin : BaseUnityPlugin
	{
		public const string ModGuid = "com.tingits.linkedlightscraft";

		public const string ModName = "LinkedLightsCraft";

		public const string ModVersion = "1.2.4";

		private const string WorkbenchStationName = "$piece_workbench";

		internal const string ExcludeChestZdoKey = "LinkedLights_ExcludePerimeter";

		internal static LinkedLightsPlugin Instance;

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> ModEnabledEntry;

		internal static ConfigEntry<bool> EnableServerConfigSyncEntry;

		internal static ConfigEntry<float> LightBuildRadiusEntry;

		internal static ConfigEntry<bool> RequireLitEntry;

		internal static ConfigEntry<bool> LinkOverlappingCirclesEntry;

		internal static ConfigEntry<bool> PreventItemDespawnEntry;

		internal static ConfigEntry<bool> ExtendWardsToPerimeterEntry;

		internal static ConfigEntry<string> AllowedLightPrefabsEntry;

		internal static ConfigEntry<bool> PullFromPerimeterChestsEntry;

		internal static ConfigEntry<bool> AllowFeedStationsEntry;

		internal static ConfigEntry<bool> AllowShipsAndCartsEntry;

		internal static ConfigEntry<string> DisallowedContainersEntry;

		internal static ConfigEntry<string> DisallowedItemsEntry;

		internal static ConfigEntry<KeyCode> FillModifierKeyEntry;

		internal static ConfigEntry<KeyCode> DisablePullKeyEntry;

		internal static ConfigEntry<bool> ShowLightCirclesEntry;

		internal static ConfigEntry<bool> ShowCombinedResourceCountsEntry;

		internal static ConfigEntry<bool> ShowChestToggleButtonEntry;

		internal static readonly HashSet<Fireplace> ActiveLights = new HashSet<Fireplace>();

		internal static readonly HashSet<Container> ActiveContainers = new HashSet<Container>();

		internal static readonly HashSet<PrivateArea> ActiveWards = new HashSet<PrivateArea>();

		private static HashSet<string> _allowedLightSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static HashSet<string> _disallowedContainerSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static HashSet<string> _disallowedItemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private Harmony _harmony;

		internal static bool IsEnabled
		{
			get
			{
				if (!ServerConfigSync.HasServerConfig)
				{
					return ModEnabledEntry.Value;
				}
				return ServerConfigSync.Enabled;
			}
		}

		internal static float LightRadius
		{
			get
			{
				if (!ServerConfigSync.HasServerConfig)
				{
					return LightBuildRadiusEntry.Value;
				}
				return ServerConfigSync.LightBuildRadius;
			}
		}

		internal static bool MustBeLit
		{
			get
			{
				if (!ServerConfigSync.HasServerConfig)
				{
					return RequireLitEntry.Value;
				}
				return ServerConfigSync.RequireLit;
			}
		}

		internal static bool OverlapMode
		{
			get
			{
				if (!ServerConfigSync.HasServerConfig)
				{
					return LinkOverlappingCirclesEntry.Value;
				}
				return ServerConfigSync.LinkOverlappingCircles;
			}
		}

		internal static bool KeepDroppedItems
		{
			get
			{
				if (!ServerConfigSync.HasServerConfig)
				{
					return PreventItemDespawnEntry.Value;
				}
				return ServerConfigSync.PreventItemDespawn;
			}
		}

		internal static bool ExtendWards
		{
			get
			{
				if (!ServerConfigSync.HasServerConfig)
				{
					return ExtendWardsToPerimeterEntry.Value;
				}
				return ServerConfigSync.ExtendWardsToPerimeter;
			}
		}

		internal static bool PullFromChests
		{
			get
			{
				if (!ServerConfigSync.HasServerConfig)
				{
					return PullFromPerimeterChestsEntry.Value;
				}
				return ServerConfigSync.PullFromPerimeterChests;
			}
		}

		internal static bool FeedStations
		{
			get
			{
				if (!ServerConfigSync.HasServerConfig)
				{
					return AllowFeedStationsEntry.Value;
				}
				return ServerConfigSync.AllowFeedStations;
			}
		}

		internal static bool IncludeShipsAndCarts
		{
			get
			{
				if (!ServerConfigSync.HasServerConfig)
				{
					return AllowShipsAndCartsEntry.Value;
				}
				return ServerConfigSync.AllowShipsAndCarts;
			}
		}

		private void Awake()
		{
			//IL_047e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0488: Expected O, but got Unknown
			Instance = this;
			ModEnabledEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "Enabled", true, "Enable or disable LinkedLightsCraft. (Synced with server)");
			EnableServerConfigSyncEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - General", "EnableServerConfigSync", true, "Sync server perimeter and storage settings to connected clients after login.");
			LightBuildRadiusEntry = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Perimeter", "LightBuildRadius", 12f, "Build perimeter radius (in meters) added by each torch, sconce, or light source. (Synced with server)");
			RequireLitEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("2 - Perimeter", "RequireLit", false, "If true, torches/sconces must have fuel and be burning to extend the build perimeter. (Synced with server)");
			LinkOverlappingCirclesEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("2 - Perimeter", "LinkOverlappingCircles", true, "If true, two nodes link whenever their perimeter circles overlap (radiusA + radiusB). If false, one node's center must lie inside the other's radius. (Synced with server)");
			PreventItemDespawnEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("2 - Perimeter", "PreventItemDespawn", true, "Prevent dropped items from despawning within a light source's LightBuildRadius when that light is connected to a Workbench. (Synced with server)");
			ExtendWardsToPerimeterEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("2 - Perimeter", "ExtendWardsToPerimeter", false, "If true, an active Ward inside a connected build perimeter extends its protection across the entire linked perimeter. Off by default so existing personal wards in shared bases do not lock out other players. (Synced with server)");
			AllowedLightPrefabsEntry = ((BaseUnityPlugin)this).Config.Bind<string>("2 - Perimeter", "AllowedLightPrefabs", "piece_walltorch,piece_groundtorch,piece_groundtorch_wood,piece_groundtorch_green,piece_groundtorch_blue,piece_brazierfloor01,piece_brazierfloor02,piece_brazierceiling01,fire_pit,bonfire,hearth,piece_jackoturnip", "Comma-separated list of Fireplace prefab names that extend the build perimeter. Leave blank to allow ALL Fireplace light sources. (Synced with server)");
			PullFromPerimeterChestsEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("3 - Perimeter Storage", "PullFromPerimeterChests", true, "Allow crafting, upgrading, and building using chests located anywhere inside the connected build perimeter. (Synced with server)");
			AllowFeedStationsEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("3 - Perimeter Storage", "AllowFeedStations", true, "Allow smelters, kilns, windmills, spinning wheels, fires/torches, cooking stations, and ballistas to pull fuel/ore/food/ammo from perimeter-linked chests. (Synced with server)");
			AllowShipsAndCartsEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("3 - Perimeter Storage", "AllowShipsAndCarts", false, "Include carts and ship holds inside the build perimeter when pulling materials. (Synced with server)");
			DisallowedContainersEntry = ((BaseUnityPlugin)this).Config.Bind<string>("3 - Perimeter Storage", "DisallowedContainers", "piece_chest_private", "Comma-separated container prefab names that will never be pulled from. (Synced with server)");
			DisallowedItemsEntry = ((BaseUnityPlugin)this).Config.Bind<string>("3 - Perimeter Storage", "DisallowedItems", "", "Comma-separated item prefab names (e.g. FineWood,RoundLog) that will never be pulled automatically from chests. (Synced with server)");
			FillModifierKeyEntry = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("3 - Perimeter Storage", "FillModifierKey", (KeyCode)304, "Hold this key when interacting with a smelter, kiln, fire, or turret to pull until full. (Client-side)");
			DisablePullKeyEntry = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("3 - Perimeter Storage", "DisablePullKey", (KeyCode)308, "Hold this key to temporarily disable pulling items from chests. (Client-side)");
			ShowLightCirclesEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("4 - Visuals", "ShowLightCircles", true, "Draw build perimeter circles around nearby light sources when holding the Hammer (green-gold = connected, dim red-gray = unlinked). (Client-side)");
			ShowCombinedResourceCountsEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("4 - Visuals", "ShowCombinedResourceCounts", true, "Display combined player + perimeter chest resource totals in crafting and build menus. (Client-side)");
			ShowChestToggleButtonEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("4 - Visuals", "ShowChestToggleButton", true, "Show an Include/Exclude button in the chest menu to control whether that chest counts toward the build/craft perimeter. (Client-side)");
			RebuildAllCaches(AllowedLightPrefabsEntry.Value, DisallowedContainersEntry.Value, DisallowedItemsEntry.Value);
			ModEnabledEntry.SettingChanged += delegate
			{
				ServerConfigSync.BroadcastToAllClients();
			};
			LightBuildRadiusEntry.SettingChanged += delegate
			{
				ServerConfigSync.BroadcastToAllClients();
			};
			RequireLitEntry.SettingChanged += delegate
			{
				ServerConfigSync.BroadcastToAllClients();
			};
			LinkOverlappingCirclesEntry.SettingChanged += delegate
			{
				ServerConfigSync.BroadcastToAllClients();
			};
			PreventItemDespawnEntry.SettingChanged += delegate
			{
				ServerConfigSync.BroadcastToAllClients();
			};
			ExtendWardsToPerimeterEntry.SettingChanged += delegate
			{
				ServerConfigSync.BroadcastToAllClients();
			};
			PullFromPerimeterChestsEntry.SettingChanged += delegate
			{
				ServerConfigSync.BroadcastToAllClients();
			};
			AllowFeedStationsEntry.SettingChanged += delegate
			{
				ServerConfigSync.BroadcastToAllClients();
			};
			AllowShipsAndCartsEntry.SettingChanged += delegate
			{
				ServerConfigSync.BroadcastToAllClients();
			};
			AllowedLightPrefabsEntry.SettingChanged += delegate
			{
				SyncAndRebuildLists();
			};
			DisallowedContainersEntry.SettingChanged += delegate
			{
				SyncAndRebuildLists();
			};
			DisallowedItemsEntry.SettingChanged += delegate
			{
				SyncAndRebuildLists();
			};
			Log = ((BaseUnityPlugin)this).Logger;
			_harmony = new Harmony("com.tingits.linkedlightscraft");
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LinkedLightsCraft v1.2.4 loaded.");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			ActiveLights.Clear();
			ActiveContainers.Clear();
			ActiveWards.Clear();
			PerimeterGraphCache.Clear();
			ServerConfigSync.Reset();
			Instance = null;
		}

		private static void SyncAndRebuildLists()
		{
			if (!ServerConfigSync.HasServerConfig)
			{
				RebuildAllCaches(AllowedLightPrefabsEntry.Value, DisallowedContainersEntry.Value, DisallowedItemsEntry.Value);
			}
			ServerConfigSync.BroadcastToAllClients();
		}

		internal static void RebuildAllCaches(string lightsCsv, string containersCsv, string itemsCsv)
		{
			_allowedLightSet = ParseCsvSet(lightsCsv);
			_disallowedContainerSet = ParseCsvSet(containersCsv);
			_disallowedItemSet = ParseCsvSet(itemsCsv);
			PerimeterGraphCache.Clear();
			PerimeterStorage.InvalidateCache();
		}

		private static HashSet<string> ParseCsvSet(string rawCsv)
		{
			return new HashSet<string>(from s in (rawCsv ?? string.Empty).Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries)
				select s.Trim() into s
				where s.Length > 0
				select s, StringComparer.OrdinalIgnoreCase);
		}

		internal static bool IsPullSuppressedByKey()
		{
			//IL_0005: 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_000e: Unknown result type (might be due to invalid IL or missing references)
			KeyCode value = DisablePullKeyEntry.Value;
			if ((int)value != 0)
			{
				return Input.GetKey(value);
			}
			return false;
		}

		internal static bool IsFillModifierHeld()
		{
			//IL_0005: 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_000e: Unknown result type (might be due to invalid IL or missing references)
			KeyCode value = FillModifierKeyEntry.Value;
			if ((int)value != 0)
			{
				return Input.GetKey(value);
			}
			return false;
		}

		internal static bool IsItemAllowedFromChests(ItemData item)
		{
			if (item == null)
			{
				return false;
			}
			if (_disallowedItemSet.Count == 0)
			{
				return true;
			}
			string text = (((Object)(object)item.m_dropPrefab != (Object)null) ? ((Object)item.m_dropPrefab).name : null);
			if (!string.IsNullOrEmpty(text) && _disallowedItemSet.Contains(text))
			{
				return false;
			}
			string text2 = item.m_shared?.m_name;
			if (!string.IsNullOrEmpty(text2) && _disallowedItemSet.Contains(text2))
			{
				return false;
			}
			return true;
		}

		internal static bool IsValidLightRelay(Fireplace fp)
		{
			if ((Object)(object)fp == (Object)null || !((Behaviour)fp).isActiveAndEnabled)
			{
				return false;
			}
			ZNetView component = ((Component)fp).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return false;
			}
			if (MustBeLit && !fp.IsBurning())
			{
				return false;
			}
			if (_allowedLightSet.Count > 0)
			{
				string prefabName = Utils.GetPrefabName(((Component)fp).gameObject);
				if (!_allowedLightSet.Contains(prefabName))
				{
					return false;
				}
			}
			return true;
		}

		internal static bool IsContainerTypeSupported(Container container)
		{
			if ((Object)(object)container == (Object)null || !((Behaviour)container).isActiveAndEnabled || container.m_autoDestroyEmpty || container.GetInventory() == null)
			{
				return false;
			}
			ZNetView component = ((Component)container).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return false;
			}
			bool num = (Object)(object)((Component)container).GetComponent<Piece>() != (Object)null;
			bool flag = (Object)(object)((Component)container).GetComponentInParent<Vagon>() != (Object)null || (Object)(object)((Component)container).GetComponentInParent<Ship>() != (Object)null;
			if (!num && !(IncludeShipsAndCarts && flag))
			{
				return false;
			}
			if (_disallowedContainerSet.Count > 0)
			{
				string prefabName = Utils.GetPrefabName(((Component)container).gameObject);
				if (_disallowedContainerSet.Contains(prefabName))
				{
					return false;
				}
			}
			return true;
		}

		internal static bool IsContainerExcludedByToggle(Container container)
		{
			if ((Object)(object)container == (Object)null)
			{
				return true;
			}
			ZNetView component = ((Component)container).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return false;
			}
			ZDO zDO = component.GetZDO();
			if (zDO != null)
			{
				return zDO.GetBool("LinkedLights_ExcludePerimeter", false);
			}
			return false;
		}

		internal static void SetContainerExcludedByToggle(Container container, bool excluded)
		{
			if ((Object)(object)container == (Object)null)
			{
				return;
			}
			ZNetView component = ((Component)container).GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.IsValid())
			{
				if (!component.IsOwner())
				{
					component.ClaimOwnership();
				}
				ZDO zDO = component.GetZDO();
				if (zDO != null)
				{
					zDO.Set("LinkedLights_ExcludePerimeter", excluded);
				}
			}
		}

		internal static bool IsEligibleContainer(Container container)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!IsContainerTypeSupported(container))
			{
				return false;
			}
			if (container.IsInUse())
			{
				return false;
			}
			if (IsContainerExcludedByToggle(container))
			{
				return false;
			}
			if (!PrivateArea.CheckAccess(((Component)container).transform.position, 0f, false, false))
			{
				return false;
			}
			return true;
		}

		internal static bool IsProtectedByWorkbenchLinkedLight(Vector3 point)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			List<PerimeterNode> nodes = PerimeterGraphCache.GetNodes();
			if (nodes.Count == 0)
			{
				return false;
			}
			int num = -1;
			for (int i = 0; i < nodes.Count; i++)
			{
				if ((Object)(object)nodes[i].Light == (Object)null)
				{
					continue;
				}
				float radius = nodes[i].Radius;
				Vector3 val = point - nodes[i].Position;
				if (!(((Vector3)(ref val)).sqrMagnitude <= radius * radius))
				{
					continue;
				}
				int componentId = nodes[i].ComponentId;
				if (componentId == num)
				{
					continue;
				}
				num = componentId;
				for (int j = 0; j < nodes.Count; j++)
				{
					if ((Object)(object)nodes[j].Station != (Object)null && nodes[j].ComponentId == componentId && nodes[j].StationName == "$piece_workbench")
					{
						return true;
					}
				}
			}
			return false;
		}
	}
	internal struct PerimeterNode
	{
		public Vector3 Position;

		public float Radius;

		public string StationName;

		public CraftingStation Station;

		public Fireplace Light;

		public int ComponentId;
	}
	internal static class PerimeterGraphCache
	{
		private const float CacheTtlSeconds = 0.25f;

		private static float _cachedTime = -10f;

		private static int _lastStationCount = -1;

		private static int _lastLightCount = -1;

		private static readonly List<PerimeterNode> _nodes = new List<PerimeterNode>();

		private static readonly HashSet<Fireplace> _stationConnectedLights = new HashSet<Fireplace>();

		private static int[] _parentBuf = Array.Empty<int>();

		private static bool[] _hasStationBuf = Array.Empty<bool>();

		public static void Clear()
		{
			_cachedTime = -10f;
			_lastStationCount = -1;
			_lastLightCount = -1;
			_nodes.Clear();
			_stationConnectedLights.Clear();
			LightRingVisual.MarkDirty();
		}

		public static List<PerimeterNode> GetNodes()
		{
			EnsureBuilt();
			return _nodes;
		}

		public static HashSet<Fireplace> GetStationConnectedLights()
		{
			EnsureBuilt();
			return _stationConnectedLights;
		}

		private static void EnsureBuilt()
		{
			//IL_0099: 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_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			List<CraftingStation> allCraftingStations = ValheimAccess.GetAllCraftingStations();
			int num = allCraftingStations?.Count ?? 0;
			int count = LinkedLightsPlugin.ActiveLights.Count;
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime - _cachedTime <= 0.25f && num == _lastStationCount && count == _lastLightCount)
			{
				return;
			}
			_cachedTime = unscaledTime;
			_nodes.Clear();
			_stationConnectedLights.Clear();
			if (allCraftingStations != null)
			{
				foreach (CraftingStation item in allCraftingStations)
				{
					if (!((Object)(object)item == (Object)null))
					{
						_nodes.Add(new PerimeterNode
						{
							Position = ((Component)item).transform.position,
							Radius = Mathf.Max(item.m_rangeBuild, 1f),
							StationName = item.m_name,
							Station = item,
							Light = null,
							ComponentId = _nodes.Count
						});
					}
				}
			}
			float radius = Mathf.Max(LinkedLightsPlugin.LightRadius, 0.5f);
			if (LinkedLightsPlugin.ActiveLights.RemoveWhere((Fireplace fp) => (Object)(object)fp == (Object)null) > 0)
			{
				LightRingVisual.MarkDirty();
			}
			_lastStationCount = num;
			_lastLightCount = LinkedLightsPlugin.ActiveLights.Count;
			foreach (Fireplace activeLight in LinkedLightsPlugin.ActiveLights)
			{
				if (LinkedLightsPlugin.IsValidLightRelay(activeLight))
				{
					_nodes.Add(new PerimeterNode
					{
						Position = ((Component)activeLight).transform.position,
						Radius = radius,
						StationName = null,
						Station = null,
						Light = activeLight,
						ComponentId = _nodes.Count
					});
				}
			}
			int count2 = _nodes.Count;
			if (count2 == 0)
			{
				return;
			}
			if (_parentBuf.Length < count2)
			{
				_parentBuf = new int[count2];
				_hasStationBuf = new bool[count2];
			}
			for (int num2 = 0; num2 < count2; num2++)
			{
				_parentBuf[num2] = num2;
				_hasStationBuf[num2] = _nodes[num2].StationName != null;
			}
			bool overlapMode = LinkedLightsPlugin.OverlapMode;
			for (int num3 = 0; num3 < count2; num3++)
			{
				PerimeterNode perimeterNode = _nodes[num3];
				for (int num4 = num3 + 1; num4 < count2; num4++)
				{
					PerimeterNode perimeterNode2 = _nodes[num4];
					float num5 = (overlapMode ? (perimeterNode.Radius + perimeterNode2.Radius) : Mathf.Max(perimeterNode.Radius, perimeterNode2.Radius));
					Vector3 val = perimeterNode.Position - perimeterNode2.Position;
					if (((Vector3)(ref val)).sqrMagnitude <= num5 * num5)
					{
						int num6 = Find(num3);
						int num7 = Find(num4);
						if (num6 != num7)
						{
							_parentBuf[num7] = num6;
							ref bool reference = ref _hasStationBuf[num6];
							reference |= _hasStationBuf[num7];
						}
					}
				}
			}
			for (int num8 = 0; num8 < count2; num8++)
			{
				int num9 = Find(num8);
				PerimeterNode value = _nodes[num8];
				value.ComponentId = num9;
				_nodes[num8] = value;
				if ((Object)(object)value.Light != (Object)null && _hasStationBuf[num9])
				{
					_stationConnectedLights.Add(value.Light);
				}
			}
			static int Find(int x)
			{
				while (_parentBuf[x] != x)
				{
					_parentBuf[x] = _parentBuf[_parentBuf[x]];
					x = _parentBuf[x];
				}
				return x;
			}
		}
	}
	internal static class PerimeterStorage
	{
		private const string RemoveChestRpcName = "LinkedLights_RemoveFromChest";

		private const float CacheTtlSeconds = 0.35f;

		private const float CacheMaxMoveSqr = 4f;

		private static float _cacheTime = -10f;

		private static Vector3 _cacheOrigin;

		private static Dictionary<string, int> _cachedItemCounts;

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

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

		public static void InvalidateCache()
		{
			_cachedItemCounts = null;
			_cacheTime = -10f;
		}

		public static void RegisterRpc()
		{
			try
			{
				if (ZRoutedRpc.instance != null)
				{
					ZRoutedRpc.instance.Register<ZPackage>("LinkedLights_RemoveFromChest", (Action<long, ZPackage>)RPC_RemoveFromChest);
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log = LinkedLightsPlugin.Log;
				if (log != null)
				{
					log.LogError((object)string.Format("Failed to register {0}: {1}", "LinkedLights_RemoveFromChest", arg));
				}
			}
		}

		public static List<Container> GetLinkedContainers(Vector3 origin)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			List<Container> list = new List<Container>();
			if (!LinkedLightsPlugin.IsEnabled || !LinkedLightsPlugin.PullFromChests || LinkedLightsPlugin.IsPullSuppressedByKey())
			{
				return list;
			}
			List<PerimeterNode> nodes = PerimeterGraphCache.GetNodes();
			if (nodes.Count == 0)
			{
				return list;
			}
			_activeComponentsScratch.Clear();
			AddCoveringComponents(nodes, origin, _activeComponentsScratch);
			if (_activeComponentsScratch.Count == 0 && (Object)(object)Player.m_localPlayer != (Object)null)
			{
				AddCoveringComponents(nodes, ((Component)Player.m_localPlayer).transform.position, _activeComponentsScratch);
			}
			if (_activeComponentsScratch.Count == 0)
			{
				return list;
			}
			LinkedLightsPlugin.ActiveContainers.RemoveWhere((Container c) => (Object)(object)c == (Object)null);
			foreach (Container activeContainer in LinkedLightsPlugin.ActiveContainers)
			{
				if (!LinkedLightsPlugin.IsEligibleContainer(activeContainer))
				{
					continue;
				}
				Vector3 position = ((Component)activeContainer).transform.position;
				bool flag = false;
				for (int num = 0; num < nodes.Count; num++)
				{
					if (_activeComponentsScratch.Contains(nodes[num].ComponentId))
					{
						float radius = nodes[num].Radius;
						Vector3 val = position - nodes[num].Position;
						if (((Vector3)(ref val)).sqrMagnitude <= radius * radius)
						{
							flag = true;
							break;
						}
					}
				}
				if (flag)
				{
					list.Add(activeContainer);
				}
			}
			list.Sort((Container a, Container b) => Vector3.SqrMagnitude(((Component)a).transform.position - origin).CompareTo(Vector3.SqrMagnitude(((Component)b).transform.position - origin)));
			return list;
		}

		private static void AddCoveringComponents(List<PerimeterNode> nodes, Vector3 point, HashSet<int> targetSet)
		{
			//IL_0011: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < nodes.Count; i++)
			{
				float radius = nodes[i].Radius;
				Vector3 val = point - nodes[i].Position;
				if (((Vector3)(ref val)).sqrMagnitude <= radius * radius)
				{
					targetSet.Add(nodes[i].ComponentId);
				}
			}
		}

		public static int CountItem(Vector3 origin, string sharedName, int quality = -1)
		{
			//IL_0030: 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)
			if (string.IsNullOrEmpty(sharedName))
			{
				return 0;
			}
			if (quality < 0)
			{
				EnsureCountCache(origin);
				if (_cachedItemCounts == null || !_cachedItemCounts.TryGetValue(sharedName, out var value))
				{
					return 0;
				}
				return value;
			}
			int num = 0;
			List<Container> linkedContainers = GetLinkedContainers(origin);
			for (int i = 0; i < linkedContainers.Count; i++)
			{
				Inventory inventory = linkedContainers[i].GetInventory();
				if (inventory == null)
				{
					continue;
				}
				foreach (ItemData allItem in inventory.GetAllItems())
				{
					if (allItem != null && allItem.m_shared != null && !(allItem.m_shared.m_name != sharedName) && allItem.m_quality == quality && LinkedLightsPlugin.IsItemAllowedFromChests(allItem))
					{
						num += allItem.m_stack;
					}
				}
			}
			return num;
		}

		private static void EnsureCountCache(Vector3 origin)
		{
			//IL_0037: 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_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_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			if (_cachedItemCounts != null && Time.unscaledTime - _cacheTime <= 0.35f && Vector3.SqrMagnitude(origin - _cacheOrigin) <= 4f)
			{
				return;
			}
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			List<Container> linkedContainers = GetLinkedContainers(origin);
			for (int i = 0; i < linkedContainers.Count; i++)
			{
				Inventory inventory = linkedContainers[i].GetInventory();
				if (inventory == null)
				{
					continue;
				}
				foreach (ItemData allItem in inventory.GetAllItems())
				{
					if (allItem != null && allItem.m_shared != null && LinkedLightsPlugin.IsItemAllowedFromChests(allItem))
					{
						string name = allItem.m_shared.m_name;
						if (!string.IsNullOrEmpty(name))
						{
							dictionary[name] = (dictionary.TryGetValue(name, out var value) ? (value + allItem.m_stack) : allItem.m_stack);
						}
					}
				}
			}
			_cachedItemCounts = dictionary;
			_cacheOrigin = origin;
			_cacheTime = Time.unscaledTime;
		}

		public static int RemoveItem(Vector3 origin, string sharedName, int amount, int quality = -1)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (amount <= 0 || string.IsNullOrEmpty(sharedName))
			{
				return 0;
			}
			int num = amount;
			List<Container> linkedContainers = GetLinkedContainers(origin);
			for (int i = 0; i < linkedContainers.Count; i++)
			{
				if (num <= 0)
				{
					break;
				}
				num -= RemoveFromContainer(linkedContainers[i], sharedName, num, quality);
			}
			if (num < amount)
			{
				InvalidateCache();
			}
			return amount - num;
		}

		internal static int RemoveFromContainer(Container container, string sharedName, int amount, int quality = -1)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)container == (Object)null || amount <= 0 || string.IsNullOrEmpty(sharedName))
			{
				return 0;
			}
			Inventory inventory = container.GetInventory();
			if (inventory == null)
			{
				return 0;
			}
			ZNetView component = ((Component)container).GetComponent<ZNetView>();
			bool flag = (Object)(object)component == (Object)null || !component.IsValid() || component.IsOwner();
			if (!flag && ZRoutedRpc.instance != null)
			{
				ZDO zDO = component.GetZDO();
				long num = ((zDO != null) ? zDO.GetOwner() : 0);
				if (zDO != null && num != 0L)
				{
					int num2 = RemoveFromInventoryLocal(inventory, sharedName, amount, quality);
					if (num2 > 0)
					{
						SendRemoveFromChestRpc(num, zDO.m_uid, sharedName, num2, quality);
						InvalidateCache();
					}
					return num2;
				}
			}
			int num3 = RemoveFromInventoryLocal(inventory, sharedName, amount, quality);
			if (num3 > 0)
			{
				if (!flag)
				{
					SaveContainer(container);
				}
				InvalidateCache();
			}
			return num3;
		}

		private static int RemoveFromInventoryLocal(Inventory inv, string sharedName, int amount, int quality)
		{
			int num = amount;
			List<ItemData> allItems = inv.GetAllItems();
			int num2 = allItems.Count - 1;
			while (num2 >= 0 && num > 0)
			{
				ItemData val = allItems[num2];
				if (val != null && val.m_shared != null && !(val.m_shared.m_name != sharedName) && (quality < 0 || val.m_quality == quality) && LinkedLightsPlugin.IsItemAllowedFromChests(val))
				{
					int num3 = Mathf.Min(val.m_stack, num);
					inv.RemoveItem(val, num3);
					num -= num3;
				}
				num2--;
			}
			return amount - num;
		}

		private static void SendRemoveFromChestRpc(long ownerPeerId, ZDOID zdoid, string sharedName, int amount, int quality)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ZPackage val = new ZPackage();
				val.Write(zdoid);
				val.Write(sharedName);
				val.Write(amount);
				val.Write(quality);
				ZRoutedRpc.instance.InvokeRoutedRPC(ownerPeerId, "LinkedLights_RemoveFromChest", new object[1] { val });
			}
			catch (Exception arg)
			{
				ManualLogSource log = LinkedLightsPlugin.Log;
				if (log != null)
				{
					log.LogError((object)string.Format("Failed to send {0} to owner {1}: {2}", "LinkedLights_RemoveFromChest", ownerPeerId, arg));
				}
			}
		}

		private static void RPC_RemoveFromChest(long sender, ZPackage pkg)
		{
			//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_0044: Unknown result type (might be due to invalid IL or missing references)
			if (pkg == null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			try
			{
				ZDOID val = pkg.ReadZDOID();
				string text = pkg.ReadString();
				int num = pkg.ReadInt();
				int quality = pkg.ReadInt();
				if (num <= 0 || string.IsNullOrEmpty(text))
				{
					return;
				}
				GameObject val2 = ZNetScene.instance.FindInstance(val);
				if ((Object)(object)val2 == (Object)null)
				{
					return;
				}
				Container component = val2.GetComponent<Container>();
				if ((Object)(object)component == (Object)null || component.IsInUse())
				{
					return;
				}
				ZNetView component2 = ((Component)component).GetComponent<ZNetView>();
				if (!((Object)(object)component2 == (Object)null) && component2.IsValid() && component2.IsOwner())
				{
					Inventory inventory = component.GetInventory();
					if (inventory != null && RemoveFromInventoryLocal(inventory, text, num, quality) > 0)
					{
						InvalidateCache();
					}
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log = LinkedLightsPlugin.Log;
				if (log != null)
				{
					log.LogError((object)string.Format("Failed to process {0}: {1}", "LinkedLights_RemoveFromChest", arg));
				}
			}
		}

		public static void ReturnItem(Container preferredContainer, Vector3 fallbackOrigin, ItemData item)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			if (item == null || item.m_stack <= 0)
			{
				return;
			}
			if ((Object)(object)preferredContainer != (Object)null && CanWriteContainerSafely(preferredContainer) && preferredContainer.GetInventory() != null)
			{
				ZNetView component = ((Component)preferredContainer).GetComponent<ZNetView>();
				bool flag = (Object)(object)component == (Object)null || !component.IsValid() || component.IsOwner();
				if (preferredContainer.GetInventory().AddItem(item))
				{
					if (!flag)
					{
						SaveContainer(preferredContainer);
					}
					InvalidateCache();
					return;
				}
			}
			List<Container> linkedContainers = GetLinkedContainers(fallbackOrigin);
			for (int i = 0; i < linkedContainers.Count; i++)
			{
				if (!CanWriteContainerSafely(linkedContainers[i]))
				{
					continue;
				}
				ZNetView component2 = ((Component)linkedContainers[i]).GetComponent<ZNetView>();
				bool flag2 = (Object)(object)component2 == (Object)null || !component2.IsValid() || component2.IsOwner();
				Inventory inventory = linkedContainers[i].GetInventory();
				if (inventory != null && inventory.AddItem(item))
				{
					if (!flag2)
					{
						SaveContainer(linkedContainers[i]);
					}
					InvalidateCache();
					return;
				}
			}
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				ItemDrop.DropItem(item, item.m_stack, ((Component)Player.m_localPlayer).transform.position + Vector3.up, Quaternion.identity);
			}
		}

		private static bool CanWriteContainerSafely(Container container)
		{
			if ((Object)(object)container == (Object)null || container.IsInUse())
			{
				return false;
			}
			ZNetView component = ((Component)container).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return true;
			}
			if (component.IsOwner())
			{
				return true;
			}
			ZDO zDO = component.GetZDO();
			if (zDO != null)
			{
				return zDO.GetOwner() == 0;
			}
			return false;
		}

		private static void SaveContainer(Container container)
		{
			ZNetView component = ((Component)container).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid() && !component.IsOwner())
			{
				component.ClaimOwnership();
			}
			ContainerSaveMethod?.Invoke(container, null);
		}
	}
	internal static class ChestToggleUI
	{
		private const string ButtonName = "LinkedLights_PerimeterToggleBtn";

		private const string IconObjectName = "LinkedLights_VennIcon";

		private const string TooltipText = "Include/exclude from perimeter pull";

		private static Container _activeContainer;

		private static GameObject _buttonObj;

		private static Component _iconImage;

		private static UITooltip _tooltip;

		private static Sprite _includedSprite;

		private static Sprite _excludedSprite;

		public static void OnContainerOpened(InventoryGui gui, Container container)
		{
			_activeContainer = container;
			PerimeterStorage.InvalidateCache();
			Refresh(gui);
		}

		public static void OnContainerClosed()
		{
			_activeContainer = null;
			PerimeterStorage.InvalidateCache();
			if ((Object)(object)_buttonObj != (Object)null)
			{
				_buttonObj.SetActive(false);
			}
		}

		public static void Refresh(InventoryGui gui)
		{
			if ((Object)(object)gui == (Object)null || (Object)(object)gui.m_container == (Object)null)
			{
				return;
			}
			if (!LinkedLightsPlugin.IsEnabled || !LinkedLightsPlugin.PullFromChests || !LinkedLightsPlugin.ShowChestToggleButtonEntry.Value || !((Object)(object)_activeContainer != (Object)null) || !LinkedLightsPlugin.IsContainerTypeSupported(_activeContainer))
			{
				if ((Object)(object)_buttonObj != (Object)null)
				{
					_buttonObj.SetActive(false);
				}
				return;
			}
			EnsureButtonCreated(gui);
			if (!((Object)(object)_buttonObj == (Object)null))
			{
				_buttonObj.SetActive(true);
				UpdateButtonVisuals(LinkedLightsPlugin.IsContainerExcludedByToggle(_activeContainer));
			}
		}

		private static void EnsureButtonCreated(InventoryGui gui)
		{
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0303: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: 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_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_04be: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_050b: Unknown result type (might be due to invalid IL or missing references)
			//IL_051f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0495: Unknown result type (might be due to invalid IL or missing references)
			//IL_049b: Expected O, but got Unknown
			if ((Object)(object)_buttonObj != (Object)null)
			{
				return;
			}
			object? obj = typeof(InventoryGui).GetField("m_takeAllButton", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(gui);
			Component val = (Component)((obj is Component) ? obj : null);
			object? obj2 = typeof(InventoryGui).GetField("m_stackAllButton", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(gui);
			Component val2 = (Component)((obj2 is Component) ? obj2 : null);
			Component val3 = val ?? val2;
			if ((Object)(object)val3 == (Object)null)
			{
				return;
			}
			Transform val4 = (Transform)(((Object)(object)val3.transform.parent != (Object)null) ? ((object)val3.transform.parent) : ((object)gui.m_container));
			Transform val5 = val4.Find("LinkedLights_PerimeterToggleBtn");
			if ((Object)(object)val5 != (Object)null)
			{
				_buttonObj = ((Component)val5).gameObject;
				Transform obj3 = _buttonObj.transform.Find("LinkedLights_VennIcon");
				_iconImage = ((obj3 != null) ? ((Component)obj3).GetComponent("Image") : null);
				_tooltip = _buttonObj.GetComponent<UITooltip>();
				return;
			}
			_buttonObj = Object.Instantiate<GameObject>(val3.gameObject, val4);
			((Object)_buttonObj).name = "LinkedLights_PerimeterToggleBtn";
			_buttonObj.transform.SetAsLastSibling();
			RectTransform component = _buttonObj.GetComponent<RectTransform>();
			RectTransform val6 = (((Object)(object)val != (Object)null) ? val.GetComponent<RectTransform>() : null);
			RectTransform val7 = (((Object)(object)val2 != (Object)null) ? val2.GetComponent<RectTransform>() : null);
			RectTransform val8 = val6;
			if ((Object)(object)val7 != (Object)null && ((Object)(object)val8 == (Object)null || val7.anchoredPosition.x > val8.anchoredPosition.x))
			{
				val8 = val7;
			}
			if ((Object)(object)component != (Object)null && (Object)(object)val8 != (Object)null)
			{
				component.anchorMin = val8.anchorMin;
				component.anchorMax = val8.anchorMax;
				component.pivot = new Vector2(0f, 0.5f);
				component.sizeDelta = new Vector2(36f, 36f);
				Rect rect = val8.rect;
				float num;
				if (!(((Rect)(ref rect)).width > 1f))
				{
					num = val8.sizeDelta.x;
				}
				else
				{
					rect = val8.rect;
					num = ((Rect)(ref rect)).width;
				}
				float num2 = num;
				float num3 = val8.anchoredPosition.x + num2 * (1f - val8.pivot.x);
				float y = val8.anchoredPosition.y;
				rect = val8.rect;
				float num4 = y + ((Rect)(ref rect)).height * (0.5f - val8.pivot.y);
				component.anchoredPosition = new Vector2(num3 + 8f, num4);
			}
			else if ((Object)(object)component != (Object)null)
			{
				component.anchorMin = new Vector2(1f, 1f);
				component.anchorMax = new Vector2(1f, 1f);
				component.pivot = new Vector2(0f, 1f);
				component.anchoredPosition = new Vector2(8f, -12f);
				component.sizeDelta = new Vector2(36f, 36f);
			}
			Component component2 = _buttonObj.GetComponent("UIGamePad");
			if ((Object)(object)component2 != (Object)null)
			{
				Object.Destroy((Object)(object)component2);
			}
			Type type = null;
			Component[] componentsInChildren = _buttonObj.GetComponentsInChildren<Component>(true);
			foreach (Component val9 in componentsInChildren)
			{
				if ((Object)(object)val9 == (Object)null)
				{
					continue;
				}
				switch (((object)val9).GetType().Name)
				{
				case "Image":
					if (type == null)
					{
						type = ((object)val9).GetType();
					}
					if ((Object)(object)val9.gameObject != (Object)(object)_buttonObj)
					{
						val9.gameObject.SetActive(false);
					}
					break;
				case "Localize":
					Object.Destroy((Object)(object)val9);
					break;
				case "TMP_Text":
				case "TextMeshProUGUI":
				case "Text":
					val9.gameObject.SetActive(false);
					break;
				}
			}
			Component component3 = _buttonObj.GetComponent("Button");
			if ((Object)(object)component3 != (Object)null)
			{
				PropertyInfo property = ((object)component3).GetType().GetProperty("onClick");
				Type type2 = property?.PropertyType;
				if (type2 != null)
				{
					object obj4 = Activator.CreateInstance(type2);
					type2.GetMethod("AddListener", new Type[1] { typeof(UnityAction) })?.Invoke(obj4, new object[1] { (object)new UnityAction(OnToggleClicked) });
					property.SetValue(component3, obj4);
				}
			}
			if (type != null)
			{
				GameObject val10 = new GameObject("LinkedLights_VennIcon");
				val10.transform.SetParent(_buttonObj.transform, false);
				val10.transform.SetAsLastSibling();
				RectTransform obj5 = val10.AddComponent<RectTransform>();
				obj5.anchorMin = Vector2.zero;
				obj5.anchorMax = Vector2.one;
				obj5.offsetMin = new Vector2(4f, 4f);
				obj5.offsetMax = new Vector2(-4f, -4f);
				_iconImage = val10.AddComponent(type);
				type.GetProperty("raycastTarget")?.SetValue(_iconImage, false);
				type.GetProperty("preserveAspect")?.SetValue(_iconImage, true);
			}
			_tooltip = _buttonObj.GetComponent<UITooltip>();
			if ((Object)(object)_tooltip == (Object)null)
			{
				_tooltip = _buttonObj.AddComponent<UITooltip>();
			}
			if ((Object)(object)_tooltip.m_tooltipPrefab == (Object)null)
			{
				UITooltip val11 = ((IEnumerable<UITooltip>)((Component)gui).GetComponentsInChildren<UITooltip>(true)).FirstOrDefault((Func<UITooltip, bool>)((UITooltip t) => (Object)(object)t != (Object)null && (Object)(object)t.m_tooltipPrefab != (Object)null));
				if ((Object)(object)val11 != (Object)null)
				{
					_tooltip.m_tooltipPrefab = val11.m_tooltipPrefab;
				}
			}
		}

		private static void OnToggleClicked()
		{
			if (!((Object)(object)_activeContainer == (Object)null))
			{
				bool excluded = !LinkedLightsPlugin.IsContainerExcludedByToggle(_activeContainer);
				LinkedLightsPlugin.SetContainerExcludedByToggle(_activeContainer, excluded);
				PerimeterStorage.InvalidateCache();
				UpdateButtonVisuals(excluded);
			}
		}

		private static void UpdateButtonVisuals(bool excluded)
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_buttonObj == (Object)null))
			{
				if ((Object)(object)_includedSprite == (Object)null)
				{
					_includedSprite = CreateVennSprite(excluded: false);
				}
				if ((Object)(object)_excludedSprite == (Object)null)
				{
					_excludedSprite = CreateVennSprite(excluded: true);
				}
				if ((Object)(object)_iconImage != (Object)null)
				{
					Type type = ((object)_iconImage).GetType();
					type.GetProperty("sprite")?.SetValue(_iconImage, excluded ? _excludedSprite : _includedSprite);
					type.GetProperty("color")?.SetValue(_iconImage, Color.white);
				}
				if ((Object)(object)_tooltip != (Object)null)
				{
					_tooltip.m_topic = (excluded ? "Perimeter Pull: OFF" : "Perimeter Pull: ON");
					_tooltip.m_text = "Include/exclude from perimeter pull";
					ValheimAccess.UpdateTooltipTextElements(_tooltip);
				}
			}
		}

		private static Sprite CreateVennSprite(bool excluded)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: 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_0089: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: 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_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: 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_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: 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_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(64, 64, (TextureFormat)4, false);
			((Texture)val).filterMode = (FilterMode)1;
			((Texture)val).wrapMode = (TextureWrapMode)1;
			Color val2 = (excluded ? new Color(0.68f, 0.36f, 0.36f, 0.9f) : new Color(0.45f, 0.9f, 0.5f, 1f));
			Color val3 = (excluded ? new Color(0.58f, 0.34f, 0.34f, 0.9f) : new Color(0.96f, 0.78f, 0.33f, 1f));
			Color val4 = (excluded ? new Color(0.68f, 0.36f, 0.36f, 0.14f) : new Color(0.45f, 0.9f, 0.5f, 0.22f));
			Color val5 = (excluded ? new Color(0.58f, 0.34f, 0.34f, 0.14f) : new Color(0.96f, 0.78f, 0.33f, 0.22f));
			Color val6 = (excluded ? new Color(0.75f, 0.42f, 0.4f, 0.24f) : new Color(1f, 0.94f, 0.68f, 0.55f));
			Color val7 = default(Color);
			((Color)(ref val7))..ctor(0.95f, 0.42f, 0.38f, 0.95f);
			Color[] array = (Color[])(object)new Color[4096];
			for (int i = 0; i < 64; i++)
			{
				for (int j = 0; j < 64; j++)
				{
					float num = Mathf.Sqrt(((float)j - 23f) * ((float)j - 23f) + ((float)i - 32f) * ((float)i - 32f));
					float num2 = Mathf.Sqrt(((float)j - 41f) * ((float)j - 41f) + ((float)i - 32f) * ((float)i - 32f));
					bool flag = num <= 17.5f;
					bool flag2 = num2 <= 17.5f;
					bool flag3 = num >= 14.5f && num <= 17.5f;
					bool flag4 = num2 >= 14.5f && num2 <= 17.5f;
					Color val8 = Color.clear;
					if (flag && flag2)
					{
						val8 = val6;
					}
					else if (flag)
					{
						val8 = val4;
					}
					else if (flag2)
					{
						val8 = val5;
					}
					if (flag3 && flag4)
					{
						val8 = Color.Lerp(val2, val3, 0.5f);
					}
					else if (flag3)
					{
						val8 = val2;
					}
					else if (flag4)
					{
						val8 = val3;
					}
					if (excluded && j >= 10 && j <= 53 && i >= 10 && i <= 53 && (float)Mathf.Abs(j - (63 - i)) * 0.7071f <= 2.1f)
					{
						val8 = val7;
					}
					array[i * 64 + j] = val8;
				}
			}
			val.SetPixels(array);
			val.Apply();
			return Sprite.Create(val, new Rect(0f, 0f, 64f, 64f), new Vector2(0.5f, 0.5f), 100f);
		}
	}
	internal sealed class StagedFeedContext
	{
		public Player Player;

		public Container SourceContainer;

		public ItemDrop SourceDrop;

		public ItemData StagedItem;

		public Vector3 Origin;

		public int InitialPlayerCount;

		public int StagedCount;

		public int RemainingExtraSlots;
	}
	internal sealed class StagedSingleIngredientContext
	{
		public Player Player;

		public string SharedName;

		public int InitialPlayerCount;

		public int StagedCount;

		public Vector3 Origin;
	}
	internal static class ServerConfigSync
	{
		private const string RpcName = "LinkedLights_SyncConfig";

		private const float SyncDelaySeconds = 2f;

		public static bool HasServerConfig { get; private set; }

		public static bool Enabled { get; private set; }

		public static float LightBuildRadius { get; private set; }

		public static bool RequireLit { get; private set; }

		public static bool LinkOverlappingCircles { get; private set; }

		public static bool PreventItemDespawn { get; private set; }

		public static bool ExtendWardsToPerimeter { get; private set; }

		public static bool PullFromPerimeterChests { get; private set; }

		public static bool AllowFeedStations { get; private set; }

		public static bool AllowShipsAndCarts { get; private set; }

		public static bool IsSyncEnabled
		{
			get
			{
				if (LinkedLightsPlugin.EnableServerConfigSyncEntry != null)
				{
					return LinkedLightsPlugin.EnableServerConfigSyncEntry.Value;
				}
				return true;
			}
		}

		public static void RegisterRpc()
		{
			try
			{
				if (ZRoutedRpc.instance != null)
				{
					ZRoutedRpc.instance.Register<ZPackage>("LinkedLights_SyncConfig", (Action<long, ZPackage>)RPC_ReceiveConfig);
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log = LinkedLightsPlugin.Log;
				if (log != null)
				{
					log.LogError((object)string.Format("Failed to register {0}: {1}", "LinkedLights_SyncConfig", arg));
				}
			}
		}

		public static void ScheduleSendToPeer(long peerId)
		{
			if (IsSyncEnabled && peerId != 0L && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer())
			{
				MonoBehaviour val = (MonoBehaviour)(object)(((Object)(object)LinkedLightsPlugin.Instance != (Object)null) ? LinkedLightsPlugin.Instance : ((LinkedLightsPlugin)(object)ZNet.instance));
				if ((Object)(object)val != (Object)null)
				{
					val.StartCoroutine(SendToPeerDelayed(peerId, 2f));
				}
			}
		}

		private static IEnumerator SendToPeerDelayed(long peerId, float delaySeconds)
		{
			yield return (object)new WaitForSecondsRealtime(delaySeconds);
			if (IsSyncEnabled && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && ValheimAccess.GetPeer(ZNet.instance, peerId) != null)
			{
				SendToPeer(peerId);
			}
		}

		public static void SendToPeer(long peerId)
		{
			if (!IsSyncEnabled || peerId == 0L || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || ZRoutedRpc.instance == null)
			{
				return;
			}
			try
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(peerId, "LinkedLights_SyncConfig", new object[1] { BuildConfigPackage() });
			}
			catch (Exception arg)
			{
				ManualLogSource log = LinkedLightsPlugin.Log;
				if (log != null)
				{
					log.LogError((object)$"Failed to send config to peer {peerId}: {arg}");
				}
			}
		}

		public static void BroadcastToAllClients()
		{
			if (!IsSyncEnabled || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || ZRoutedRpc.instance == null)
			{
				return;
			}
			try
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "LinkedLights_SyncConfig", new object[1] { BuildConfigPackage() });
			}
			catch (Exception arg)
			{
				ManualLogSource log = LinkedLightsPlugin.Log;
				if (log != null)
				{
					log.LogError((object)$"Failed to broadcast config: {arg}");
				}
			}
		}

		private static ZPackage BuildConfigPackage()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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_0025: 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_0045: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(LinkedLightsPlugin.ModEnabledEntry.Value);
			val.Write(LinkedLightsPlugin.LightBuildRadiusEntry.Value);
			val.Write(LinkedLightsPlugin.RequireLitEntry.Value);
			val.Write(LinkedLightsPlugin.LinkOverlappingCirclesEntry.Value);
			val.Write(LinkedLightsPlugin.PreventItemDespawnEntry.Value);
			val.Write(LinkedLightsPlugin.ExtendWardsToPerimeterEntry.Value);
			val.Write(LinkedLightsPlugin.PullFromPerimeterChestsEntry.Value);
			val.Write(LinkedLightsPlugin.AllowFeedStationsEntry.Value);
			val.Write(LinkedLightsPlugin.AllowShipsAndCartsEntry.Value);
			val.Write(LinkedLightsPlugin.AllowedLightPrefabsEntry.Value);
			val.Write(LinkedLightsPlugin.DisallowedContainersEntry.Value);
			val.Write(LinkedLightsPlugin.DisallowedItemsEntry.Value);
			return val;
		}

		private static void RPC_ReceiveConfig(long sender, ZPackage pkg)
		{
			if (!IsSyncEnabled || ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) || pkg == null)
			{
				return;
			}
			try
			{
				Enabled = pkg.ReadBool();
				LightBuildRadius = pkg.ReadSingle();
				RequireLit = pkg.ReadBool();
				LinkOverlappingCircles = pkg.ReadBool();
				PreventItemDespawn = pkg.ReadBool();
				ExtendWardsToPerimeter = pkg.ReadBool();
				PullFromPerimeterChests = pkg.ReadBool();
				AllowFeedStations = pkg.ReadBool();
				AllowShipsAndCarts = pkg.ReadBool();
				string lightsCsv = pkg.ReadString();
				string containersCsv = pkg.ReadString();
				string itemsCsv = pkg.ReadString();
				HasServerConfig = true;
				LinkedLightsPlugin.RebuildAllCaches(lightsCsv, containersCsv, itemsCsv);
			}
			catch (Exception arg)
			{
				ManualLogSource log = LinkedLightsPlugin.Log;
				if (log != null)
				{
					log.LogError((object)$"Failed to read server config RPC: {arg}");
				}
			}
		}

		public static void Reset()
		{
			HasServerConfig = false;
			if (LinkedLightsPlugin.AllowedLightPrefabsEntry != null)
			{
				LinkedLightsPlugin.RebuildAllCaches(LinkedLightsPlugin.AllowedLightPrefabsEntry.Value, LinkedLightsPlugin.DisallowedContainersEntry.Value, LinkedLightsPlugin.DisallowedItemsEntry.Value);
			}
		}
	}
	[HarmonyPatch]
	internal static class Patches
	{
		private static readonly object GoldHighlightColorBoxed = (object)new Color(1f, 0.86f, 0.35f, 1f);

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

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

		private static PropertyInfo _tmpTextProp;

		private static PropertyInfo _tmpColorProp;

		private static PropertyInfo _uiTextProp;

		private static PropertyInfo _uiColorProp;

		private static bool _inFillLoop;

		private static bool _ringsShownLastFrame;

		[HarmonyPatch(typeof(ZNet), "Awake")]
		[HarmonyPostfix]
		private static void ZNet_Awake()
		{
			ServerConfigSync.RegisterRpc();
			PerimeterStorage.RegisterRpc();
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPostfix]
		private static void ZNet_RPC_PeerInfo(ZNet __instance, ZRpc rpc)
		{
			if (!((Object)(object)__instance == (Object)null) && __instance.IsServer())
			{
				ZNetPeer peer = ValheimAccess.GetPeer(__instance, rpc);
				if (peer != null && peer.m_uid != 0L)
				{
					ServerConfigSync.ScheduleSendToPeer(peer.m_uid);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnDestroy")]
		[HarmonyPostfix]
		private static void ZNet_OnDestroy()
		{
			ServerConfigSync.Reset();
			PerimeterGraphCache.Clear();
			PerimeterStorage.InvalidateCache();
			ChestToggleUI.OnContainerClosed();
			LightRingVisual.Clear();
			LinkedLightsPlugin.ActiveLights.Clear();
			LinkedLightsPlugin.ActiveContainers.Clear();
			LinkedLightsPlugin.ActiveWards.Clear();
			_ringsShownLastFrame = false;
		}

		private static bool ShouldTrackOnAwake(Component c)
		{
			if ((Object)(object)c != (Object)null && !ZNetView.m_forceDisableInit)
			{
				return (Object)(object)c.GetComponent<ZNetView>() != (Object)null;
			}
			return false;
		}

		[HarmonyPatch(typeof(Fireplace), "Awake")]
		[HarmonyPostfix]
		private static void Fireplace_Awake(Fireplace __instance)
		{
			if (ShouldTrackOnAwake((Component)(object)__instance))
			{
				LinkedLightsPlugin.ActiveLights.Add(__instance);
			}
		}

		[HarmonyPatch(typeof(Container), "Awake")]
		[HarmonyPostfix]
		private static void Container_Awake(Container __instance)
		{
			if (ShouldTrackOnAwake((Component)(object)__instance))
			{
				LinkedLightsPlugin.ActiveContainers.Add(__instance);
			}
		}

		[HarmonyPatch(typeof(PrivateArea), "Awake")]
		[HarmonyPostfix]
		private static void PrivateArea_Awake(PrivateArea __instance)
		{
			if (ShouldTrackOnAwake((Component)(object)__instance))
			{
				LinkedLightsPlugin.ActiveWards.Add(__instance);
			}
		}

		[HarmonyPatch(typeof(PrivateArea), "OnDestroy")]
		[HarmonyPostfix]
		private static void PrivateArea_OnDestroy(PrivateArea __instance)
		{
			if ((Object)(object)__instance != (Object)null)
			{
				LinkedLightsPlugin.ActiveWards.Remove(__instance);
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "Show")]
		[HarmonyPostfix]
		private static void InventoryGui_Show(InventoryGui __instance, Container container)
		{
			ChestToggleUI.OnContainerOpened(__instance, container);
		}

		[HarmonyPatch(typeof(InventoryGui), "Hide")]
		[HarmonyPostfix]
		private static void InventoryGui_Hide()
		{
			ChestToggleUI.OnContainerClosed();
		}

		[HarmonyPatch(typeof(PrivateArea), "CheckAccess")]
		[HarmonyPostfix]
		private static void PrivateArea_CheckAccess(Vector3 point, float radius, bool flash, bool wardCheck, ref bool __result)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: 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_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			if (!__result || !LinkedLightsPlugin.IsEnabled || !LinkedLightsPlugin.ExtendWards || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return;
			}
			List<PerimeterNode> nodes = PerimeterGraphCache.GetNodes();
			if (nodes.Count == 0)
			{
				return;
			}
			_wardComponentsScratch.Clear();
			Vector3 val;
			for (int i = 0; i < nodes.Count; i++)
			{
				float num = nodes[i].Radius + radius;
				val = point - nodes[i].Position;
				if (((Vector3)(ref val)).sqrMagnitude <= num * num)
				{
					_wardComponentsScratch.Add(nodes[i].ComponentId);
				}
			}
			if (_wardComponentsScratch.Count == 0)
			{
				return;
			}
			LinkedLightsPlugin.ActiveWards.RemoveWhere((PrivateArea w) => (Object)(object)w == (Object)null);
			foreach (PrivateArea activeWard in LinkedLightsPlugin.ActiveWards)
			{
				if ((Object)(object)activeWard == (Object)null)
				{
					continue;
				}
				ZNetView component = ((Component)activeWard).GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && component.IsValid() && ValheimAccess.IsWardEnabled(activeWard) && ValheimAccess.HaveLocalAccess(activeWard))
				{
					float num2 = activeWard.m_radius + radius;
					val = point - ((Component)activeWard).transform.position;
					if (((Vector3)(ref val)).sqrMagnitude <= num2 * num2)
					{
						return;
					}
				}
			}
			foreach (PrivateArea activeWard2 in LinkedLightsPlugin.ActiveWards)
			{
				if ((Object)(object)activeWard2 == (Object)null)
				{
					continue;
				}
				ZNetView component2 = ((Component)activeWard2).GetComponent<ZNetView>();
				if ((Object)(object)component2 == (Object)null || !component2.IsValid() || !ValheimAccess.IsWardEnabled(activeWard2) || ValheimAccess.HaveLocalAccess(activeWard2))
				{
					continue;
				}
				Vector3 position = ((Component)activeWard2).transform.position;
				bool flag = false;
				for (int num3 = 0; num3 < nodes.Count; num3++)
				{
					if (_wardComponentsScratch.Contains(nodes[num3].ComponentId))
					{
						float radius2 = nodes[num3].Radius;
						val = position - nodes[num3].Position;
						if (((Vector3)(ref val)).sqrMagnitude <= radius2 * radius2)
						{
							flag = true;
							break;
						}
					}
				}
				if (flag)
				{
					if (flash)
					{
						ValheimAccess.FlashShield(activeWard2, flashConnected: false);
						ValheimAccess.ShowCharacterMessage((Character)(object)Player.m_localPlayer, (MessageType)2, "$msg_privatezone");
					}
					__result = false;
					break;
				}
			}
		}

		[HarmonyPatch(typeof(ItemDrop), "TimedDestruction")]
		[HarmonyPrefix]
		private static bool ItemDrop_TimedDestruction(ItemDrop __instance)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			if (!LinkedLightsPlugin.IsEnabled || !LinkedLightsPlugin.KeepDroppedItems || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if (LinkedLightsPlugin.IsProtectedByWorkbenchLinkedLight(((Component)__instance).transform.position))
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(CraftingStation), "HaveBuildStationInRange")]
		[HarmonyPostfix]
		private static void CraftingStation_HaveBuildStationInRange(string name, Vector3 point, ref CraftingStation __result)
		{
			//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_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__result != (Object)null || !LinkedLightsPlugin.IsEnabled)
			{
				return;
			}
			List<PerimeterNode> nodes = PerimeterGraphCache.GetNodes();
			if (nodes.Count == 0)
			{
				return;
			}
			_stationComponentsScratch.Clear();
			for (int i = 0; i < nodes.Count; i++)
			{
				float radius = nodes[i].Radius;
				Vector3 val = nodes[i].Position - point;
				if (((Vector3)(ref val)).sqrMagnitude <= radius * radius)
				{
					if ((Object)(object)nodes[i].Station != (Object)null && nodes[i].StationName == name)
					{
						__result = nodes[i].Station;
						return;
					}
					_stationComponentsScratch.Add(nodes[i].ComponentId);
				}
			}
			if (_stationComponentsScratch.Count == 0)
			{
				return;
			}
			for (int j = 0; j < nodes.Count; j++)
			{
				if ((Object)(object)nodes[j].Station != (Object)null && nodes[j].StationName == name && _stationComponentsScratch.Contains(nodes[j].ComponentId))
				{
					__result = nodes[j].Station;
					break;
				}
			}
		}

		[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
		{
			typeof(Piece),
			typeof(RequirementMode)
		})]
		[HarmonyPostfix]
		private static void Player_HaveRequirements(Player __instance, Piece piece, RequirementMode mode, ref bool __result)
		{
			//IL_0023: 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)
			if (!__result && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && !((Object)(object)piece == (Object)null) && !__instance.NoCostCheat() && (int)mode == 0 && LinkedLightsPlugin.IsEnabled && LinkedLightsPlugin.PullFromChests && !LinkedLightsPlugin.IsPullSuppressedByKey() && (!((Object)(object)piece.m_craftingStation != (Object)null) || !((Object)(object)CraftingStation.HaveBuildStationInRange(piece.m_craftingStation.m_name, ((Component)__instance).transform.position) == (Object)null) || (!((Object)(object)ZoneSystem.instance == (Object)null) && ZoneSystem.instance.GetGlobalKey((GlobalKeys)27))) && (string.IsNullOrEmpty(piece.m_dlc) || !((Object)(object)DLCMan.instance != (Object)null) || ValheimAccess.IsDlcInstalled(DLCMan.instance, piece.m_dlc)) && HasCombinedRequirements(__instance, piece.m_resources, 0, 1))
			{
				__result = true;
			}
		}

		[HarmonyPatch(typeof(Player), "HaveRequirementItems")]
		[HarmonyPostfix]
		private static void Player_HaveRequirementItems(Player __instance, Recipe piece, bool discover, int qualityLevel, int amount, ref bool __result)
		{
			if (!(__result || discover) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && !((Object)(object)piece == (Object)null) && !__instance.NoCostCheat() && LinkedLightsPlugin.IsEnabled && LinkedLightsPlugin.PullFromChests && !LinkedLightsPlugin.IsPullSuppressedByKey() && HasCombinedRequirements(__instance, piece.m_resources, qualityLevel, amount, piece.m_requireOnlyOneIngredient))
			{
				__result = true;
			}
		}

		private static bool HasCombinedRequirements(Player player, Requirement[] requirements, int qualityLevel, int craftMultiplier, bool requireOnlyOne = false)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			if (requirements == null)
			{
				return true;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null)
			{
				return false;
			}
			Vector3 position = ((Component)player).transform.position;
			bool flag = false;
			foreach (Requirement val in requirements)
			{
				if (val == null || (Object)(object)val.m_resItem == (Object)null)
				{
					continue;
				}
				int num = val.GetAmount(qualityLevel) * Mathf.Max(craftMultiplier, 1);
				if (num <= 0)
				{
					continue;
				}
				flag = true;
				string name = val.m_resItem.m_itemData.m_shared.m_name;
				int num2 = inventory.CountItems(name, -1, true);
				bool flag2 = num2 >= num || num2 + PerimeterStorage.CountItem(position, name) >= num;
				if (requireOnlyOne)
				{
					if (flag2)
					{
						return true;
					}
				}
				else if (!flag2)
				{
					return false;
				}
			}
			if (requireOnlyOne)
			{
				return !flag;
			}
			return true;
		}

		[HarmonyPatch(typeof(Player), "ConsumeResources")]
		[HarmonyPrefix]
		private static void Player_ConsumeResources_Prefix(Player __instance, Requirement[] requirements, int qualityLevel, int itemQuality, int multiplier, out Dictionary<string, int> __state)
		{
			__state = null;
			if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || requirements == null || __instance.NoCostCheat() || !LinkedLightsPlugin.IsEnabled || !LinkedLightsPlugin.PullFromChests || LinkedLightsPlugin.IsPullSuppressedByKey())
			{
				return;
			}
			Inventory inventory = ((Humanoid)__instance).GetInventory();
			if (inventory == null)
			{
				return;
			}
			__state = new Dictionary<string, int>();
			foreach (Requirement val in requirements)
			{
				if (val != null && !((Object)(object)val.m_resItem == (Object)null))
				{
					string name = val.m_resItem.m_itemData.m_shared.m_name;
					if (!__state.ContainsKey(name))
					{
						__state[name] = inventory.CountItems(name, -1, true);
					}
				}
			}
		}

		[HarmonyPatch(typeof(Player), "ConsumeResources")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void Player_ConsumeResources_Postfix(Player __instance, Requirement[] requirements, int qualityLevel, int itemQuality, int multiplier, Dictionary<string, int> __state)
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || requirements == null)
			{
				return;
			}
			Inventory inventory = ((Humanoid)__instance).GetInventory();
			if (inventory == null)
			{
				return;
			}
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			foreach (Requirement val in requirements)
			{
				if (val == null || (Object)(object)val.m_resItem == (Object)null)
				{
					continue;
				}
				int num = val.GetAmount(qualityLevel) * Mathf.Max(multiplier, 1);
				if (num > 0)
				{
					string name = val.m_resItem.m_itemData.m_shared.m_name;
					if (dictionary.ContainsKey(name))
					{
						dictionary[name] += num;
					}
					else
					{
						dictionary[name] = num;
					}
				}
			}
			Vector3 position = ((Component)__instance).transform.position;
			foreach (KeyValuePair<string, int> item in dictionary)
			{
				string key = item.Key;
				int value = item.Value;
				int value2;
				int num2 = (__state.TryGetValue(key, out value2) ? value2 : 0);
				int num3 = inventory.CountItems(key, -1, true);
				int num4 = Mathf.Max(0, num2 - num3);
				int num5 = value - num4;
				if (num5 > 0)
				{
					PerimeterStorage.RemoveItem(position, key, num5);
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
		[HarmonyPrefix]
		private static void InventoryGui_DoCrafting_Prefix(InventoryGui __instance, Player player, out StagedSingleIngredientContext __state)
		{
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			if ((Object)(object)__instance == (Object)null || (Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || player.NoCostCheat())
			{
				return;
			}
			Recipe craftRecipe = ValheimAccess.GetCraftRecipe(__instance);
			if ((Object)(object)craftRecipe == (Object)null || !craftRecipe.m_requireOnlyOneIngredient || craftRecipe.m_resources == null || !LinkedLightsPlugin.IsEnabled || !LinkedLightsPlugin.PullFromChests || LinkedLightsPlugin.IsPullSuppressedByKey())
			{
				return;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null)
			{
				return;
			}
			ItemData craftUpgradeItem = ValheimAccess.GetCraftUpgradeItem(__instance);
			int num = ((craftUpgradeItem == null) ? 1 : (craftUpgradeItem.m_quality + 1));
			int num2 = ((!ValheimAccess.IsMultiCrafting(__instance)) ? 1 : Mathf.Max(__instance.m_multiCraftAmount, 1));
			Requirement[] resources = craftRecipe.m_resources;
			foreach (Requirement val in resources)
			{
				if (val == null || (Object)(object)val.m_resItem == (Object)null)
				{
					continue;
				}
				int num3 = val.GetAmount(num) * num2;
				if (num3 > 0)
				{
					string name = val.m_resItem.m_itemData.m_shared.m_name;
					if (inventory.CountItems(name, -1, true) >= num3)
					{
						return;
					}
				}
			}
			Vector3 position = ((Component)player).transform.position;
			List<Container> linkedContainers = PerimeterStorage.GetLinkedContainers(position);
			if (linkedContainers.Count == 0)
			{
				return;
			}
			resources = craftRecipe.m_resources;
			foreach (Requirement val2 in resources)
			{
				if (val2 == null || (Object)(object)val2.m_resItem == (Object)null)
				{
					continue;
				}
				int num4 = val2.GetAmount(num) * num2;
				if (num4 <= 0)
				{
					continue;
				}
				string name2 = val2.m_resItem.m_itemData.m_shared.m_name;
				int num5 = inventory.CountItems(name2, -1, true);
				int num6 = num4 - num5;
				if (num6 <= 0 || PerimeterStorage.CountItem(position, name2) < num6)
				{
					continue;
				}
				int num7 = num6;
				for (int j = 0; j < linkedContainers.Count; j++)
				{
					if (num7 <= 0)
					{
						break;
					}
					Inventory inventory2 = linkedContainers[j].GetInventory();
					if (inventory2 == null)
					{
						continue;
					}
					foreach (ItemData allItem in inventory2.GetAllItems())
					{
						if (num7 <= 0)
						{
							break;
						}
						if (allItem == null || allItem.m_shared == null || allItem.m_shared.m_name != name2 || !LinkedLightsPlugin.IsItemAllowedFromChests(allItem))
						{
							continue;
						}
						int num8 = Mathf.Min(allItem.m_stack, num7);
						ItemData val3 = allItem.Clone();
						val3.m_stack = num8;
						if (!inventory.AddItem(val3))
						{
							int num9 = num6 - num7;
							if (num9 > 0)
							{
								inventory.RemoveItem(name2, num9, -1, true);
							}
							return;
						}
						num7 -= num8;
					}
				}
				if (num7 == 0)
				{
					__state = new StagedSingleIngredientContext
					{
						Player = player,
						SharedName = name2,
						InitialPlayerCount = num5,
						StagedCount = num6,
						Origin = position
					};
					break;
				}
				int num10 = num6 - num7;
				if (num10 > 0)
				{
					inventory.RemoveItem(name2, num10, -1, true);
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
		[HarmonyPostfix]
		private static void InventoryGui_DoCrafting_Postfix(StagedSingleIngredientContext __state)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null || (Object)(object)__state.Player == (Object)null)
			{
				return;
			}
			Inventory inventory = ((Humanoid)__state.Player).GetInventory();
			if (inventory != null)
			{
				int num = inventory.CountItems(__state.SharedName, -1, true);
				int num2 = __state.InitialPlayerCount + __state.StagedCount;
				int num3 = Mathf.Max(0, num2 - num);
				int num4 = Mathf.Max(0, __state.StagedCount - num3);
				if (num4 > 0)
				{
					inventory.RemoveItem(__state.SharedName, num4, -1, true);
				}
				int num5 = Mathf.Max(0, num3 - __state.InitialPlayerCount);
				if (num5 > 0)
				{
					PerimeterStorage.RemoveItem(__state.Origin, __state.SharedName, num5);
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void InventoryGui_SetupRequirement(object[] __args)
		{
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			if (__args == null || __args.Length < 6 || !LinkedLightsPlugin.IsEnabled || !LinkedLightsPlugin.PullFromChests || !LinkedLightsPlugin.ShowCombinedResourceCountsEntry.Value || LinkedLightsPlugin.IsPullSuppressedByKey())
			{
				return;
			}
			object obj = __args[0];
			Transform val = (Transform)((obj is Transform) ? obj : null);
			object obj2 = __args[1];
			Requirement val2 = (Requirement)((obj2 is Requirement) ? obj2 : null);
			object obj3 = __args[2];
			Player val3 = (Player)((obj3 is Player) ? obj3 : null);
			int num = ((!(__args[4] is int num2)) ? 1 : num2);
			int num3 = ((!(__args[5] is int num4)) ? 1 : Mathf.Max(num4, 1));
			if ((Object)(object)val == (Object)null || val2 == null || (Object)(object)val2.m_resItem == (Object)null || (Object)(object)val3 == (Object)null)
			{
				return;
			}
			int num5 = val2.GetAmount(num) * num3;
			if (num5 <= 0)
			{
				return;
			}
			string text = val2.m_resItem.m_itemData?.m_shared?.m_name;
			if (!string.IsNullOrEmpty(text))
			{
				Inventory inventory = ((Humanoid)val3).GetInventory();
				int num6 = ((inventory != null) ? inventory.CountItems(text, -1, true) : 0);
				int num7 = PerimeterStorage.CountItem(((Component)val3).transform.position, text);
				if (num7 > 0)
				{
					int num8 = num6 + num7;
					UpdateRequirementText(val, $"{num8}/{num5}", num6 < num5 && num8 >= num5);
				}
			}
		}

		private static void UpdateRequirementText(Transform root, string formattedText, bool highlightGold)
		{
			Transform val = root.Find("res_amount");
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Component component = ((Component)val).GetComponent("TMP_Text");
			if ((Object)(object)component != (Object)null)
			{
				if (_tmpTextProp == null)
				{
					Type type = ((object)component).GetType();
					_tmpTextProp = type.GetProperty("text");
					_tmpColorProp = type.GetProperty("color");
				}
				_tmpTextProp?.SetValue(component, formattedText);
				if (highlightGold)
				{
					_tmpColorProp?.SetValue(component, GoldHighlightColorBoxed);
				}
				return;
			}
			Component component2 = ((Component)val).GetComponent("Text");
			if ((Object)(object)component2 != (Object)null)
			{
				if (_uiTextProp == null)
				{
					Type type2 = ((object)component2).GetType();
					_uiTextProp = type2.GetProperty("text");
					_uiColorProp = type2.GetProperty("color");
				}
				_uiTextProp?.SetValue(component2, formattedText);
				if (highlightGold)
				{
					_uiColorProp?.SetValue(component2, GoldHighlightColorBoxed);
				}
			}
		}

		[HarmonyPatch(typeof(Smelter), "OnAddFuel")]
		[HarmonyPrefix]
		private static void Smelter_OnAddFuel_Prefix(Smelter __instance, Humanoid user, ItemData item, out StagedFeedContext __state)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			if (!_inFillLoop && item == null && !((Object)(object)__instance == (Object)null) && !((Object)(object)__instance.m_fuelItem == (Object)null))
			{
				int remainingExtraSlots = Mathf.Max(0, __instance.m_maxFuel - Mathf.CeilToInt(ValheimAccess.GetSmelterFuel(__instance)) - 1);
				__state = TryStageSingleItem(user, ((Component)__instance).transform.position, (IEnumerable<ItemDrop>)(object)new ItemDrop[1] { __instance.m_fuelItem }, remainingExtraSlots);
			}
		}

		[HarmonyPatch(typeof(Smelter), "OnAddFuel")]
		[HarmonyPostfix]
		private static void Smelter_OnAddFuel_Postfix(Smelter __instance, Switch sw, Humanoid user, ItemData item, StagedFeedContext __state)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null || !FinishStagedItem(__state) || _inFillLoop || __state.RemainingExtraSlots <= 0 || !LinkedLightsPlugin.IsFillModifierHeld() || !((Object)(object)__instance != (Object)null) || !((Object)(object)__instance.m_fuelItem != (Object)null))
			{
				return;
			}
			int num = Mathf.Min(__state.RemainingExtraSlots, 200);
			_inFillLoop = true;
			try
			{
				for (int i = 0; i < num; i++)
				{
					StagedFeedContext stagedFeedContext = TryStageSingleItem(user, ((Component)__instance).transform.position, (IEnumerable<ItemDrop>)(object)new ItemDrop[1] { __instance.m_fuelItem });
					if (stagedFeedContext == null)
					{
						break;
					}
					ValheimAccess.InvokeSmelterAddFuel(__instance, sw, user, null);
					if (!FinishStagedItem(stagedFeedContext))
					{
						break;
					}
				}
			}
			finally
			{
				_inFillLoop = false;
			}
		}

		[HarmonyPatch(typeof(Smelter), "OnAddOre")]
		[HarmonyPrefix]
		private static void Smelter_OnAddOre_Prefix(Smelter __instance, Humanoid user, ItemData item, out StagedFeedContext __state)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			if (!_inFillLoop && item == null && !((Object)(object)__instance == (Object)null) && __instance.m_conversion != null)
			{
				IEnumerable<ItemDrop> candidateDrops = from c in __instance.m_conversion
					where c != null && (Object)(object)c.m_from != (Object)null
					select c.m_from;
				int remainingExtraSlots = Mathf.Max(0, __instance.m_maxOre - ValheimAccess.GetSmelterQueueSize(__instance) - 1);
				__state = TryStageSingleItem(user, ((Component)__instance).transform.position, candidateDrops, remainingExtraSlots);
			}
		}

		[HarmonyPatch(typeof(Smelter), "OnAddOre")]
		[HarmonyPostfix]
		private static void Smelter_OnAddOre_Postfix(Smelter __instance, Switch sw, Humanoid user, ItemData item, StagedFeedContext __state)
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null || !FinishStagedItem(__state) || _inFillLoop || __state.RemainingExtraSlots <= 0 || !LinkedLightsPlugin.IsFillModifierHeld() || !((Object)(object)__instance != (Object)null) || __instance.m_conversion == null)
			{
				return;
			}
			List<ItemDrop> candidateDrops = (from c in __instance.m_conversion
				where c != null && (Object)(object)c.m_from != (Object)null
				select c.m_from).ToList();
			int num = Mathf.Min(__state.RemainingExtraSlots, 200);
			_inFillLoop = true;
			try
			{
				for (int num2 = 0; num2 < num; num2++)
				{
					StagedFeedContext stagedFeedContext = TryStageSingleItem(user, ((Component)__instance).transform.position, candidateDrops);
					if (stagedFeedContext == null)
					{
						break;
					}
					ValheimAccess.InvokeSmelterAddOre(__instance, sw, user, null);
					if (!FinishStagedItem(stagedFeedContext))
					{
						break;
					}
				}
			}
			finally
			{
				_inFillLoop = false;
			}
		}

		[HarmonyPatch(typeof(Fireplace), "Interact")]
		[HarmonyPrefix]
		private static void Fireplace_Interact_Prefix(Fireplace __instance, Humanoid user, bool hold, bool alt, out StagedFeedContext __state)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			if (!(_inFillLoop || hold || alt) && !((Object)(object)__instance == (Object)null) && !((Object)(object)__instance.m_fuelItem == (Object)null))
			{
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				float num = (((Object)(object)component != (Object)null && component.IsValid()) ? component.GetZDO().GetFloat(ZDOVars.s_fuel, 0f) : __instance.m_maxFuel);
				int remainingExtraSlots = Mathf.Max(0, Mathf.CeilToInt(__instance.m_maxFuel) - Mathf.CeilToInt(num) - 1);
				__state = TryStageSingleItem(user, ((Component)__instance).transform.position, (IEnumerable<ItemDrop>)(object)new ItemDrop[1] { __instance.m_fuelItem }, remainingExtraSlots);
			}
		}

		[HarmonyPatch(typeof(Fireplace), "Interact")]
		[HarmonyPostfix]
		private static void Fireplace_Interact_Postfix(Fireplace __instance, Humanoid user, bool hold, bool alt, StagedFeedContext __state)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null || !FinishStagedItem(__state) || _inFillLoop || __state.RemainingExtraSlots <= 0 || !LinkedLightsPlugin.IsFillModifierHeld() || !((Object)(object)__instance != (Object)null) || !((Object)(object)__instance.m_fuelItem != (Object)null))
			{
				return;
			}
			int num = Mathf.Min(__state.RemainingExtraSlots, 100);
			_inFillLoop = true;
			try
			{
				for (int i = 0; i < num; i++)
				{
					StagedFeedContext stagedFeedContext = TryStageSingleItem(user, ((Component)__instance).transform.position, (IEnumerable<ItemDrop>)(object)new ItemDrop[1] { __instance.m_fuelItem });
					if (stagedFeedContext == null)
					{
						break;
					}
					__instance.Interact(user, false, false);
					if (!FinishStagedItem(stagedFeedContext))
					{
						break;
					}
				}
			}
			finally
			{
				_inFillLoop = false;
			}
		}

		[HarmonyPatch(typeof(CookingStation), "Interact")]
		[HarmonyPrefix]
		private static void CookingStation_Interact_Prefix(CookingStation __instance, Humanoid user, bool hold, bool alt, out StagedFeedContext __state)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			if (hold || alt || (Object)(object)__instance == (Object)null)
			{
				return;
			}
			List<ItemDrop> list = new List<ItemDrop>();
			if ((Object)(object)__instance.m_fuelItem != (Object)null)
			{
				list.Add(__instance.m_fuelItem);
			}
			if (__instance.m_conversion != null)
			{
				foreach (ItemConversion item in __instance.m_conversion)
				{
					if (item != null && (Object)(object)item.m_from != (Object)null)
					{
						list.Add(item.m_from);
					}
				}
			}
			__state = TryStageSingleItem(user, ((Component)__instance).transform.position, list);
		}

		[HarmonyPatch(typeof(CookingStation), "Interact")]
		[HarmonyPostfix]
		private static void CookingStation_Interact_Postfix(StagedFeedContext __state)
		{
			if (__state != null)
			{
				FinishStagedItem(__state);
			}
		}

		[HarmonyPatch(typeof(Turret), "Interact")]
		[HarmonyPrefix]
		private static void Turret_Interact_Prefix(Turret __instance, Humanoid character, bool hold, bool alt, out StagedFeedContext __state)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			if (!(_inFillLoop || hold || alt) && !((Object)(object)__instance == (Object)null) && __instance.m_allowedAmmo != null)
			{
				int ammo = __instance.GetAmmo();
				string loadedAmmoPrefab = ((ammo > 0) ? __instance.GetAmmoType() : null);
				IEnumerable<ItemDrop> candidateDrops = from a in __instance.m_allowedAmmo
					where (Object)(object)a.m_ammo != (Object)null && (string.IsNullOrEmpty(loadedAmmoPrefab) || ((Object)a.m_ammo).name == loadedAmmoPrefab)
					select a.m_ammo;
				int remainingExtraSlots = Mathf.Max(0, __instance.m_maxAmmo - ammo - 1);
				__state = TryStageSingleItem(character, ((Component)__instance).transform.position, candidateDrops, remainingExtraSlots);
			}
		}

		[HarmonyPatch(typeof(Turret), "Interact")]
		[HarmonyPos