Decompiled source of Feastworks v1.0.1

Feastworks.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using ServerSync;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Feastworks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1+901b84ab23f2f10926b13865f9b40bb283490874")]
[assembly: AssemblyProduct("Feastworks")]
[assembly: AssemblyTitle("Feastworks")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 ServerSync
{
	public abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	public class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase()
	{
		public readonly ConfigEntry<T> SourceConfig = sourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	public abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
		{
			Priority = priority;
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	public sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0)
			: base(configSync, identifier, typeof(T), priority)
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		public bool? ReadOnly = false;
	}
	public class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> list = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p)
							{
								string hostName = p.m_rpc.GetSocket().GetHostName();
								return ((object)listContainsId != null) ? ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })) : adminList.Contains(hostName);
							}).ToList();
							SendAdmin(ZNet.instance.GetPeers().Except(list).ToList(), isAdmin: false);
							SendAdmin(list, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				try
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						configSync.resetConfigsFromServer();
						configSync.IsSourceOfTruth = true;
						configSync.InitialSyncDone = false;
					}
				}
				finally
				{
					lockExempt = false;
					ProcessingServerUpdate = false;
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ZPlayFabSocket, ISocket
			{
				public volatile bool finished;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
					((ZPlayFabSocket)this)..ctor();
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_004c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0052: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				if (!__instance.IsServer())
				{
					return;
				}
				BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket());
				AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket);
				object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
				ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
				if (val != null && (int)ZNet.m_onlineBackend != 0)
				{
					FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket");
					object? value = fieldInfo.GetValue(val);
					ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null);
					if (val2 != null)
					{
						typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId);
					}
					fieldInfo.SetValue(val, bufferingSocket);
				}
				if (__state == null)
				{
					__state = new Dictionary<Assembly, BufferingSocket>();
				}
				__state[Assembly.GetExecutingAssembly()] = bufferingSocket;
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> list = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							list.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						list.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)methodInfo == null) ? ((object)val.Contains(rpc.GetSocket().GetHostName())) : methodInfo.Invoke(ZNet.instance, new object[2]
							{
								val,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, list, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section;

			public string key;

			public Type type;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected;

			public string received;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0051;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag == true;
				}
				if (num)
				{
					return !lockExempt;
				}
				goto IL_0051;
				IL_0051:
				return false;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin
		{
			get
			{
				if (!lockExempt)
				{
					return isSourceOfTruth;
				}
				return true;
			}
		}

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; }

		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(0L, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority));
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(0L, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged -= serverLockedSettingChanged;
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Expected O, but got Unknown
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4) != 0)
				{
					MemoryStream stream = new MemoryStream(package.ReadByteArray());
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				if (!isServer)
				{
					foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
					{
						OwnConfigEntryBase key2 = configValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
						}
					}
					foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
					{
						CustomSyncedValueBase key3 = customValue.Key;
						if (key3.LocalBaseValue == null)
						{
							key3.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					serverLockedSettingChanged();
				}
				ConfigFile val2 = null;
				bool saveOnConfigSet = false;
				try
				{
					foreach (KeyValuePair<OwnConfigEntryBase, object> configValue2 in parsedConfigs.configValues)
					{
						if (val2 == null)
						{
							val2 = configValue2.Key.BaseConfig.ConfigFile;
							saveOnConfigSet = val2.SaveOnConfigSet;
							val2.SaveOnConfigSet = false;
						}
						configValue2.Key.BaseConfig.BoxedValue = configValue2.Value;
					}
					if (val2 != null)
					{
						val2.Save();
					}
				}
				finally
				{
					if (val2 != null)
					{
						val2.SaveOnConfigSet = saveOnConfigSet;
					}
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue2 in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key3 = customValue2.Key;
						if (key3.LocalBaseValue == null)
						{
							key3.LocalBaseValue = customValue2.Key.BoxedValue;
						}
					}
					customValue2.Key.BoxedValue = customValue2.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int num2 = 0; num2 < num; num2++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			if (!configSync.IsSourceOfTruth && config.SynchronizedConfig && config.LocalBaseValue != null)
			{
				if (!configSync.IsLocked)
				{
					if (config == configSync.lockedConfig)
					{
						return lockExempt;
					}
					return true;
				}
				return false;
			}
			return true;
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			ConfigFile val = null;
			bool saveOnConfigSet = false;
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				if (val == null)
				{
					val = item.BaseConfig.ConfigFile;
					saveOnConfigSet = val.SaveOnConfigSet;
					val.SaveOnConfigSet = false;
				}
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			if (val != null)
			{
				val.SaveOnConfigSet = saveOnConfigSet;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage val = new ZPackage();
						val.Write((byte)2);
						val.Write(packageIdentifier);
						val.Write(fragment);
						val.Write(fragments);
						val.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(val);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != 0L)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] array = package.GetArray();
			if (array != null && array.LongLength > 10000)
			{
				ZPackage val = new ZPackage();
				val.Write((byte)4);
				MemoryStream memoryStream = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal))
				{
					deflateStream.Write(array, 0, array.Length);
				}
				val.Write(memoryStream.ToArray());
				package = val;
			}
			List<IEnumerator<bool>> writers = (from p in peers
				where p.IsReady()
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			if (!type.IsEnum)
			{
				return type;
			}
			return Enum.GetUnderlyingType(type);
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write(partial ? ((byte)1) : ((byte)0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[HarmonyPatch]
	public class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				string text = minimumRequiredVersion;
				if (text == null)
				{
					if (!ModRequired)
					{
						return "0.0.0";
					}
					text = CurrentVersion;
				}
				return text;
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool num = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return num && flag;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return DisplayName + " is not installed on the server.";
			}
			if (!(new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)))
			{
				return DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + ".";
			}
			return DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".";
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			if (rpc != null)
			{
				return ErrorServer(rpc);
			}
			return ErrorClient();
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout(true, true);
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				Debug.LogWarning((object)array2[i].Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[HarmonyPrefix]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					CheckVersion(rpc, pkg, action);
				});
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		[HarmonyPrefix]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		[HarmonyPostfix]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			bool flag = false;
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				TMP_Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
				flag = true;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					TMP_Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed.";
					flag = true;
				}
			}
			if (flag)
			{
				RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent<RectTransform>();
				Vector2 sizeDelta = component.sizeDelta;
				sizeDelta.x = 675f;
				component.sizeDelta = sizeDelta;
				__instance.m_connectionFailedError.ForceMeshUpdate(false, false);
				float num = __instance.m_connectionFailedError.renderedHeight + 105f;
				RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent<RectTransform>();
				component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f);
				sizeDelta = component.sizeDelta;
				sizeDelta.y = num;
				component.sizeDelta = sizeDelta;
			}
		}
	}
}
namespace Feastworks
{
	internal static class FeastworksSettings
	{
		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> LockConfiguration;

		internal static ConfigEntry<int> FoodSlots;

		internal static ConfigEntry<float> FoodDurationMultiplier;

