Decompiled source of TheGreatestShips v0.9.5

BepInEx/plugins/TheGreatestShips.dll

Decompiled a day 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.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Jotunn;
using Jotunn.Managers;
using Microsoft.CodeAnalysis;
using ServerSync;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("TheGreatestShips")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("New ships built from the vanilla hulls, starting with the Fast Karve.")]
[assembly: AssemblyFileVersion("0.9.5.0")]
[assembly: AssemblyInformationalVersion("0.9.5+8fb5e54f8e3fdf360267ab1bce3bb865114cc35c")]
[assembly: AssemblyProduct("TheGreatestShips")]
[assembly: AssemblyTitle("TheGreatestShips")]
[assembly: AssemblyVersion("0.9.5.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 JetBrains.Annotations
{
	[AttributeUsage(AttributeTargets.All)]
	internal sealed class PublicAPIAttribute : Attribute
	{
		public PublicAPIAttribute()
		{
		}

		public PublicAPIAttribute(string comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All)]
	internal sealed class UsedImplicitlyAttribute : Attribute
	{
	}
}
namespace ServerSync
{
	[PublicAPI]
	public abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	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;
			};
		}
	}
	[PublicAPI]
	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
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	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;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = 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;
			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 var 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);
				ConfigFile val2 = null;
				bool saveOnConfigSet = false;
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					if (val2 == null)
					{
						val2 = configValue.Key.BaseConfig.ConfigFile;
						saveOnConfigSet = val2.SaveOnConfigSet;
						val2.SaveOnConfigSet = false;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				if (val2 != null)
				{
					val2.SaveOnConfigSet = saveOnConfigSet;
					val2.Save();
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.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();
		}
	}
	[PublicAPI]
	[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_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			object obj = AccessTools.Field(typeof(FejdStartup), "m_connectionFailedError")?.GetValue(__instance);
			if (obj == null)
			{
				return;
			}
			PropertyInfo property = obj.GetType().GetProperty("text");
			if (property == null)
			{
				return;
			}
			bool flag = false;
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				property.SetValue(obj, (string)property.GetValue(obj) + "\n" + text);
				flag = true;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy((KeyValuePair<string, string> kv) => kv.Key))
			{
				string text2 = (string)property.GetValue(obj);
				if (!text2.Contains(item.Key))
				{
					property.SetValue(obj, text2 + "\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;
				obj.GetType().GetMethod("ForceMeshUpdate", Type.EmptyTypes)?.Invoke(obj, null);
				float num = (float)(obj.GetType().GetProperty("renderedHeight")?.GetValue(obj) ?? ((object)0f)) + 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 TheGreatestShips
{
	internal sealed class PenSpec
	{
		public float Length;

		public float Width;

		public float CenterZ;

		public float PostHeight;

		public float[] RailHeights;
	}
	internal static class AnimalPen
	{
		private const string PostPrefabName = "wood_pole";

		private const string Beam2PrefabName = "wood_beam";

		private const string Beam1PrefabName = "wood_beam_1";

		private const float DeckHeight = 0.58f;

		private const float PostWidth = 0.4f;

		private const float GateWidth = 2f;

		internal static void Build(GameObject clone, PenSpec spec)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_032e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_0378: Unknown result type (might be due to invalid IL or missing references)
			//IL_038a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_072c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0741: Unknown result type (might be due to invalid IL or missing references)
			//IL_076b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0780: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_07c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_07e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_07e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_07fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0807: Unknown result type (might be due to invalid IL or missing references)
			//IL_0819: Unknown result type (might be due to invalid IL or missing references)
			//IL_081f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0839: Unknown result type (might be due to invalid IL or missing references)
			//IL_083e: Unknown result type (might be due to invalid IL or missing references)
			//IL_084e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0493: Unknown result type (might be due to invalid IL or missing references)
			//IL_049a: Expected O, but got Unknown
			//IL_04c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0436: Unknown result type (might be due to invalid IL or missing references)
			//IL_043b: Unknown result type (might be due to invalid IL or missing references)
			//IL_045a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0613: Unknown result type (might be due to invalid IL or missing references)
			//IL_0621: Unknown result type (might be due to invalid IL or missing references)
			//IL_0650: Unknown result type (might be due to invalid IL or missing references)
			//IL_065e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0691: Unknown result type (might be due to invalid IL or missing references)
			//IL_069f: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0547: Unknown result type (might be due to invalid IL or missing references)
			//IL_092e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0933: Unknown result type (might be due to invalid IL or missing references)
			//IL_0952: Expected O, but got Unknown
			GameObject prefab = PrefabManager.Instance.GetPrefab("wood_pole");
			GameObject prefab2 = PrefabManager.Instance.GetPrefab("wood_beam");
			GameObject prefab3 = PrefabManager.Instance.GetPrefab("wood_beam_1");
			if ((Object)(object)prefab == (Object)null || (Object)(object)prefab2 == (Object)null || (Object)(object)prefab3 == (Object)null)
			{
				Logger.LogError((object)"[TheGreatestShips] Animal pen: 'wood_pole', 'wood_beam' or 'wood_beam_1' not found; no pen built.");
				return;
			}
			GameObject val = new GameObject("animal_pen");
			val.transform.SetParent(clone.transform, false);
			val.AddComponent<PenBallast>();
			val.AddComponent<PenLip>();
			Rigidbody component = clone.GetComponent<Rigidbody>();
			if ((Object)(object)component != (Object)null)
			{
				component.collisionDetectionMode = (CollisionDetectionMode)3;
			}
			float num = spec.Length / 2f;
			float num2 = spec.Width / 2f;
			int num3 = 0;
			int num4 = 0;
			Vector3[] array = (Vector3[])(object)new Vector3[4]
			{
				new Vector3(num2, 0f, num),
				new Vector3(0f - num2, 0f, num),
				new Vector3(num2, 0f, 0f - num),
				new Vector3(0f - num2, 0f, 0f - num)
			};
			foreach (Vector3 val2 in array)
			{
				Place(prefab, val.transform, val2 + new Vector3(0f, 0.58f + spec.PostHeight / 2f, spec.CenterZ), Quaternion.identity).transform.localScale = new Vector3(1f, spec.PostHeight, 1f);
				num3++;
				num4++;
			}
			float num5 = 0f;
			float[] railHeights = spec.RailHeights;
			foreach (float num6 in railHeights)
			{
				num5 = Mathf.Max(num5, num6 + 0.2f);
			}
			float num7 = spec.Length - 0.4f;
			float num8 = Mathf.Min(2f, num7);
			float num9 = ((num8 >= num7 - 0.01f) ? 0f : ((num7 - num8) / 2f - 0.4f));
			float num10 = num - 0.2f - num9 / 2f;
			float num11 = num - num8 / 2f;
			float num12 = (num + num8 / 2f) / 2f;
			railHeights = spec.RailHeights;
			foreach (float num13 in railHeights)
			{
				float num14 = 0.58f + num13;
				float[] array2 = new float[2]
				{
					num,
					0f - num
				};
				foreach (float num15 in array2)
				{
					(int long2, int short1) tuple = PlaceRail(val.transform, prefab2, prefab3, new Vector3(0f, num14, spec.CenterZ + num15), 0f, spec.Width - 0.4f);
					int item = tuple.long2;
					int item2 = tuple.short1;
					num3 += item + item2;
					num4 += item * 2 + item2;
				}
			}
			Wall(val.transform, new Vector3(0f, 0.58f + num5 / 2f, spec.CenterZ + num - 0.1f), new Vector3(spec.Width, num5, 0.2f), prefab.layer);
			Wall(val.transform, new Vector3(0f, 0.58f + num5 / 2f, spec.CenterZ - num + 0.1f), new Vector3(spec.Width, num5, 0.2f), prefab.layer);
			List<GameObject> list = new List<GameObject>();
			railHeights = new float[2] { 1f, -1f };
			foreach (float num16 in railHeights)
			{
				float num17 = num16 * num2;
				float[] array2;
				if (num9 > 0.01f)
				{
					array2 = new float[2]
					{
						num8 / 2f + 0.2f,
						0f - (num8 / 2f + 0.2f)
					};
					foreach (float num18 in array2)
					{
						Place(prefab, val.transform, new Vector3(num17, 0.58f + spec.PostHeight / 2f, spec.CenterZ + num18), Quaternion.identity).transform.localScale = new Vector3(1f, spec.PostHeight, 1f);
						num3++;
						num4++;
					}
				}
				GameObject val3 = new GameObject((num16 > 0f) ? "pen_gate" : "pen_gate_port");
				val3.transform.SetParent(val.transform, false);
				val3.transform.localPosition = new Vector3(num17, 0.58f, spec.CenterZ);
				val3.AddComponent<PenGate>().Port = num16 < 0f;
				list.Add(val3);
				array2 = spec.RailHeights;
				foreach (float num19 in array2)
				{
					float num20 = 0.58f + num19;
					if (num9 > 0.01f)
					{
						float[] array3 = new float[2]
						{
							num10,
							0f - num10
						};
						foreach (float num21 in array3)
						{
							(int long2, int short1) tuple2 = PlaceRail(val.transform, prefab2, prefab3, new Vector3(num17, num20, spec.CenterZ + num21), 90f, num9);
							int item3 = tuple2.long2;
							int item4 = tuple2.short1;
							num3 += item3 + item4;
							num4 += item3 * 2 + item4;
						}
					}
					(int long2, int short1) tuple3 = PlaceRail(val3.transform, prefab2, prefab3, new Vector3(0f, num19, 0f), 90f, num8);
					int item5 = tuple3.long2;
					int item6 = tuple3.short1;
					num3 += item5 + item6;
					num4 += item5 * 2 + item6;
				}
				float num22 = num16 * (num2 - 0.1f);
				Wall(val.transform, new Vector3(num22, 0.58f + num5 / 2f, spec.CenterZ + num12), new Vector3(0.2f, num5, num11), prefab.layer);
				Wall(val.transform, new Vector3(num22, 0.58f + num5 / 2f, spec.CenterZ - num12), new Vector3(0.2f, num5, num11), prefab.layer);
				Wall(val3.transform, new Vector3((0f - num16) * 0.2f / 2f, num5 / 2f, 0f), new Vector3(0.2f, num5, num8), prefab.layer);
			}
			(Vector3, Vector3)[] array4 = new(Vector3, Vector3)[4]
			{
				(new Vector3(0f, 0f, spec.CenterZ + num - 0.2f - 0.3f), new Vector3(spec.Width, 0.2f, 0.6f)),
				(new Vector3(0f, 0f, spec.CenterZ - num + 0.2f + 0.3f), new Vector3(spec.Width, 0.2f, 0.6f)),
				(new Vector3(num2 - 0.2f - 0.3f, 0f, spec.CenterZ), new Vector3(0.6f, 0.2f, spec.Length)),
				(new Vector3(0f - num2 + 0.2f + 0.3f, 0f, spec.CenterZ), new Vector3(0.6f, 0.2f, spec.Length))
			};
			for (int i = 0; i < array4.Length; i++)
			{
				(Vector3, Vector3) tuple4 = array4[i];
				Vector3 item7 = tuple4.Item1;
				Vector3 item8 = tuple4.Item2;
				GameObject val4 = new GameObject("pen_lip")
				{
					layer = prefab.layer
				};
				val4.transform.SetParent(val.transform, false);
				val4.transform.localPosition = item7 + new Vector3(0f, 0.58f + num5 + 0.1f, 0f);
				BoxCollider obj = val4.AddComponent<BoxCollider>();
				obj.size = item8;
				((Collider)obj).enabled = false;
			}
			foreach (GameObject item9 in list)
			{
				Collider[] componentsInChildren = item9.GetComponentsInChildren<Collider>(true);
				foreach (Collider val5 in componentsInChildren)
				{
					if ((Object)(object)((Component)val5).GetComponent<PenGateHandle>() == (Object)null)
					{
						((Component)val5).gameObject.AddComponent<PenGateHandle>();
					}
				}
			}
			Dictionary<Material, Material> dictionary = new Dictionary<Material, Material>();
			Renderer[] componentsInChildren2 = val.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val6 in componentsInChildren2)
			{
				Material[] sharedMaterials = val6.sharedMaterials;
				bool flag = false;
				for (int l = 0; l < sharedMaterials.Length; l++)
				{
					Material val7 = sharedMaterials[l];
					if ((Object)(object)val7 == (Object)null)
					{
						continue;
					}
					if (!dictionary.TryGetValue(val7, out var value))
					{
						value = new Material(val7)
						{
							name = ((Object)val7).name + "_" + ((Object)clone).name
						};
						value.DisableKeyword("_VALUENOISEVERTEX_ON");
						value.EnableKeyword("_MOVEABLEOBJECT_ON");
						(string, float)[] array5 = new(string, float)[4]
						{
							("_ValueNoiseVertex", 0f),
							("_ValueNoise", 0f),
							("_RippleDistance", 0f),
							("_MoveableObject", 1f)
						};
						for (int j = 0; j < array5.Length; j++)
						{
							var (text, num23) = array5[j];
							if (value.HasProperty(text))
							{
								value.SetFloat(text, num23);
							}
						}
						dictionary[val7] = value;
					}
					sharedMaterials[l] = value;
					flag = true;
				}
				if (flag)
				{
					val6.sharedMaterials = sharedMaterials;
				}
			}
			int num24 = LayerMask.NameToLayer("vehicle");
			if (num24 >= 0)
			{
				Transform[] componentsInChildren3 = val.GetComponentsInChildren<Transform>(true);
				for (int i = 0; i < componentsInChildren3.Length; i++)
				{
					((Component)componentsInChildren3[i]).gameObject.layer = num24;
				}
			}
			Logger.LogInfo((object)$"[TheGreatestShips] Built animal pen: {num3} posts and rails (a {num8:0.0} m gate each side) plus a flat inner wall to {num5:0.00}, {spec.Width} x {spec.Length} at z {spec.CenterZ}; the same pieces would cost {num4} Wood.");
		}

		private static (int long2, int short1) PlaceRail(Transform parent, GameObject beam2, GameObject beam1, Vector3 center, float yaw, float length)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//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_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			Quaternion val = Quaternion.Euler(0f, yaw, 0f);
			float num = (0f - length) / 2f;
			int num2 = 0;
			int num3 = 0;
			while (length - (num + length / 2f) >= 1.99f)
			{
				Place(beam2, parent, center + val * new Vector3(num + 1f, 0f, 0f), val);
				num += 2f;
				num2++;
			}
			float num4 = length - (num + length / 2f);
			if (num4 > 0.01f)
			{
				Place(beam1, parent, center + val * new Vector3(num + num4 / 2f, 0f, 0f), val).transform.localScale = new Vector3(num4, 1f, 1f);
				num3++;
			}
			return (long2: num2, short1: num3);
		}

		private static void Wall(Transform parent, Vector3 localPosition, Vector3 size, int layer)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("pen_wall")
			{
				layer = layer
			};
			val.transform.SetParent(parent, false);
			val.transform.localPosition = localPosition;
			val.AddComponent<BoxCollider>().size = size;
		}

		private static GameObject Place(GameObject prefab, Transform parent, Vector3 localPosition, Quaternion localRotation)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = Object.Instantiate<GameObject>(prefab, parent);
			obj.transform.localPosition = localPosition;
			obj.transform.localRotation = localRotation;
			StripToGeometry(obj);
			return obj;
		}

		private static void StripToGeometry(GameObject piece)
		{
			List<MonoBehaviour> list = new List<MonoBehaviour>(piece.GetComponentsInChildren<MonoBehaviour>(true));
			list.Sort((MonoBehaviour a, MonoBehaviour b) => ((a is ZNetView) ? 1 : 0) - ((b is ZNetView) ? 1 : 0));
			foreach (MonoBehaviour item in list)
			{
				if ((Object)(object)item != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)item);
				}
			}
		}
	}
	internal sealed class PenLip : MonoBehaviour
	{
		private const float DriftSpeed = 1f;

		private Ship _ship;

		private Rigidbody _body;

		private Collider[] _lips;

		private float _next;

		private bool _on;

		private void Start()
		{
			_ship = ((Component)this).GetComponentInParent<Ship>();
			_body = ((Component)this).GetComponentInParent<Rigidbody>();
			List<Collider> list = new List<Collider>();
			Collider[] componentsInChildren = ((Component)this).GetComponentsInChildren<Collider>(true);
			foreach (Collider val in componentsInChildren)
			{
				if (((Object)val).name == "pen_lip")
				{
					list.Add(val);
				}
			}
			_lips = list.ToArray();
		}

		private void Update()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_ship == (Object)null || _lips == null || Time.time < _next)
			{
				return;
			}
			_next = Time.time + 0.25f;
			int num;
			if ((int)_ship.GetSpeedSetting() == 0)
			{
				if ((Object)(object)_body != (Object)null)
				{
					Vector3 linearVelocity = _body.linearVelocity;
					num = ((((Vector3)(ref linearVelocity)).magnitude > 1f) ? 1 : 0);
				}
				else
				{
					num = 0;
				}
			}
			else
			{
				num = 1;
			}
			bool flag = (byte)num != 0;
			if (flag != _on)
			{
				_on = flag;
				Collider[] lips = _lips;
				for (int i = 0; i < lips.Length; i++)
				{
					lips[i].enabled = flag;
				}
			}
		}
	}
	internal sealed class PenBallast : MonoBehaviour
	{
		private void Start()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			Rigidbody componentInParent = ((Component)this).GetComponentInParent<Rigidbody>();
			if (!((Object)(object)componentInParent == (Object)null))
			{
				Collider[] componentsInChildren = ((Component)this).GetComponentsInChildren<Collider>(true);
				bool[] array = new bool[componentsInChildren.Length];
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					array[i] = componentsInChildren[i].enabled;
					componentsInChildren[i].enabled = false;
				}
				componentInParent.ResetCenterOfMass();
				componentInParent.ResetInertiaTensor();
				Vector3 centerOfMass = componentInParent.centerOfMass;
				Vector3 inertiaTensor = componentInParent.inertiaTensor;
				Quaternion inertiaTensorRotation = componentInParent.inertiaTensorRotation;
				for (int j = 0; j < componentsInChildren.Length; j++)
				{
					componentsInChildren[j].enabled = array[j];
				}
				componentInParent.centerOfMass = centerOfMass;
				componentInParent.inertiaTensor = inertiaTensor;
				componentInParent.inertiaTensorRotation = inertiaTensorRotation;
			}
		}
	}
	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	internal static class ObjectDBAwakePatch
	{
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void Postfix()
		{
			ShipPrefabs.OnObjectDBAwake();
		}
	}
	[HarmonyPatch(typeof(ZNetScene), "Awake")]
	internal static class ZNetSceneAwakePatch
	{
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void Postfix()
		{
			ShipPrefabs.OnZNetSceneAwake();
		}
	}
	[HarmonyPatch(typeof(Hud), "SetupPieceInfo")]
	internal static class HudSetupPieceInfoPatch
	{
		private static bool _logged;

		[HarmonyPrefix]
		private static void Prefix(Hud __instance, Piece piece)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			GameObject[] requirementItems = __instance.m_requirementItems;
			if ((Object)(object)piece == (Object)null || piece.m_resources == null || requirementItems == null || requirementItems.Length == 0)
			{
				return;
			}
			int num = piece.m_resources.Length + 1;
			if (num <= requirementItems.Length)
			{
				return;
			}
			List<GameObject> list = new List<GameObject>(requirementItems);
			Vector2 val = Vector2.zero;
			if (requirementItems.Length >= 2)
			{
				RectTransform component = requirementItems[^2].GetComponent<RectTransform>();
				RectTransform component2 = requirementItems[^1].GetComponent<RectTransform>();
				if ((Object)(object)component != (Object)null && (Object)(object)component2 != (Object)null)
				{
					val = component2.anchoredPosition - component.anchoredPosition;
				}
			}
			while (list.Count < num)
			{
				GameObject val2 = list[list.Count - 1];
				GameObject val3 = Object.Instantiate<GameObject>(val2, val2.transform.parent);
				((Object)val3).name = ((Object)val2).name;
				val3.transform.SetSiblingIndex(val2.transform.GetSiblingIndex() + 1);
				RectTransform component3 = val3.GetComponent<RectTransform>();
				if ((Object)(object)component3 != (Object)null)
				{
					component3.anchoredPosition += val;
				}
				list.Add(val3);
			}
			__instance.m_requirementItems = list.ToArray();
			if (!_logged)
			{
				_logged = true;
				Logger.LogInfo((object)$"[TheGreatestShips] Build HUD had {requirementItems.Length} requirement slots; grew it to {list.Count} for {piece.m_name}.");
			}
		}
	}
	[HarmonyPatch(typeof(Container), "Load")]
	internal static class ContainerLoadFitPatch
	{
		private static readonly HashSet<string> _ourShips = new HashSet<string>(ShipDefinitions.All.Select((ShipDefinition d) => d.PrefabName));

		[HarmonyPostfix]
		private static void Postfix(Container __instance, bool __result)
		{
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			if (!__result || (Object)(object)__instance == (Object)null || !__instance.IsOwner() || !_ourShips.Contains(Utils.GetPrefabName(((Component)((Component)__instance).transform.root).gameObject)))
			{
				return;
			}
			Inventory inventory = __instance.GetInventory();
			if (inventory == null)
			{
				return;
			}
			int width = inventory.GetWidth();
			int height = inventory.GetHeight();
			int num = 0;
			foreach (ItemData item in new List<ItemData>(inventory.GetAllItems()))
			{
				if (item.m_gridPos.x >= width || item.m_gridPos.y >= height)
				{
					Vector2i val = inventory.FindEmptySlot(true);
					if (val.x < 0)
					{
						break;
					}
					item.m_gridPos = val;
					num++;
				}
			}
			if (num > 0)
			{
				inventory.Changed(false, false);
				Logger.LogInfo((object)$"[TheGreatestShips] {__instance.m_name}: moved {num} stack(s) that sat outside the hold's grid into free slots.");
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGrid), "UpdateGui")]
	internal static class InventoryGridFitPatch
	{
		private static readonly FieldRef<InventoryGrid, List<InventoryElement>> _elements = AccessTools.FieldRefAccess<InventoryGrid, List<InventoryElement>>("m_elements");

		private static readonly FieldRef<InventoryGrid, int> _width = AccessTools.FieldRefAccess<InventoryGrid, int>("m_width");

		private static readonly FieldRef<InventoryGrid, int> _height = AccessTools.FieldRefAccess<InventoryGrid, int>("m_height");

		private static readonly FieldRef<InventoryGrid, float> _space = AccessTools.FieldRefAccess<InventoryGrid, float>("m_elementSpace");

		[HarmonyPostfix]
		private static void Postfix(InventoryGrid __instance)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: 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_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			List<InventoryElement> list = _elements.Invoke(__instance);
			if (list == null || list.Count == 0)
			{
				return;
			}
			int num = _width.Invoke(__instance);
			int num2 = _height.Invoke(__instance);
			if (num <= 0 || num2 <= 0)
			{
				return;
			}
			Transform transform = ((Component)__instance).transform;
			RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			float num3 = _space.Invoke(__instance);
			float num4 = (float)num * num3;
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Rect rect = val.rect;
			if (((Rect)(ref rect)).width <= 0f)
			{
				return;
			}
			rect = val.rect;
			if (num4 <= ((Rect)(ref rect)).width)
			{
				return;
			}
			rect = val.rect;
			float num5 = ((Rect)(ref rect)).width / num4;
			Transform transform2 = ((Component)list[0]).transform;
			RectTransform val2 = (RectTransform)(object)((transform2 is RectTransform) ? transform2 : null);
			if ((Object)(object)val2 == (Object)null || Mathf.Approximately(((Transform)val2).localScale.x, num5))
			{
				return;
			}
			rect = val.rect;
			float num6 = ((Rect)(ref rect)).width / 2f - num4 * num5 / 2f;
			for (int i = 0; i < list.Count; i++)
			{
				Transform transform3 = ((Component)list[i]).transform;
				RectTransform val3 = (RectTransform)(object)((transform3 is RectTransform) ? transform3 : null);
				if (!((Object)(object)val3 == (Object)null))
				{
					int num7 = i % num;
					int num8 = i / num;
					((Transform)val3).localScale = new Vector3(num5, num5, 1f);
					val3.anchoredPosition = new Vector2(num6 + (float)num7 * num3 * num5, (float)(-num8) * num3 * num5);
				}
			}
			Logger.LogInfo((object)$"[TheGreatestShips] Inventory grid {num}x{num2} is wider than its panel; slots drawn at {num5:0.00} scale to fit.");
		}
	}
	[HarmonyPatch(typeof(ImpactEffect), "OnCollisionEnter")]
	internal static class ImpactEffectSparesLivestockPatch
	{
		private static readonly HashSet<string> _ourShips = new HashSet<string>(ShipDefinitions.All.Select((ShipDefinition d) => d.PrefabName));

		[HarmonyPrefix]
		private static bool Prefix(ImpactEffect __instance, Collision info)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (info == null || info.contactCount == 0)
			{
				return true;
			}
			string text = ((Object)__instance).name;
			int num = text.IndexOf('(');
			if (num > 0)
			{
				text = text.Substring(0, num).Trim();
			}
			if (!_ourShips.Contains(text))
			{
				return true;
			}
			ContactPoint contact = info.GetContact(0);
			Collider otherCollider = ((ContactPoint)(ref contact)).otherCollider;
			GameObject val = (((Object)(object)otherCollider != (Object)null) ? Projectile.FindHitObject(otherCollider) : null);
			Character val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<Character>() : null);
			if (!((Object)(object)val2 == (Object)null))
			{
				return !val2.IsTamed();
			}
			return true;
		}
	}
	internal sealed class PenGate : MonoBehaviour, Hoverable, Interactable
	{
		private const float SwingAngle = 65f;

		private const float SwingSpeed = 120f;

		public bool Port;

		private ZNetView _nview;

		private bool _open;

		private float _next;

		private string ZdoKey
		{
			get
			{
				if (!Port)
				{
					return "DM_PenGateOpen";
				}
				return "DM_PenGateOpenPort";
			}
		}

		private string RpcName
		{
			get
			{
				if (!Port)
				{
					return "DM_PenGate";
				}
				return "DM_PenGatePort";
			}
		}

		private float OpenAngle
		{
			get
			{
				if (!Port)
				{
					return -65f;
				}
				return 65f;
			}
		}

		private void Start()
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			_nview = ((Component)this).GetComponentInParent<ZNetView>();
			if ((Object)(object)_nview == (Object)null || !_nview.IsValid())
			{
				_nview = null;
				return;
			}
			try
			{
				_nview.Register<bool>(RpcName, (Action<long, bool>)RPC_SetOpen);
			}
			catch (ArgumentException)
			{
			}
			_open = _nview.GetZDO().GetBool(ZdoKey, false);
			((Component)this).transform.localRotation = Target();
		}

		private void RPC_SetOpen(long sender, bool open)
		{
			if ((Object)(object)_nview != (Object)null && _nview.IsValid() && _nview.IsOwner())
			{
				_nview.GetZDO().Set(ZdoKey, open);
			}
		}

		private void Update()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_nview == (Object)null) && _nview.IsValid())
			{
				if (Time.time >= _next)
				{
					_next = Time.time + 0.25f;
					_open = _nview.GetZDO().GetBool(ZdoKey, false);
				}
				Quaternion val = Target();
				if (((Component)this).transform.localRotation != val)
				{
					((Component)this).transform.localRotation = Quaternion.RotateTowards(((Component)this).transform.localRotation, val, 120f * Time.deltaTime);
				}
			}
		}

		private Quaternion Target()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			return Quaternion.Euler(0f, 0f, _open ? OpenAngle : 0f);
		}

		public string GetHoverText()
		{
			return Localization.instance.Localize("Pen gate\n[<color=yellow><b>$KEY_Use</b></color>] " + (_open ? "Close" : "Open"));
		}

		public string GetHoverName()
		{
			return "Pen gate";
		}

		public float GetHoverOffset()
		{
			return 0f;
		}

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			if (hold || (Object)(object)_nview == (Object)null || !_nview.IsValid())
			{
				return false;
			}
			bool flag = !_nview.GetZDO().GetBool(ZdoKey, false);
			if (_nview.IsOwner())
			{
				_nview.GetZDO().Set(ZdoKey, flag);
			}
			else
			{
				_nview.InvokeRPC(RpcName, new object[1] { flag });
			}
			_next = 0f;
			return true;
		}

		public bool UseItem(Humanoid user, ItemData item)
		{
			return false;
		}
	}
	internal sealed class PenGateHandle : MonoBehaviour, Hoverable, Interactable
	{
		private PenGate _gate;

		private PenGate Gate
		{
			get
			{
				if (!((Object)(object)_gate != (Object)null))
				{
					return _gate = ((Component)this).GetComponentInParent<PenGate>();
				}
				return _gate;
			}
		}

		public string GetHoverText()
		{
			if (!((Object)(object)Gate != (Object)null))
			{
				return "";
			}
			return Gate.GetHoverText();
		}

		public string GetHoverName()
		{
			if (!((Object)(object)Gate != (Object)null))
			{
				return "";
			}
			return Gate.GetHoverName();
		}

		public float GetHoverOffset()
		{
			return 0f;
		}

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			if ((Object)(object)Gate != (Object)null)
			{
				return Gate.Interact(user, hold, alt);
			}
			return false;
		}

		public bool UseItem(Humanoid user, ItemData item)
		{
			return false;
		}
	}
	internal static class ShipConfig
	{
		internal sealed class Entries
		{
			public ConfigEntry<string> Recipe;

			public ConfigEntry<float> Speed;

			public ConfigEntry<float> Health;

			public ConfigEntry<float> RudderSpeed;

			public ConfigEntry<Color> SailColor;

			public ConfigEntry<Color> HullColor;

			public ConfigEntry<int> HullStripes;

			public ConfigEntry<float> Width;

			public ConfigEntry<float> Length;

			public ConfigEntry<float> Scale;
		}

		private static readonly Dictionary<ShipDefinition, Entries> _entries = new Dictionary<ShipDefinition, Entries>();

		internal static ConfigEntry<bool> NameVanillaShips;

		internal static ConfigEntry<bool> LockConfiguration;

		private const int CurrentConfigVersion = 20;

		internal static Entries For(ShipDefinition def)
		{
			return _entries[def];
		}

		internal static void Bind(TheGreatestShipsMod mod)
		{
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			ConfigEntry<int> val = ((BaseUnityPlugin)mod).Config.Bind<int>("General", "Config Version", 1, "Used by the mod to update old defaults. Do not change.");
			LockConfiguration = mod.BindLocking("General", "Lock Configuration", defaultValue: true, "While on, the settings marked as synced can be changed only by the server's admins (adminlist.txt), from their game; everyone else sees them read-only. Off, any player can change them for the whole server.");
			NameVanillaShips = ((BaseUnityPlugin)mod).Config.Bind<bool>("General", "Name Vanilla Ships", true, "Label the vanilla ships' rudders and holds with the ship's name (\"Use rudder (Karve)\", \"Longship Storage\"), as this mod's own ships are, so you can tell which ship you are looking at. Requires a game restart.");
			ShipDefinition[] all = ShipDefinitions.All;
			foreach (ShipDefinition shipDefinition in all)
			{
				string displayName = shipDefinition.DisplayName;
				Entries entries = new Entries();
				entries.Recipe = mod.BindSynced(displayName, "Recipe", Migrated(mod, shipDefinition, "Recipe", shipDefinition.DefaultRecipe), "Comma-separated ItemName:Amount pairs (prefab names). Everything is returned when the ship is deconstructed, as with the vanilla ships.");
				float num = shipDefinition.BaseTopSpeed * shipDefinition.DefaultSpeed;
				entries.Speed = mod.BindSynced(displayName, "Top Speed Multiplier", Migrated(mod, shipDefinition, "Top Speed Multiplier", shipDefinition.DefaultSpeed), $"Top speed relative to the vanilla {shipDefinition.BaseName} ({shipDefinition.BaseTopSpeed} in full wind). " + $"{shipDefinition.DefaultSpeed} makes it about {num:0.#}. Acceleration under sail changes with it.");
				entries.Health = mod.BindSynced(displayName, "Health", Migrated(mod, shipDefinition, "Health", shipDefinition.DefaultHealth), string.Format("Hull health (the vanilla {0} has {1}). ", shipDefinition.BaseName, (shipDefinition.BasePrefab == "Karve") ? 500 : 1000) + "Ships already built keep their damage; this is the maximum.");
				entries.RudderSpeed = mod.BindSynced(displayName, "Rudder Speed", Migrated(mod, shipDefinition, "Rudder Speed", shipDefinition.DefaultRudderSpeed), "How quickly the rudder swings (the vanilla " + shipDefinition.BaseName + " has 1). Lower turns more slowly.");
				entries.SailColor = ((BaseUnityPlugin)mod).Config.Bind<Color>(displayName, "Sail Color", Migrated<Color>(mod, shipDefinition, "Sail Color", shipDefinition.DefaultSailColor), "Tint multiplied into the sail so the " + shipDefinition.DisplayName + " can be told apart from a " + shipDefinition.BaseName + ". White leaves the sail as it is. Requires a game restart.");
				entries.HullColor = ((BaseUnityPlugin)mod).Config.Bind<Color>(displayName, "Hull Color", Migrated<Color>(mod, shipDefinition, "Hull Color", shipDefinition.DefaultHullColor), "Paint multiplied into the hull planks (not the mast or rudder). White leaves the wood as it is. Requires a game restart.");
				entries.HullStripes = ((BaseUnityPlugin)mod).Config.Bind<int>(displayName, "Hull Stripes", Migrated(mod, shipDefinition, "Hull Stripes", shipDefinition.DefaultHullStripes), "Paint the hull color in this many bands with bare wood between them. 0 paints the hull solid. The bands follow the hull texture's layout. Requires a game restart.");
				entries.Width = mod.BindSynced(displayName, "Hull Width", Migrated(mod, shipDefinition, "Hull Width", shipDefinition.DefaultWidth), "Width relative to the vanilla " + shipDefinition.BaseName + "; below 1 is narrower, above 1 wider.");
				entries.Length = mod.BindSynced(displayName, "Hull Length", Migrated(mod, shipDefinition, "Hull Length", shipDefinition.DefaultLength), "Bow-to-stern length relative to the vanilla " + shipDefinition.BaseName + "; below 1 is shorter, above 1 longer.");
				entries.Scale = mod.BindSynced(displayName, "Hull Scale", Migrated(mod, shipDefinition, "Hull Scale", shipDefinition.DefaultScale), "Size of the whole ship, all three dimensions, relative to the vanilla " + shipDefinition.BaseName + ". Width and Length multiply on top of it.");
				ShipDefinition captured = shipDefinition;
				entries.Recipe.SettingChanged += delegate
				{
					ShipPrefabs.ApplyRecipe(captured);
				};
				entries.Speed.SettingChanged += delegate
				{
					ShipPrefabs.ApplyHandling(captured);
				};
				entries.Health.SettingChanged += delegate
				{
					ShipPrefabs.ApplyHandling(captured);
				};
				entries.RudderSpeed.SettingChanged += delegate
				{
					ShipPrefabs.ApplyHandling(captured);
				};
				entries.Width.SettingChanged += delegate
				{
					ShipPrefabs.ApplyDimensions(captured);
				};
				entries.Length.SettingChanged += delegate
				{
					ShipPrefabs.ApplyDimensions(captured);
				};
				entries.Scale.SettingChanged += delegate
				{
					ShipPrefabs.ApplyDimensions(captured);
				};
				if (val.Value < 20)
				{
					Migrate(shipDefinition, entries);
				}
				_entries[shipDefinition] = entries;
			}
			if (val.Value < 20)
			{
				val.Value = 20;
			}
		}

		private static T Migrated<T>(TheGreatestShipsMod mod, ShipDefinition def, string key, T fallback)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			if (def.OldDisplayNames == null)
			{
				return fallback;
			}
			string text = TomlTypeConverter.ConvertToString((object)fallback, typeof(T));
			T result = fallback;
			bool flag = false;
			string[] oldDisplayNames = def.OldDisplayNames;
			for (int i = 0; i < oldDisplayNames.Length; i++)
			{
				ConfigDefinition val = new ConfigDefinition(oldDisplayNames[i], key);
				ConfigEntry<T> val2 = ((BaseUnityPlugin)mod).Config.Bind<T>(val, fallback, (ConfigDescription)null);
				if (!flag && ((ConfigEntryBase)val2).GetSerializedValue() != text)
				{
					result = val2.Value;
					flag = true;
				}
				((BaseUnityPlugin)mod).Config.Remove(val);
			}
			return result;
		}

		private static void Migrate(ShipDefinition def, Entries e)
		{
			if (!float.IsNaN(def.OldDefaultSpeed) && Mathf.Approximately(e.Speed.Value, def.OldDefaultSpeed))
			{
				e.Speed.Value = def.DefaultSpeed;
				Logger.LogInfo((object)$"[TheGreatestShips] {def.DisplayName}: Top Speed Multiplier {def.OldDefaultSpeed} -> {def.DefaultSpeed} (new default).");
			}
			if (def.OldDefaultRecipes != null && Array.IndexOf(def.OldDefaultRecipes, e.Recipe.Value) >= 0)
			{
				e.Recipe.Value = def.DefaultRecipe;
				Logger.LogInfo((object)("[TheGreatestShips] " + def.DisplayName + ": recipe updated to the new default."));
			}
			MigrateFloat(def, "Health", e.Health, def.OldDefaultHealths, def.DefaultHealth);
			MigrateFloat(def, "Hull Width", e.Width, def.OldDefaultWidths, def.DefaultWidth);
			MigrateFloat(def, "Hull Length", e.Length, def.OldDefaultLengths, def.DefaultLength);
		}

		private static void MigrateFloat(ShipDefinition def, string key, ConfigEntry<float> entry, float[] oldDefaults, float current)
		{
			if (oldDefaults == null)
			{
				return;
			}
			foreach (float num in oldDefaults)
			{
				if (Mathf.Approximately(entry.Value, num))
				{
					entry.Value = current;
					Logger.LogInfo((object)$"[TheGreatestShips] {def.DisplayName}: {key} {num} -> {current} (new default).");
					break;
				}
			}
		}

		internal static Requirement[] ParseRecipe(string recipe, string owner)
		{
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			List<Requirement> list = new List<Requirement>();
			string[] array = recipe.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Trim().Split(new char[1] { ':' });
				if (array2.Length < 2)
				{
					continue;
				}
				string text = array2[0].Trim();
				if (int.TryParse(array2[1].Trim(), out var result) && result > 0)
				{
					ObjectDB instance = ObjectDB.instance;
					object obj;
					if (instance == null)
					{
						obj = null;
					}
					else
					{
						GameObject itemPrefab = instance.GetItemPrefab(text);
						obj = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
					}
					ItemDrop val = (ItemDrop)obj;
					if ((Object)(object)val == (Object)null)
					{
						Logger.LogWarning((object)("[TheGreatestShips] " + owner + ": '" + text + "' not found in ObjectDB, skipped."));
					}
					else
					{
						list.Add(new Requirement
						{
							m_resItem = val,
							m_amount = result,
							m_recover = true
						});
					}
				}
			}
			return list.ToArray();
		}
	}
	internal sealed class ShipDefinition
	{
		public string PrefabName;

		public string BasePrefab;

		public string BaseName;

		public float BaseTopSpeed;

		public string DisplayName;

		public string Description;

		public string[] OldDisplayNames;

		public int StorageWidth;

		public int StorageHeight;

		public string DefaultRecipe;

		public float DefaultSpeed;

		public float DefaultHealth;

		public float DefaultRudderSpeed;

		public Color DefaultSailColor;

		public Color DefaultHullColor;

		public int DefaultHullStripes;

		public float DefaultWidth;

		public float DefaultLength = 1f;

		public float DefaultScale = 1f;

		public PenSpec Pen;

		public float OldDefaultSpeed = float.NaN;

		public string[] OldDefaultRecipes;

		public float[] OldDefaultHealths;

		public float[] OldDefaultWidths;

		public float[] OldDefaultLengths;
	}
	internal static class ShipDefinitions
	{
		private static readonly Color Blue = new Color(0.375f, 0.55f, 0.875f, 1f);

		private static readonly Color Amber = new Color(1f, 0.8f, 0.5f, 1f);

		private static readonly Color Red = new Color(1f, 0.62f, 0.55f, 1f);

		private static readonly Color Green = new Color(0.6f, 0.85f, 0.6f, 1f);

		private static readonly Color Brown = new Color(0.55f, 0.4f, 0.3f, 1f);

		public static readonly ShipDefinition[] All = new ShipDefinition[8]
		{
			new ShipDefinition
			{
				PrefabName = "DM_FastKarve",
				BasePrefab = "Karve",
				BaseName = "Karve",
				BaseTopSpeed = 7.3f,
				DisplayName = "Fast Karve",
				Description = "A light racing karve with an oversized sail. Faster than a longship, with room for little more than a spare cloak.",
				StorageWidth = 2,
				StorageHeight = 1,
				DefaultRecipe = "FineWood:30,ElderBark:20,BronzeNails:60,TrollHide:8,Resin:20",
				DefaultSpeed = 1.37f,
				OldDefaultSpeed = 1.14f,
				DefaultHealth = 400f,
				DefaultRudderSpeed = 1f,
				DefaultSailColor = Blue,
				DefaultHullColor = Red,
				DefaultHullStripes = 6,
				DefaultWidth = 0.85f
			},
			new ShipDefinition
			{
				PrefabName = "DM_FastLongship",
				BasePrefab = "VikingShip",
				BaseName = "Longship",
				BaseTopSpeed = 9.65f,
				DisplayName = "Fast Longship",
				Description = "A long, lean longship under an oversized sail, braced with troll hide and extra iron and sealed with swamp guck: the fastest hull on the water. Two thirds of a longship's hold, and a lighter one.",
				StorageWidth = 4,
				StorageHeight = 3,
				DefaultRecipe = "FineWood:40,ElderBark:40,IronNails:120,DeerHide:10,TrollHide:10",
				OldDefaultRecipes = new string[2] { "FineWood:40,ElderBark:40,IronNails:120,DeerHide:10,TrollHide:10,Guck:10", "FineWood:40,ElderBark:40,IronNails:100,LinenThread:20,Resin:30" },
				DefaultSpeed = 1.342f,
				OldDefaultSpeed = 1.28f,
				DefaultHealth = 800f,
				DefaultRudderSpeed = 1f,
				DefaultSailColor = Blue,
				DefaultHullColor = Red,
				DefaultHullStripes = 6,
				DefaultWidth = 0.85f,
				DefaultLength = 1.1f
			},
			new ShipDefinition
			{
				PrefabName = "DM_CargoLongship",
				BasePrefab = "VikingShip",
				BaseName = "Longship",
				BaseTopSpeed = 9.65f,
				DisplayName = "Knarr",
				OldDisplayNames = new string[1] { "Cargo Longship" },
				Description = "A deep, heavy longship built to haul. Slower and clumsier than a longship, but sturdier, with nearly twice its hold. The smallest of three cargo tiers -- see also the Busse and the Big Busse.",
				StorageWidth = 8,
				StorageHeight = 4,
				DefaultRecipe = "FineWood:40,ElderBark:50,IronNails:120,DeerHide:10,TrollHide:10",
				OldDefaultRecipes = new string[7] { "FineWood:40,ElderBark:30,IronNails:120,DeerHide:10,TrollHide:10,RoundLog:20", "FineWood:40,ElderBark:40,IronNails:140,DeerHide:10,TrollHide:10,RoundLog:20", "FineWood:40,ElderBark:60,IronNails:180,DeerHide:10,TrollHide:10,RoundLog:30", "FineWood:40,ElderBark:60,IronNails:180,TrollHide:10,RoundLog:30", "FineWood:40,ElderBark:60,IronNails:180,DeerHide:10,RoundLog:30", "FineWood:40,ElderBark:60,IronNails:180,DeerHide:10,RoundLog:30,Chain:2", "FineWood:40,ElderBark:60,IronNails:150,DeerHide:10,RoundLog:30" },
				DefaultSpeed = 0.87f,
				DefaultHealth = 1100f,
				OldDefaultHealths = new float[1] { 1500f },
				DefaultRudderSpeed = 0.8f,
				DefaultSailColor = Amber,
				DefaultHullColor = Green,
				DefaultHullStripes = 6,
				DefaultWidth = 1.25f
			},
			new ShipDefinition
			{
				PrefabName = "DM_Busse",
				BasePrefab = "VikingShip",
				BaseName = "Longship",
				BaseTopSpeed = 9.65f,
				DisplayName = "Busse",
				Description = "A longship built out further than the Knarr. Slower still and even clumsier, but holds half again as much and shrugs off more damage.",
				StorageWidth = 8,
				StorageHeight = 6,
				DefaultRecipe = "FineWood:50,ElderBark:70,IronNails:150,DeerHide:15,TrollHide:15",
				OldDefaultRecipes = new string[9] { "FineWood:50,ElderBark:60,IronNails:140,DeerHide:15,TrollHide:15", "FineWood:50,ElderBark:30,IronNails:140,DeerHide:15,TrollHide:15,RoundLog:30", "FineWood:50,ElderBark:40,IronNails:160,DeerHide:15,Tro