		internal static ConfigEntry<bool> DisableFoodDegradation;

		internal static ConfigEntry<float> HealthMultiplier;

		internal static ConfigEntry<float> StaminaMultiplier;

		internal static ConfigEntry<float> EitrMultiplier;

		internal static ConfigEntry<bool> EnableFoodFreezer;

		internal static ConfigEntry<float> HearthCheckRadius;

		internal static ConfigEntry<bool> RequireLitFire;

		internal static ConfigEntry<bool> FreezeWhenRested;

		internal static ConfigEntry<int> ExtraCookingSlots;

		internal static ConfigEntry<float> CookingTimeMultiplier;

		internal static ConfigEntry<bool> AutoPop;

		internal static ConfigEntry<bool> AutoPopFoodOnly;

		internal static ConfigEntry<bool> PatchFood;

		internal static ConfigEntry<bool> PatchHud;

		internal static ConfigEntry<bool> PatchCooking;

		internal static ConfigEntry<string> SkipPatches;

		private static readonly List<Action> Unsubscribers = new List<Action>();

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

		internal static event Action Changed;

		internal static void Bind(ConfigFile config)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Expected O, but got Unknown
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Expected O, but got Unknown
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Expected O, but got Unknown
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Expected O, but got Unknown
			Enabled = config.Bind<bool>("General", "Enabled", true, "Master switch for Feastworks.");
			LockConfiguration = config.Bind<bool>("ServerSync", "LockConfiguration", true, "When locked, only server administrators can change synchronized settings.");
			FoodSlots = config.Bind<int>("Food", "FoodSlots", 6, new ConfigDescription("Maximum simultaneous food buffs. Increases apply live; restart to reduce.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(3, 10), Array.Empty<object>()));
			FoodDurationMultiplier = config.Bind<float>("Food", "FoodDurationMultiplier", 1f, new ConfigDescription("Multiplier applied to food duration.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 5f), Array.Empty<object>()));
			DisableFoodDegradation = config.Bind<bool>("Food", "DisableFoodDegradation", false, "Keep full food benefits while their timers continue to expire normally.");
			HealthMultiplier = config.Bind<float>("Food", "HealthMultiplier", 1f, new ConfigDescription("Multiplier applied to food health benefits.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>()));
			StaminaMultiplier = config.Bind<float>("Food", "StaminaMultiplier", 1f, new ConfigDescription("Multiplier applied to food stamina benefits.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>()));
			EitrMultiplier = config.Bind<float>("Food", "EitrMultiplier", 1f, new ConfigDescription("Multiplier applied to food eitr benefits.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>()));
			EnableFoodFreezer = config.Bind<bool>("Food Freezer", "Enabled", false, "Pause the local player's food timers near a hearth.");
			HearthCheckRadius = config.Bind<float>("Food Freezer", "HearthCheckRadius", 30f, new ConfigDescription("Radius in meters searched for a hearth.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 100f), Array.Empty<object>()));
			RequireLitFire = config.Bind<bool>("Food Freezer", "RequireLitFire", true, "Only pause food timers near a burning hearth.");
			FreezeWhenRested = config.Bind<bool>("Food Freezer", "FreezeWhenRested", false, "Also pause food timers while Rested or Resting.");
			ExtraCookingSlots = config.Bind<int>("Cooking", "ExtraCookingSlots", 0, new ConfigDescription("Additional slots appended to every placed cooking station. Increases apply live; restart to reduce.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			CookingTimeMultiplier = config.Bind<float>("Cooking", "CookingTimeMultiplier", 1f, new ConfigDescription("Multiplier applied to every cooking-station recipe time.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>()));
			AutoPop = config.Bind<bool>("Cooking", "AutoPop", true, "Drop completed food beside its cooking station before it can burn.");
			AutoPopFoodOnly = config.Bind<bool>("Cooking", "AutoPopFoodOnly", true, "Only auto-pop cooking stations whose recipes all produce food.");
			PatchFood = config.Bind<bool>("Diagnostics", "PatchFood", true, "Local only. Apply food-slot/duration/benefit patches.");
			PatchHud = config.Bind<bool>("Diagnostics", "PatchHud", true, "Local only. Apply food HUD expansion patches.");
			PatchCooking = config.Bind<bool>("Diagnostics", "PatchCooking", true, "Local only. Apply cooking-station patches.");
			SkipPatches = config.Bind<string>("Diagnostics", "SkipPatches", "", "Local only. Comma-separated patch class names to skip.");
			Normalize();
			RegisterEntries();
		}

		internal static ConfigSync CreateConfigSync()
		{
			ConfigSync configSync = new ConfigSync("com.dfg.feastworks");
			configSync.DisplayName = "Feastworks";
			configSync.CurrentVersion = "1.0.1";
			configSync.MinimumRequiredVersion = "1.0.1";
			configSync.ModRequired = true;
			configSync.AddLockingConfigEntry<bool>(LockConfiguration);
			configSync.AddConfigEntry<bool>(Enabled);
			configSync.AddConfigEntry<int>(FoodSlots);
			configSync.AddConfigEntry<float>(FoodDurationMultiplier);
			configSync.AddConfigEntry<bool>(DisableFoodDegradation);
			configSync.AddConfigEntry<float>(HealthMultiplier);
			configSync.AddConfigEntry<float>(StaminaMultiplier);
			configSync.AddConfigEntry<float>(EitrMultiplier);
			configSync.AddConfigEntry<bool>(EnableFoodFreezer);
			configSync.AddConfigEntry<float>(HearthCheckRadius);
			configSync.AddConfigEntry<bool>(RequireLitFire);
			configSync.AddConfigEntry<bool>(FreezeWhenRested);
			configSync.AddConfigEntry<int>(ExtraCookingSlots);
			configSync.AddConfigEntry<float>(CookingTimeMultiplier);
			configSync.AddConfigEntry<bool>(AutoPop);
			configSync.AddConfigEntry<bool>(AutoPopFoodOnly);
			return configSync;
		}

		internal static void Dispose()
		{
			for (int i = 0; i < Unsubscribers.Count; i++)
			{
				Unsubscribers[i]();
			}
			Unsubscribers.Clear();
			FeastworksSettings.Changed = null;
		}

		private static void Normalize()
		{
			FoodSlots.Value = Mathf.Clamp(FoodSlots.Value, 3, 10);
			FoodDurationMultiplier.Value = Mathf.Clamp(FoodDurationMultiplier.Value, 0.25f, 5f);
			HealthMultiplier.Value = Mathf.Clamp(HealthMultiplier.Value, 0f, 5f);
			StaminaMultiplier.Value = Mathf.Clamp(StaminaMultiplier.Value, 0f, 5f);
			EitrMultiplier.Value = Mathf.Clamp(EitrMultiplier.Value, 0f, 5f);
			HearthCheckRadius.Value = Mathf.Clamp(HearthCheckRadius.Value, 1f, 100f);
			ExtraCookingSlots.Value = Mathf.Clamp(ExtraCookingSlots.Value, 0, 20);
			CookingTimeMultiplier.Value = Mathf.Clamp(CookingTimeMultiplier.Value, 0.1f, 10f);
		}

		private static void RegisterEntries()
		{
			Track<bool>(Enabled);
			Track<bool>(LockConfiguration);
			Track<int>(FoodSlots);
			Track<float>(FoodDurationMultiplier);
			Track<bool>(DisableFoodDegradation);
			Track<float>(HealthMultiplier);
			Track<float>(StaminaMultiplier);
			Track<float>(EitrMultiplier);
			Track<bool>(EnableFoodFreezer);
			Track<float>(HearthCheckRadius);
			Track<bool>(RequireLitFire);
			Track<bool>(FreezeWhenRested);
			Track<int>(ExtraCookingSlots);
			Track<float>(CookingTimeMultiplier);
			Track<bool>(AutoPop);
			Track<bool>(AutoPopFoodOnly);
		}

		private static void Track<T>(ConfigEntry<T> entry)
		{
			EventHandler handler = OnSettingChanged;
			entry.SettingChanged += handler;
			Unsubscribers.Add(delegate
			{
				entry.SettingChanged -= handler;
			});
		}

		private static void OnSettingChanged(object sender, EventArgs args)
		{
			FeastworksSettings.Changed?.Invoke();
		}
	}
	internal sealed class PatchLifecycle
	{
		private static readonly Type[] PatchTypes = new Type[11]
		{
			typeof(FoodSlotCanEatPatch),
			typeof(FoodSlotEatFoodPatch),
			typeof(FoodUpdatePatch),
			typeof(FoodEatDurationPatch),
			typeof(FoodBenefitsPatch),
			typeof(FoodCanEatAgainPatch),
			typeof(HudAwakePatch),
			typeof(HudFoodSlotsPatch),
			typeof(CookingStationAwakePatch),
			typeof(CookingStationUpdatePatch),
			typeof(CookingStationRemovePatch)
		};

		private readonly ManualLogSource m_log;

		private Harmony m_harmony;

		internal PatchLifecycle(ManualLogSource log)
		{
			m_log = log;
		}

		internal bool Apply()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			if (m_harmony != null)
			{
				return true;
			}
			Harmony val = new Harmony("com.dfg.feastworks");
			try
			{
				for (int i = 0; i < PatchTypes.Length; i++)
				{
					Type type = PatchTypes[i];
					bool num = type == typeof(HudAwakePatch) || type == typeof(HudFoodSlotsPatch);
					bool flag = type == typeof(CookingStationAwakePatch) || type == typeof(CookingStationUpdatePatch) || type == typeof(CookingStationRemovePatch);
					if (!(num ? FeastworksSettings.PatchHud.Value : (flag ? FeastworksSettings.PatchCooking.Value : FeastworksSettings.PatchFood.Value)) || (";" + FeastworksSettings.SkipPatches.Value.Replace(" ", "").Replace(",", ";") + ";").Contains(";" + type.Name + ";"))
					{
						m_log.LogInfo((object)("Diagnostics: skipped patch " + type.Name));
					}
					else
					{
						val.PatchAll(type);
					}
				}
				m_harmony = val;
				m_log.LogInfo((object)"Harmony patches applied.");
				return true;
			}
			catch (Exception ex)
			{
				try
				{
					val.UnpatchSelf();
				}
				catch (Exception ex2)
				{
					m_log.LogError((object)("Harmony rollback failed: " + ex2));
				}
				m_harmony = null;
				m_log.LogError((object)("Harmony patch setup failed: " + ex));
				return false;
			}
		}

		internal void Shutdown()
		{
			if (m_harmony == null)
			{
				return;
			}
			try
			{
				m_harmony.UnpatchSelf();
				m_log.LogInfo((object)"Harmony patches removed.");
			}
			catch (Exception ex)
			{
				m_log.LogError((object)("Harmony cleanup failed: " + ex));
			}
			finally
			{
				m_harmony = null;
			}
		}
	}
	[BepInPlugin("com.dfg.feastworks", "Feastworks", "1.0.1")]
	public sealed class FeastworksPlugin : BaseUnityPlugin
	{
		public const string PluginGUID = "com.dfg.feastworks";

		public const string PluginName = "Feastworks";

		public const string PluginVersion = "1.0.1";

		internal static ManualLogSource Log;

		private PatchLifecycle m_patches;

		private ConfigSync m_configSync;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			FeastworksSettings.Bind(((BaseUnityPlugin)this).Config);
			FeastworksSettings.Changed += OnSettingsChanged;
			FoodRuntime.Initialize();
			CookingRuntime.Initialize(Log);
			m_patches = new PatchLifecycle(Log);
			if (!m_patches.Apply())
			{
				((Behaviour)this).enabled = false;
				return;
			}
			try
			{
				m_configSync = FeastworksSettings.CreateConfigSync();
			}
			catch (Exception ex)
			{
				Log.LogError((object)("ServerSync initialization failed: " + ex));
				m_patches.Shutdown();
				((Behaviour)this).enabled = false;
				return;
			}
			LogCompatibilityWarnings();
			Log.LogInfo((object)("Feastworks 1.0.1 loaded. Config: " + ((BaseUnityPlugin)this).Config.ConfigFilePath));
		}

		private void Update()
		{
			FoodRuntime.Update();
			CookingRuntime.Update();
		}

		private void OnDestroy()
		{
			FeastworksSettings.Changed -= OnSettingsChanged;
			FeastworksSettings.Dispose();
			FoodRuntime.Shutdown();
			CookingRuntime.Shutdown();
			if (m_patches != null)
			{
				m_patches.Shutdown();
			}
			m_configSync = null;
		}

		private void OnSettingsChanged()
		{
			FoodRuntime.MarkSettingsChanged();
			CookingRuntime.MarkDirty();
		}

		private void LogCompatibilityWarnings()
		{
			if (Chainloader.PluginInfos.ContainsKey("com.foodfreezer.foodfreezer"))
			{
				Log.LogWarning((object)"FoodFreezer is loaded. Remove it from the DFG profile to avoid overlapping food-timer patches.");
			}
			if (Chainloader.PluginInfos.ContainsKey("blacks7ar.FoodDurationMultiplier"))
			{
				Log.LogWarning((object)"FoodDurationMultiplier is loaded. Disable it before using Feastworks food-duration settings.");
			}
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				if (pluginInfo.Value.Metadata.Name.IndexOf("extrafood", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					Log.LogWarning((object)(pluginInfo.Value.Metadata.Name + " is loaded and may overlap Feastworks food-slot patches."));
				}
				if (pluginInfo.Value.Metadata.Name.IndexOf("instantcook", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					Log.LogWarning((object)(pluginInfo.Value.Metadata.Name + " is loaded and may overlap Feastworks cooking-time behavior."));
				}
			}
		}
	}
	internal static class CookingRuntime
	{
		private sealed class StationState
		{
			internal CookingStation Station;

			internal ZNetView NetworkView;

			internal Transform[] OriginalSlots;

			internal ParticleSystem[] OriginalDoneParticles;

			internal ParticleSystem[] OriginalBurntParticles;

			internal readonly Dictionary<ItemConversion, float> CookTimes = new Dictionary<ItemConversion, float>();

			internal readonly Dictionary<ItemConversion, float> AppliedCookTimes = new Dictionary<ItemConversion, float>();

			internal readonly List<GameObject> CreatedObjects = new List<GameObject>();

			internal float LastCookingMultiplier = 1f;

			internal bool OwnsCookTimes;

			internal bool AllOutputsFood;

			internal bool ExpansionFailed;

			internal bool ExpansionErrorLogged;

			internal bool Dirty = true;

			internal float NextScan;

			internal int PendingAutoPop;

			internal float PendingAt;

			internal float NextAutoPopCheck;

			internal bool AutoPopDisabled;

			internal bool AutoPopErrorLogged;
		}

		private static readonly Dictionary<CookingStation, StationState> States = new Dictionary<CookingStation, StationState>();

		private static readonly List<StationState> StateList = new List<StationState>();

		private static readonly FieldInfo ParticleSystemsField = AccessTools.Field(typeof(CookingStation), "m_ps");

		private static readonly FieldInfo AudioSourcesField = AccessTools.Field(typeof(CookingStation), "m_as");

		private static readonly MethodInfo GetSlotMethod = AccessTools.Method(typeof(CookingStation), "GetSlot", (Type[])null, (Type[])null);

		private static ManualLogSource s_log;

		private static int s_cursor;

		private static float s_nextPrune;

		internal static void Initialize(ManualLogSource log)
		{
			s_log = log;
			States.Clear();
			StateList.Clear();
			s_cursor = 0;
			s_nextPrune = 0f;
		}

		internal static void MarkDirty()
		{
			for (int i = 0; i < StateList.Count; i++)
			{
				StateList[i].Dirty = true;
			}
		}

		internal static void Register(CookingStation station)
		{
			if (!((Object)(object)station == (Object)null) && !States.ContainsKey(station))
			{
				StationState stationState = new StationState
				{
					Station = station,
					NetworkView = ((Component)station).GetComponent<ZNetView>(),
					OriginalSlots = (station.m_slots ?? Array.Empty<Transform>()),
					OriginalDoneParticles = (station.m_donePS ?? Array.Empty<ParticleSystem>()),
					OriginalBurntParticles = (station.m_burntPS ?? Array.Empty<ParticleSystem>())
				};
				CaptureCookTimes(stationState);
				stationState.AllOutputsFood = AllConversionsProduceFood(station);
				States.Add(station, stationState);
				StateList.Add(stationState);
			}
		}

		internal static void ApplyExisting(CookingStation station)
		{
			if ((Object)(object)station != (Object)null && States.TryGetValue(station, out var value))
			{
				TryApply(value);
			}
		}

		internal static void Update()
		{
			if (StateList.Count == 0)
			{
				return;
			}
			int num = 0;
			while (num < 12 && StateList.Count > 0)
			{
				if (s_cursor >= StateList.Count)
				{
					s_cursor = 0;
				}
				StationState stationState = StateList[s_cursor];
				s_cursor = (s_cursor + 1) % StateList.Count;
				num++;
				if (!((Object)(object)stationState.Station == (Object)null) && !stationState.ExpansionFailed && (stationState.Dirty || Time.time >= stationState.NextScan))
				{
					TryApply(stationState);
				}
			}
			if (Time.time < s_nextPrune)
			{
				return;
			}
			s_nextPrune = Time.time + 10f;
			for (int num2 = StateList.Count - 1; num2 >= 0; num2--)
			{
				StationState stationState2 = StateList[num2];
				if (!((Object)(object)stationState2.Station != (Object)null))
				{
					States.Remove(stationState2.Station);
					StateList.RemoveAt(num2);
				}
			}
		}

		internal static void Shutdown()
		{
			for (int i = 0; i < StateList.Count; i++)
			{
				StationState state = StateList[i];
				RestoreCookTimes(state);
				RestoreStation(state);
			}
			States.Clear();
			StateList.Clear();
			s_cursor = 0;
		}

		internal static void UpdateAutoPop(CookingStation station)
		{
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)station == (Object)null || !FeastworksSettings.IsActive || !FeastworksSettings.AutoPop.Value)
			{
				return;
			}
			if (!States.TryGetValue(station, out var value))
			{
				Register(station);
				if (!States.TryGetValue(station, out value))
				{
					return;
				}
			}
			if (value.ExpansionFailed || value.AutoPopDisabled)
			{
				return;
			}
			if ((Object)(object)value.NetworkView == (Object)null)
			{
				value.NetworkView = ((Component)station).GetComponent<ZNetView>();
			}
			if ((Object)(object)value.NetworkView == (Object)null || !value.NetworkView.IsValid() || !value.NetworkView.IsOwner() || (FeastworksSettings.AutoPopFoodOnly.Value && !value.AllOutputsFood))
			{
				return;
			}
			if (GetSlotMethod == null)
			{
				value.AutoPopDisabled = true;
				LogAutoPopFailure(value, "CookingStation.GetSlot was not found.");
			}
			else
			{
				if ((value.PendingAutoPop > 0 && Time.time - value.PendingAt < 1f) || Time.time < value.NextAutoPopCheck)
				{
					return;
				}
				value.NextAutoPopCheck = Time.time + 0.25f;
				int num = 0;
				Transform[] slots = station.m_slots;
				try
				{
					for (int i = 0; i < slots.Length; i++)
					{
						if (TryGetSlot(station, i, out var itemName, out var status) && status == 1 && !string.IsNullOrEmpty(itemName))
						{
							num++;
						}
					}
				}
				catch (Exception ex)
				{
					value.AutoPopDisabled = true;
					value.PendingAutoPop = 0;
					LogAutoPopFailure(value, "Auto-pop slot inspection failed: " + ex.GetBaseException().Message);
					return;
				}
				if (num != 0)
				{
					Vector3 val = (((Object)(object)station.m_spawnPoint != (Object)null) ? station.m_spawnPoint.position : (((Component)station).transform.position + Vector3.up));
					value.PendingAutoPop = 1;
					value.PendingAt = Time.time;
					try
					{
						value.NetworkView.InvokeRPC("RPC_RemoveDoneItem", new object[2] { val, 1 });
						return;
					}
					catch (Exception ex2)
					{
						value.PendingAutoPop = 0;
						LogAutoPopFailure(value, "Auto-pop request failed: " + ex2.GetBaseException().Message);
						return;
					}
				}
				value.PendingAutoPop = 0;
			}
		}

		internal static void MarkAutoPopRemoved(CookingStation station, int amount)
		{
			if (!((Object)(object)station == (Object)null) && amount > 0 && States.TryGetValue(station, out var value))
			{
				value.PendingAutoPop = 0;
			}
		}

		private static void TryApply(StationState state)
		{
			if ((Object)(object)state.Station == (Object)null || state.ExpansionFailed)
			{
				return;
			}
			try
			{
				Apply(state);
			}
			catch (Exception ex)
			{
				state.ExpansionFailed = true;
				if (!state.ExpansionErrorLogged)
				{
					state.ExpansionErrorLogged = true;
					ManualLogSource obj = s_log;
					if (obj != null)
					{
						obj.LogWarning((object)(((Object)state.Station).name + ": Feastworks could not safely modify this cooking station: " + ex.GetBaseException().Message));
					}
				}
			}
		}

		private static void Apply(StationState state)
		{
			if (!((Object)(object)state.Station == (Object)null))
			{
				CaptureCookTimes(state);
				state.AllOutputsFood = AllConversionsProduceFood(state.Station);
				if (FeastworksSettings.IsActive)
				{
					EnsureExpanded(state);
					ApplyCookTimes(state);
				}
				else if (state.OwnsCookTimes)
				{
					RestoreCookTimes(state);
				}
				state.Dirty = false;
				state.NextScan = Time.time + 5f;
			}
		}

		private static void EnsureExpanded(StationState state)
		{
			CookingStation station = state.Station;
			if ((Object)(object)station == (Object)null || station.m_slots == null || station.m_slots.Length == 0 || FeastworksSettings.ExtraCookingSlots == null || FeastworksSettings.ExtraCookingSlots.Value <= 0)
			{
				return;
			}
			ZNetView component = ((Component)station).GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.GetZDO() != null)
			{
				int num = state.OriginalSlots.Length + FeastworksSettings.ExtraCookingSlots.Value;
				if (station.m_slots.Length < num)
				{
					ExpandSlots(state, num);
				}
				else
				{
					ExpandRuntimeArrays(station, station.m_slots);
				}
			}
		}

		private static void ExpandSlots(StationState state, int desired)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			CookingStation station = state.Station;
			Transform[] slots = station.m_slots;
			ParticleSystem[] donePS = station.m_donePS;
			ParticleSystem[] burntPS = station.m_burntPS;
			ParticleSystem[] value = ParticleSystemsField?.GetValue(station) as ParticleSystem[];
			AudioSource[] value2 = AudioSourcesField?.GetValue(station) as AudioSource[];
			List<Transform> list = new List<Transform>(station.m_slots);
			List<GameObject> list2 = new List<GameObject>();
			try
			{
				Vector3 val = Vector3.zero;
				if (list.Count >= 2)
				{
					val = list[list.Count - 1].localPosition - list[list.Count - 2].localPosition;
				}
				if (((Vector3)(ref val)).sqrMagnitude < 0.0001f)
				{
					val = Vector3.right;
				}
				while (list.Count < desired)
				{
					Transform val2 = list[list.Count - 1];
					GameObject val3 = Object.Instantiate<GameObject>(((Component)val2).gameObject, val2.parent, false);
					((Object)val3).name = "slot" + list.Count;
					val3.transform.localPosition = val2.localPosition + val;
					val3.transform.localRotation = val2.localRotation;
					val3.transform.localScale = val2.localScale;
					ParticleSystem component = val3.GetComponent<ParticleSystem>();
					AudioSource component2 = val3.GetComponent<AudioSource>();
					if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null)
					{
						Object.Destroy((Object)(object)val3);
						throw new InvalidOperationException("A cloned cooking slot is missing ParticleSystem or AudioSource.");
					}
					component.Stop(true, (ParticleSystemStopBehavior)0);
					component2.Stop();
					list2.Add(val3);
					list.Add(val3.transform);
				}
				Transform[] slots2 = list.ToArray();
				ParticleSystem[] donePS2 = ExpandOptionalParticles(state.OriginalDoneParticles, state.OriginalSlots, list, list2);
				ParticleSystem[] burntPS2 = ExpandOptionalParticles(state.OriginalBurntParticles, state.OriginalSlots, list, list2);
				ParticleSystem[] array = BuildRuntimeParticleArray(station, slots2);
				AudioSource[] array2 = BuildRuntimeAudioArray(station, slots2);
				if (ParticleSystemsField == null || AudioSourcesField == null)
				{
					throw new InvalidOperationException("CookingStation runtime slot arrays were not found.");
				}
				station.m_slots = slots2;
				station.m_donePS = donePS2;
				station.m_burntPS = burntPS2;
				if (array != null)
				{
					ParticleSystemsField.SetValue(station, array);
				}
				if (array2 != null)
				{
					AudioSourcesField.SetValue(station, array2);
				}
				state.CreatedObjects.AddRange(list2);
			}
			catch
			{
				station.m_slots = slots;
				station.m_donePS = donePS;
				station.m_burntPS = burntPS;
				if (ParticleSystemsField != null)
				{
					ParticleSystemsField.SetValue(station, value);
				}
				if (AudioSourcesField != null)
				{
					AudioSourcesField.SetValue(station, value2);
				}
				for (int i = 0; i < list2.Count; i++)
				{
					if ((Object)(object)list2[i] != (Object)null)
					{
						Object.Destroy((Object)(object)list2[i]);
					}
				}
				throw;
			}
			ManualLogSource obj2 = s_log;
			if (obj2 != null)
			{
				obj2.LogInfo((object)("Expanded " + ((Object)station).name + " from " + state.OriginalSlots.Length + " to " + station.m_slots.Length + " cooking slots."));
			}
		}

		private static ParticleSystem[] ExpandOptionalParticles(ParticleSystem[] original, Transform[] originalSlots, List<Transform> expandedSlots, List<GameObject> created)
		{
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			if (original == null || original.Length == 0)
			{
				return original ?? Array.Empty<ParticleSystem>();
			}
			if (expandedSlots.Count <= original.Length)
			{
				return original;
			}
			ParticleSystem[] array = (ParticleSystem[])(object)new ParticleSystem[expandedSlots.Count];
			for (int i = 0; i < array.Length; i++)
			{
				if (i < original.Length)
				{
					array[i] = original[i];
					continue;
				}
				int num = Math.Min(i, original.Length - 1);
				while (num >= 0 && (Object)(object)original[num] == (Object)null)
				{
					num--;
				}
				if (num < 0)
				{
					throw new InvalidOperationException("Cooking-station particle array has no template.");
				}
				ParticleSystem val = original[num];
				ParticleSystem val2 = FindParticleInClonedSlot(val, num, originalSlots, expandedSlots, i);
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = Object.Instantiate<ParticleSystem>(val, ((Component)val).transform.parent);
					created.Add(((Component)val2).gameObject);
					((Object)val2).name = ((Object)val).name + i;
					((Component)val2).transform.position = expandedSlots[i].position;
					((Component)val2).transform.rotation = expandedSlots[i].rotation;
					((Component)val2).transform.localScale = ((Component)val).transform.localScale;
				}
				if ((Object)(object)val2 == (Object)null)
				{
					throw new InvalidOperationException("A cooking-station particle template could not be cloned.");
				}
				val2.Stop(true, (ParticleSystemStopBehavior)0);
				array[i] = val2;
			}
			return array;
		}

		private static ParticleSystem FindParticleInClonedSlot(ParticleSystem template, int templateIndex, Transform[] originalSlots, List<Transform> expandedSlots, int targetIndex)
		{
			if (templateIndex >= originalSlots.Length || (Object)(object)originalSlots[templateIndex] == (Object)null)
			{
				return null;
			}
			Transform val = originalSlots[templateIndex];
			if (!((Component)template).transform.IsChildOf(val))
			{
				return null;
			}
			string relativePath = GetRelativePath(val, ((Component)template).transform);
			Transform obj = (string.IsNullOrEmpty(relativePath) ? expandedSlots[targetIndex] : expandedSlots[targetIndex].Find(relativePath));
			if (obj == null)
			{
				return null;
			}
			return ((Component)obj).GetComponent<ParticleSystem>();
		}

		private static void ExpandRuntimeArrays(CookingStation station, Transform[] slots)
		{
			ParticleSystem[] array = BuildRuntimeParticleArray(station, slots);
			AudioSource[] array2 = BuildRuntimeAudioArray(station, slots);
			if (array != null)
			{
				ParticleSystemsField.SetValue(station, array);
			}
			if (array2 != null)
			{
				AudioSourcesField.SetValue(station, array2);
			}
		}

		private static ParticleSystem[] BuildRuntimeParticleArray(CookingStation station, Transform[] slots)
		{
			ParticleSystem[] array = ParticleSystemsField?.GetValue(station) as ParticleSystem[];
			if (array == null || array.Length >= slots.Length)
			{
				return array;
			}
			ParticleSystem[] array2 = (ParticleSystem[])(object)new ParticleSystem[slots.Length];
			Array.Copy(array, array2, array.Length);
			for (int i = array.Length; i < array2.Length; i++)
			{
				array2[i] = ((Component)slots[i]).GetComponent<ParticleSystem>();
				if ((Object)(object)array2[i] == (Object)null)
				{
					throw new InvalidOperationException("Cooking-station runtime particle array could not be expanded.");
				}
			}
			return array2;
		}

		private static AudioSource[] BuildRuntimeAudioArray(CookingStation station, Transform[] slots)
		{
			AudioSource[] array = AudioSourcesField?.GetValue(station) as AudioSource[];
			if (array == null || array.Length >= slots.Length)
			{
				return array;
			}
			AudioSource[] array2 = (AudioSource[])(object)new AudioSource[slots.Length];
			Array.Copy(array, array2, array.Length);
			for (int i = array.Length; i < array2.Length; i++)
			{
				array2[i] = ((Component)slots[i]).GetComponent<AudioSource>();
				if ((Object)(object)array2[i] == (Object)null)
				{
					throw new InvalidOperationException("Cooking-station runtime audio array could not be expanded.");
				}
			}
			return array2;
		}

		private static void RestoreStation(StationState state)
		{
			CookingStation station = state.Station;
			if ((Object)(object)station != (Object)null && ParticleSystemsField != null && AudioSourcesField != null)
			{
				ParticleSystem[] array = (ParticleSystem[])(object)new ParticleSystem[state.OriginalSlots.Length];
				AudioSource[] array2 = (AudioSource[])(object)new AudioSource[state.OriginalSlots.Length];
				for (int i = 0; i < state.OriginalSlots.Length; i++)
				{
					array[i] = ((Component)state.OriginalSlots[i]).GetComponent<ParticleSystem>();
					array2[i] = ((Component)state.OriginalSlots[i]).GetComponent<AudioSource>();
				}
				station.m_slots = state.OriginalSlots;
				station.m_donePS = state.OriginalDoneParticles;
				station.m_burntPS = state.OriginalBurntParticles;
				ParticleSystemsField.SetValue(station, array);
				AudioSourcesField.SetValue(station, array2);
			}
			for (int j = 0; j < state.CreatedObjects.Count; j++)
			{
				if ((Object)(object)state.CreatedObjects[j] != (Object)null)
				{
					Object.Destroy((Object)(object)state.CreatedObjects[j]);
				}
			}
			state.CreatedObjects.Clear();
		}

		private static void CaptureCookTimes(StationState state)
		{
			if (state.Station.m_conversion == null)
			{
				return;
			}
			for (int i = 0; i < state.Station.m_conversion.Count; i++)
			{
				ItemConversion val = state.Station.m_conversion[i];
				if (val != null && !state.CookTimes.ContainsKey(val))
				{
					state.CookTimes.Add(val, val.m_cookTime);
				}
			}
		}

		private static void ApplyCookTimes(StationState state)
		{
			float num = Mathf.Clamp(FeastworksSettings.CookingTimeMultiplier.Value, 0.1f, 10f);
			List<KeyValuePair<ItemConversion, float>> list = null;
			foreach (KeyValuePair<ItemConversion, float> cookTime in state.CookTimes)
			{
				ItemConversion key = cookTime.Key;
				if (key == null)
				{
					continue;
				}
				float value = 0f;
				bool flag = !state.OwnsCookTimes || !state.AppliedCookTimes.TryGetValue(key, out value);
				if (!flag)
				{
					float num2 = Mathf.Max(0.01f, value * 0.01f);
					flag = Mathf.Abs(key.m_cookTime - value) > num2;
				}
				if (flag)
				{
					if (list == null)
					{
						list = new List<KeyValuePair<ItemConversion, float>>();
					}
					float value2 = ((state.OwnsCookTimes && state.LastCookingMultiplier > 0f) ? (key.m_cookTime / state.LastCookingMultiplier) : key.m_cookTime);
					list.Add(new KeyValuePair<ItemConversion, float>(key, value2));
				}
			}
			if (list != null)
			{
				for (int i = 0; i < list.Count; i++)
				{
					state.CookTimes[list[i].Key] = list[i].Value;
				}
			}
			foreach (KeyValuePair<ItemConversion, float> cookTime2 in state.CookTimes)
			{
				if (cookTime2.Key != null)
				{
					float num3 = Mathf.Max(0.1f, cookTime2.Value * num);
					cookTime2.Key.m_cookTime = num3;
					state.AppliedCookTimes[cookTime2.Key] = num3;
				}
			}
			state.LastCookingMultiplier = num;
			state.OwnsCookTimes = true;
		}

		private static void RestoreCookTimes(StationState state)
		{
			if (!state.OwnsCookTimes)
			{
				return;
			}
			foreach (KeyValuePair<ItemConversion, float> cookTime in state.CookTimes)
			{
				if (cookTime.Key != null)
				{
					cookTime.Key.m_cookTime = cookTime.Value;
				}
			}
			state.AppliedCookTimes.Clear();
			state.LastCookingMultiplier = 1f;
			state.OwnsCookTimes = false;
		}

		private static bool AllConversionsProduceFood(CookingStation station)
		{
			if (station.m_conversion == null || station.m_conversion.Count == 0)
			{
				return false;
			}
			for (int i = 0; i < station.m_conversion.Count; i++)
			{
				SharedData val = (station.m_conversion[i]?.m_to)?.m_itemData?.m_shared;
				if (val == null || val.m_foodBurnTime <= 0f)
				{
					return false;
				}
			}
			return true;
		}

		private static bool TryGetSlot(CookingStation station, int index, out string itemName, out int status)
		{
			Type type = GetSlotMethod.GetParameters()[3].ParameterType;
			if (type.IsByRef)
			{
				type = type.GetElementType();
			}
			object obj = ((type != null && type.IsEnum) ? Enum.ToObject(type, 0) : ((object)0));
			object[] array = new object[5] { index, null, 0f, obj, false };
			GetSlotMethod.Invoke(station, array);
			itemName = array[1] as string;
			status = Convert.ToInt32(array[3]);
			return itemName != null;
		}

		private static string GetRelativePath(Transform root, Transform target)
		{
			if ((Object)(object)target == (Object)(object)root)
			{
				return string.Empty;
			}
			if ((Object)(object)target == (Object)null || !target.IsChildOf(root))
			{
				return null;
			}
			List<string> list = new List<string>();
			Transform val = target;
			while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)root)
			{
				list.Add(((Object)val).name);
				val = val.parent;
			}
			list.Reverse();
			return string.Join("/", list.ToArray());
		}

		private static void LogAutoPopFailure(StationState state, string message)
		{
			if (!state.AutoPopErrorLogged)
			{
				state.AutoPopErrorLogged = true;
				ManualLogSource obj = s_log;
				if (obj != null)
				{
					obj.LogWarning((object)(((Object)state.Station).name + ": " + message));
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class CookingStationAwakePatch
	{
		private static MethodInfo TargetMethod()
		{
			return AccessTools.Method(typeof(CookingStation), "Awake", Type.EmptyTypes, (Type[])null);
		}

		private static void Postfix(CookingStation __instance)
		{
			CookingRuntime.Register(__instance);
		}
	}
	[HarmonyPatch]
	internal static class CookingStationUpdatePatch
	{
		private static MethodInfo TargetMethod()
		{
			return AccessTools.Method(typeof(CookingStation), "UpdateCooking", Type.EmptyTypes, (Type[])null);
		}

		private static void Postfix(CookingStation __instance)
		{
			CookingRuntime.UpdateAutoPop(__instance);
		}
	}
	[HarmonyPatch]
	internal static class CookingStationRemovePatch
	{
		private static MethodInfo TargetMethod()
		{
			return AccessTools.Method(typeof(CookingStation), "RPC_RemoveDoneItem", new Type[3]
			{
				typeof(long),
				typeof(Vector3),
				typeof(int)
			}, (Type[])null);
		}

		private static void Postfix(CookingStation __instance, int amount)
		{
			CookingRuntime.MarkAutoPopRemoved(__instance, amount);
		}
	}
	[HarmonyPatch]
	internal static class HudAwakePatch
	{
		private static MethodInfo TargetMethod()
		{
			return AccessTools.Method(typeof(Hud), "Awake", Type.EmptyTypes, (Type[])null);
		}

		private static void Postfix(Hud __instance)
		{
			FoodHudFeature.EnsureSlots(__instance);
		}
	}
	[HarmonyPatch]
	internal static class HudFoodSlotsPatch
	{
		private static MethodInfo TargetMethod()
		{
			return AccessTools.Method(typeof(Hud), "UpdateFood", new Type[1] { typeof(Player) }, (Type[])null);
		}

		private static void Prefix(Hud __instance)
		{
			FoodHudFeature.EnsureSlots(__instance);
		}

		private static void Postfix(Hud __instance)
		{
			FoodHudFeature.SyncBackgrounds(__instance);
		}
	}
	internal static class FoodHudFeature
	{
		private sealed class LayoutMetrics
		{
			internal Component Top;

			internal float MaxY;

			internal float Spacing;
		}

		private static readonly Dictionary<int, GameObject> Backgrounds = new Dictionary<int, GameObject>();

		private static bool s_loggedFailure;

		internal static void EnsureSlots(Hud hud)
		{
			if ((Object)(object)hud == (Object)null || !FeastworksSettings.IsActive)
			{
				return;
			}
			if (hud.m_foodBars == null || hud.m_foodIcons == null || hud.m_foodTime == null)
			{
				LogFailure("Food HUD arrays are unavailable.");
				return;
			}
			int num = hud.m_foodBars.Length;
			if (hud.m_foodIcons.Length != num || hud.m_foodTime.Length != num || num < 3)
			{
				LogFailure("Food HUD slot arrays have incompatible lengths.");
				return;
			}
			int num2 = Mathf.Clamp(FeastworksSettings.FoodSlots.Value, 3, 10);
			if (num >= num2)
			{
				SyncBackgrounds(hud);
				return;
			}
			LayoutMetrics layoutMetrics = MeasureImages(hud.m_foodBars);
			LayoutMetrics layoutMetrics2 = MeasureImages(hud.m_foodIcons);
			LayoutMetrics layoutMetrics3 = MeasureText(hud.m_foodTime);
			if (layoutMetrics == null || layoutMetrics2 == null || layoutMetrics3 == null)
			{
				LogFailure("Food HUD slot positions could not be measured.");
				return;
			}
			List<Image> list = new List<Image>(hud.m_foodBars);
			List<Image> list2 = new List<Image>(hud.m_foodIcons);
			List<TMP_Text> list3 = new List<TMP_Text>(hud.m_foodTime);
			List<GameObject> list4 = new List<GameObject>();
			List<int> list5 = new List<int>();
			try
			{
				for (int i = num; i < num2; i++)
				{
					Component top = layoutMetrics.Top;
					Image val = CloneNext((Image)(object)((top is Image) ? top : null), layoutMetrics, i, "Feastworks_foodBar" + i, list4);
					Component top2 = layoutMetrics2.Top;
					Component obj = ((top2 is Image) ? top2 : null);
					Image val2 = CloneNext((Image)(object)obj, layoutMetrics2, i, "Feastworks_foodIcon" + i, list4);
					Component top3 = layoutMetrics3.Top;
					TMP_Text val3 = CloneNext((TMP_Text)(object)((top3 is TMP_Text) ? top3 : null), layoutMetrics3, i, "Feastworks_foodTime" + i, list4);
					if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null)
					{
						throw new InvalidOperationException("A food HUD component could not be cloned.");
					}
					list.Add(val);
					list2.Add(val2);
					list3.Add(val3);
					GameObject val4 = CloneBackground((Image)(object)obj, val2, i);
					if ((Object)(object)val4 != (Object)null)
					{
						Backgrounds[i] = val4;
						list5.Add(i);
						list4.Add(val4);
					}
				}
				hud.m_foodBars = list.ToArray();
				hud.m_foodIcons = list2.ToArray();
				hud.m_foodTime = list3.ToArray();
				for (int j = 0; j < list4.Count; j++)
				{
					if ((Object)(object)list4[j] != (Object)null && !Backgrounds.ContainsValue(list4[j]))
					{
						list4[j].SetActive(false);
					}
				}
				SyncBackgrounds(hud);
			}
			catch (Exception ex)
			{
				for (int k = 0; k < list4.Count; k++)
				{
					Destroy(list4[k]);
				}
				for (int l = 0; l < list5.Count; l++)
				{
					Backgrounds.Remove(list5[l]);
				}
				LogFailure("Food HUD expansion failed safely: " + ex.GetBaseException().Message);
			}
		}

		internal static void SyncBackgrounds(Hud hud)
		{
			if ((Object)(object)hud == (Object)null || hud.m_foodIcons == null || Backgrounds.Count == 0)
			{
				return;
			}
			List<int> list = null;
			foreach (KeyValuePair<int, GameObject> background in Backgrounds)
			{
				if ((Object)(object)background.Value == (Object)null || background.Key < 0 || background.Key >= hud.m_foodIcons.Length || (Object)(object)hud.m_foodIcons[background.Key] == (Object)null)
				{
					if (list == null)
					{
						list = new List<int>();
					}
					list.Add(background.Key);
				}
				else
				{
					bool activeSelf = ((Component)hud.m_foodIcons[background.Key]).gameObject.activeSelf;
					if (background.Value.activeSelf != activeSelf)
					{
						background.Value.SetActive(activeSelf);
					}
				}
			}
			if (list != null)
			{
				for (int i = 0; i < list.Count; i++)
				{
					Backgrounds.Remove(list[i]);
				}
			}
		}

		private static LayoutMetrics MeasureImages(Image[] images)
		{
			//IL_003b: 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)
			if (images == null || images.Length < 3)
			{
				return null;
			}
			LayoutMetrics layoutMetrics = new LayoutMetrics();
			float num = float.MaxValue;
			float num2 = float.MinValue;
			foreach (Image val in images)
			{
				if ((Object)(object)val == (Object)null)
				{
					return null;
				}
				float y = ((Component)val).transform.position.y;
				if (y < num)
				{
					num = y;
				}
				if (y > num2 || (Object)(object)layoutMetrics.Top == (Object)null)
				{
					num2 = y;
					layoutMetrics.Top = (Component)(object)val;
				}
			}
			float num3 = float.MaxValue;
			float num4 = float.MinValue;
			for (int j = 0; j < 3; j++)
			{
				float y2 = ((Component)images[j]).transform.position.y;
				num3 = Mathf.Min(num3, y2);
				num4 = Mathf.Max(num4, y2);
			}
			layoutMetrics.MaxY = num2;
			layoutMetrics.Spacing = (num4 - num3) * 0.5f;
			if (!(layoutMetrics.Spacing > 0.01f))
			{
				return null;
			}
			return layoutMetrics;
		}

		private static LayoutMetrics MeasureText(TMP_Text[] texts)
		{
			//IL_003b: 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)
			if (texts == null || texts.Length < 3)
			{
				return null;
			}
			LayoutMetrics layoutMetrics = new LayoutMetrics();
			float num = float.MaxValue;
			float num2 = float.MinValue;
			foreach (TMP_Text val in texts)
			{
				if ((Object)(object)val == (Object)null)
				{
					return null;
				}
				float y = val.transform.position.y;
				if (y < num)
				{
					num = y;
				}
				if (y > num2 || (Object)(object)layoutMetrics.Top == (Object)null)
				{
					num2 = y;
					layoutMetrics.Top = (Component)(object)val;
				}
			}
			float num3 = float.MaxValue;
			float num4 = float.MinValue;
			for (int j = 0; j < 3; j++)
			{
				float y2 = texts[j].transform.position.y;
				num3 = Mathf.Min(num3, y2);
				num4 = Mathf.Max(num4, y2);
			}
			layoutMetrics.MaxY = num2;
			layoutMetrics.Spacing = (num4 - num3) * 0.5f;
			if (!(layoutMetrics.Spacing > 0.01f))
			{
				return null;
			}
			return layoutMetrics;
		}

		private static Image CloneNext(Image source, LayoutMetrics metrics, int index, string cloneName, List<GameObject> created)
		{
			return CloneNext<Image>(source, metrics, index, cloneName, created);
		}

		private static TMP_Text CloneNext(TMP_Text source, LayoutMetrics metrics, int index, string cloneName, List<GameObject> created)
		{
			return CloneNext<TMP_Text>(source, metrics, index, cloneName, created);
		}

		private static T CloneNext<T>(T source, LayoutMetrics metrics, int index, string cloneName, List<GameObject> created) where T : Component
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)source == (Object)null)
			{
				return default(T);
			}
			GameObject val = Object.Instantiate<GameObject>(((Component)source).gameObject, ((Component)source).transform.parent, false);
			((Object)val).name = cloneName;
			T component = val.GetComponent<T>();
			if ((Object)(object)component == (Object)null)
			{
				Destroy(val);
				return default(T);
			}
			Vector3 position = ((Component)component).transform.position;
			position.y = metrics.MaxY + metrics.Spacing;
			((Component)component).transform.position = position;
			((Component)component).transform.SetAsLastSibling();
			metrics.Top = (Component)(object)component;
			metrics.MaxY = position.y;
			created.Add(val);
			val.SetActive(false);
			return component;
		}

		private static GameObject CloneBackground(Image topIcon, Image newIcon, int index)
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)topIcon == (Object)null || (Object)(object)newIcon == (Object)null || (Object)(object)((Component)topIcon).transform.parent == (Object)null || (Object)(object)((Component)topIcon).transform.parent.parent == (Object)null)
			{
				return null;
			}
			Transform parent = ((Component)topIcon).transform.parent;
			GameObject val = Object.Instantiate<GameObject>(((Component)parent).gameObject, parent.parent, false);
			((Object)val).name = "Feastworks_foodBackground" + index;
			val.transform.position = parent.position + (((Component)newIcon).transform.position - ((Component)topIcon).transform.position);
			val.transform.SetSiblingIndex(parent.GetSiblingIndex());
			for (int i = 0; i < val.transform.childCount; i++)
			{
				((Component)val.transform.GetChild(i)).gameObject.SetActive(false);
			}
			val.SetActive(false);
			return val;
		}

		private static void Destroy(GameObject gameObject)
		{
			if ((Object)(object)gameObject != (Object)null)
			{
				Object.Destroy((Object)(object)gameObject);
			}
		}

		private static void LogFailure(string message)
		{
			if (!s_loggedFailure)
			{
				s_loggedFailure = true;
				FeastworksPlugin.Log.LogWarning((object)message);
			}
		}
	}
	internal static class FoodRuntime
	{
		private static readonly int HearthLayerMask = LayerMask.GetMask(new string[2] { "piece", "piece_nonsolid" });

		private static readonly Dictionary<Food, float> ActiveFoodMultipliers = new Dictionary<Food, float>();

		private static readonly MethodInfo UpdateFoodMethod = AccessTools.Method(typeof(Playe