Decompiled source of SwappableStaysail v1.2.4

BepInEx/plugins/SwappableStaysail/SwappableStaysail.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;
using cakeslice;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("SwappableStaysail")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.4.0")]
[assembly: AssemblyInformationalVersion("1.2.4")]
[assembly: AssemblyProduct("SwappableStaysail")]
[assembly: AssemblyTitle("SwappableStaysail")]
[assembly: AssemblyVersion("1.2.4.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SwappableStaysail
{
	[BepInPlugin("DogEggz", "Swappable Staysail", "1.2.4")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class SwappableStaysailPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "DogEggz";

		public const string PluginName = "Swappable Staysail";

		public const string PluginVersion = "1.2.4";

		public const string ShipyardExpansionGuid = "com.nandbrew.shipyardexpansion";

		internal const string SaveDataKey = "DogEggz";

		private Harmony harmony;

		internal static SwappableStaysailPlugin Instance { get; private set; }

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			harmony = new Harmony("DogEggz");
			harmony.PatchAll();
			SailDamageBridge.Initialize(harmony);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Swappable Staysail 1.2.4 loaded. Sail package prefab indexes: legacy=" + $"{390}, standard=" + $"{600}, small=" + $"{601}."));
		}

		private void OnDestroy()
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			SailmakerSession.Dispose();
			StayInstallTargeting.Dispose();
			FurledStaysailButton.DisposeAll();
			SailpackFactory.Dispose();
			SailpackPersistence.Dispose();
			SailDamageBridge.Dispose();
			Instance = null;
			Log = null;
		}
	}
	internal static class SailDamageBridge
	{
		internal const string SailDamageGuid = "kap.saildamage";

		internal const ButtonFunction PatchSailsFunction = (ButtonFunction)1000;

		private static FieldInfo damageModelInstance;

		private static MethodInfo snapshotMethod;

		private static MethodInfo restoreMethod;

		private static MethodInfo saveKeyMethod;

		private static FieldInfo patchSailsOrdered;

		private static readonly Dictionary<Sail, string> HoleKeys = new Dictionary<Sail, string>();

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

		private static readonly ConditionalWeakTable<SaveSailData, string> RebuildKeys = new ConditionalWeakTable<SaveSailData, string>();

		private static Sail drawingSail;

		private static bool DamageAvailable
		{
			get
			{
				if (damageModelInstance != null && snapshotMethod != null)
				{
					return restoreMethod != null;
				}
				return false;
			}
		}

		private static bool HoleKeysAvailable { get; set; }

		internal static void Initialize(Harmony harmony)
		{
			if (!Chainloader.PluginInfos.TryGetValue("kap.saildamage", out var value) || (Object)(object)((value != null) ? value.Instance : null) == (Object)null)
			{
				return;
			}
			Assembly assembly = ((object)value.Instance).GetType().Assembly;
			Type type = assembly.GetType("SailDamage.DamageModel");
			Type type2 = assembly.GetType("SailDamage.ShipyardRepair");
			Type type3 = assembly.GetType("SailDamage.SailVisuals");
			Type type4 = ((type3 != null) ? AccessTools.Inner(type3, "Holes") : null);
			if (type != null)
			{
				damageModelInstance = AccessTools.Field(type, "Instance");
				snapshotMethod = AccessTools.Method(type, "Snapshot", new Type[1] { typeof(Sail) }, (Type[])null);
				restoreMethod = AccessTools.Method(type, "Restore", new Type[2]
				{
					typeof(Sail),
					typeof(float[])
				}, (Type[])null);
				saveKeyMethod = AccessTools.Method(type, "SaveKey", new Type[1] { typeof(Sail) }, (Type[])null);
			}
			if (type2 != null)
			{
				patchSailsOrdered = AccessTools.Field(type2, "Ordered");
			}
			ConstructorInfo constructorInfo = ((type4 == null) ? null : AccessTools.GetDeclaredConstructors(type4, (bool?)null).FirstOrDefault(delegate(ConstructorInfo constructor)
			{
				ParameterInfo[] parameters = constructor.GetParameters();
				return parameters.Length != 0 && parameters[0].ParameterType == typeof(Sail);
			}));
			if (saveKeyMethod != null && constructorInfo != null)
			{
				try
				{
					harmony.Patch((MethodBase)constructorInfo, Hook("HolesPrefix"), (HarmonyMethod)null, (HarmonyMethod)null, Hook("HolesFinalizer"), (HarmonyMethod)null);
					harmony.Patch((MethodBase)saveKeyMethod, (HarmonyMethod)null, Hook("SaveKeyPostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					harmony.Patch((MethodBase)AccessTools.Method(typeof(SaveableBoatCustomization), "GetData", (Type[])null, (Type[])null), (HarmonyMethod)null, Hook("RebuildRecordPostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					harmony.Patch((MethodBase)AccessTools.Method(typeof(Mast), "LoadSail", (Type[])null, (Type[])null), Hook("LoadSailPrefix"), Hook("LoadSailPostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					HoleKeysAvailable = true;
				}
				catch (Exception arg)
				{
					ManualLogSource log = SwappableStaysailPlugin.Log;
					if (log != null)
					{
						log.LogWarning((object)("Sail Damage found, but its hole positions cannot be kept " + $"for packed staysails: {arg}"));
					}
				}
			}
			ManualLogSource log2 = SwappableStaysailPlugin.Log;
			if (log2 != null)
			{
				log2.LogInfo((object)($"Sail Damage {value.Metadata.Version} found: packed staysails keep " + "damage " + (DamageAvailable ? "on" : "OFF") + ", hole positions " + (HoleKeysAvailable ? "on" : "OFF") + ", Patch Sails guard " + ((patchSailsOrdered != null) ? "on" : "OFF") + "."));
			}
		}

		internal static void Dispose()
		{
			HoleKeys.Clear();
			PendingHoleKeys.Clear();
			drawingSail = null;
		}

		internal static bool PatchSailsOrdered()
		{
			try
			{
				return patchSailsOrdered != null && (bool)patchSailsOrdered.GetValue(null);
			}
			catch (Exception)
			{
				return false;
			}
		}

		internal static void CaptureDamage(Sail sail, SailpackRecord record)
		{
			if (!DamageAvailable || (Object)(object)sail == (Object)null || record == null)
			{
				return;
			}
			try
			{
				object value = damageModelInstance.GetValue(null);
				float[] array = ((value != null) ? (snapshotMethod.Invoke(value, new object[1] { sail }) as float[]) : null);
				if (array != null)
				{
					record.damage = (float[])array.Clone();
					record.holeKey = HoleKeyFor(sail);
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Could not read Sail Damage data of " + sail.sailName + "; its " + $"package does not keep the damage: {arg}"));
				}
			}
		}

		internal static void ApplyDamage(Sail sail, SailpackRecord record)
		{
			if ((Object)(object)sail == (Object)null || record == null)
			{
				return;
			}
			try
			{
				if (HoleKeysAvailable && !string.IsNullOrEmpty(record.holeKey))
				{
					HoleKeys[sail] = record.holeKey;
				}
				if (DamageAvailable && record.damage != null && record.damage.Length >= 6)
				{
					object value = damageModelInstance.GetValue(null);
					if (value != null)
					{
						restoreMethod.Invoke(value, new object[2]
						{
							sail,
							(float[])record.damage.Clone()
						});
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Could not give " + sail.sailName + " its Sail Damage data back: " + ex));
				}
			}
		}

		internal static void Forget(Sail sail)
		{
			if (sail != null)
			{
				HoleKeys.Remove(sail);
			}
		}

		internal static Dictionary<string, string> GetInstalledHoleKeys()
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>(PendingHoleKeys);
			PruneDestroyed();
			foreach (KeyValuePair<Sail, string> holeKey in HoleKeys)
			{
				string text = SaveKey(holeKey.Key);
				if (text != null)
				{
					dictionary[text] = holeKey.Value;
				}
			}
			return dictionary;
		}

		internal static void LoadInstalledHoleKeys(Dictionary<string, string> keys)
		{
			HoleKeys.Clear();
			PendingHoleKeys.Clear();
			if (keys == null)
			{
				return;
			}
			foreach (KeyValuePair<string, string> key in keys)
			{
				PendingHoleKeys[key.Key] = key.Value;
			}
		}

		private static HarmonyMethod Hook(string methodName)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return new HarmonyMethod(typeof(SailDamageBridge), methodName, (Type[])null);
		}

		private static string SaveKey(Sail sail)
		{
			if (saveKeyMethod == null || (Object)(object)sail == (Object)null)
			{
				return null;
			}
			try
			{
				return saveKeyMethod.Invoke(null, new object[1] { sail }) as string;
			}
			catch (Exception)
			{
				return null;
			}
		}

		private static string HoleKeyFor(Sail sail)
		{
			Claim(sail);
			if (HoleKeys.TryGetValue(sail, out var value))
			{
				return value;
			}
			return SaveKey(sail) ?? sail.sailName;
		}

		private static void Claim(Sail sail)
		{
			if (!((Object)(object)sail == (Object)null) && PendingHoleKeys.Count != 0 && !HoleKeys.ContainsKey(sail))
			{
				string text = SaveKey(sail);
				if (text != null && PendingHoleKeys.TryGetValue(text, out var value))
				{
					PendingHoleKeys.Remove(text);
					HoleKeys[sail] = value;
				}
			}
		}

		private static void PruneDestroyed()
		{
			foreach (Sail item in HoleKeys.Keys.Where((Sail sail) => (Object)(object)sail == (Object)null).ToList())
			{
				HoleKeys.Remove(item);
			}
		}

		private static void HolesPrefix(Sail __0)
		{
			Claim(__0);
			drawingSail = __0;
		}

		private static Exception HolesFinalizer(Exception __exception)
		{
			drawingSail = null;
			return __exception;
		}

		private static void SaveKeyPostfix(Sail __0, ref string __result)
		{
			if ((Object)(object)drawingSail != (Object)null && (Object)(object)__0 == (Object)(object)drawingSail && HoleKeys.TryGetValue(__0, out var value))
			{
				__result = value;
			}
		}

		private static void RebuildRecordPostfix(SaveableBoatCustomization __instance, SaveBoatCustomizationData __result)
		{
			PruneDestroyed();
			if (HoleKeys.Count == 0 || __result?.sails == null)
			{
				return;
			}
			BoatRefs component = ((Component)__instance).GetComponent<BoatRefs>();
			if (component?.masts == null)
			{
				return;
			}
			bool[] array = new bool[__result.sails.Count];
			Mast[] masts = component.masts;
			foreach (Mast val in masts)
			{
				if ((Object)(object)val == (Object)null || !((Component)val).gameObject.activeSelf || val.sails == null)
				{
					continue;
				}
				foreach (GameObject sail in val.sails)
				{
					Sail val2 = (((Object)(object)sail != (Object)null) ? sail.GetComponent<Sail>() : null);
					if ((Object)(object)val2 == (Object)null || !HoleKeys.TryGetValue(val2, out var value))
					{
						continue;
					}
					for (int j = 0; j < __result.sails.Count; j++)
					{
						SaveSailData val3 = __result.sails[j];
						if (!array[j] && SameSail(val3, val, val2))
						{
							array[j] = true;
							RebuildKeys.Remove(val3);
							RebuildKeys.Add(val3, value);
							break;
						}
					}
				}
			}
		}

		private static bool SameSail(SaveSailData data, Mast mast, Sail sail)
		{
			if (data != null && data.mastIndex == mast.orderIndex && data.prefabIndex == sail.prefabIndex && Mathf.Abs(data.installHeight - sail.GetCurrentInstallHeight()) < 0.01f && Mathf.Abs(data.scaleY - sail.GetScaleY()) < 0.001f)
			{
				return Mathf.Abs(data.scaleZ - sail.GetScaleZ()) < 0.001f;
			}
			return false;
		}

		private static void LoadSailPrefix(SaveSailData sailData, out string __state)
		{
			__state = null;
			if (sailData != null)
			{
				RebuildKeys.TryGetValue(sailData, out __state);
			}
		}

		private static void LoadSailPostfix(Mast __instance, string __state)
		{
			if (__state != null && __instance.sails != null && __instance.sails.Count != 0)
			{
				GameObject val = __instance.sails[__instance.sails.Count - 1];
				Sail val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<Sail>() : null);
				if ((Object)(object)val2 != (Object)null)
				{
					HoleKeys[val2] = __state;
				}
			}
		}
	}
	internal static class SailDamageSaveData
	{
		private const string SaveKey = "DogEggz.SailDamage";

		private const string Prefix = "SSD1:";

		private const int FormatVersion = 1;

		private const int MaximumEntryCount = 10000;

		internal static void Save(Dictionary<int, SailpackRecord> records)
		{
			try
			{
				List<KeyValuePair<int, SailpackRecord>> list = (from pair in records
					where pair.Value != null && (pair.Value.damage != null || pair.Value.holeKey != null)
					orderby pair.Key
					select pair).ToList();
				Dictionary<string, string> installedHoleKeys = SailDamageBridge.GetInstalledHoleKeys();
				if (list.Count == 0 && installedHoleKeys.Count == 0)
				{
					GameState.modData?.Remove("DogEggz.SailDamage");
					return;
				}
				string text = Encode(list, installedHoleKeys);
				Decode(text, out var _, out var _);
				if (GameState.modData == null)
				{
					GameState.modData = new Dictionary<string, string>();
				}
				GameState.modData["DogEggz.SailDamage"] = text;
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)($"Saved Sail Damage data of {list.Count} sail package(s) " + $"and {installedHoleKeys.Count} installed staysail(s)."));
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = SwappableStaysailPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Could not save the Sail Damage data of sail packages: {arg}");
				}
			}
		}

		internal static void Load(Dictionary<int, SailpackRecord> records)
		{
			SailDamageBridge.LoadInstalledHoleKeys(null);
			if (GameState.modData == null || !GameState.modData.TryGetValue("DogEggz.SailDamage", out var value) || string.IsNullOrEmpty(value))
			{
				return;
			}
			try
			{
				Decode(value, out var packages, out var installed);
				int num = 0;
				foreach (KeyValuePair<int, SailpackRecord> item in packages)
				{
					if (records.TryGetValue(item.Key, out var value2))
					{
						value2.damage = item.Value.damage;
						value2.holeKey = item.Value.holeKey;
						num++;
					}
				}
				SailDamageBridge.LoadInstalledHoleKeys(installed);
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)($"Loaded Sail Damage data of {num} sail package(s) " + $"and {installed.Count} installed staysail(s)."));
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = SwappableStaysailPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Could not load the Sail Damage data of sail packages: {arg}");
				}
			}
		}

		private static string Encode(List<KeyValuePair<int, SailpackRecord>> packages, Dictionary<string, string> installed)
		{
			using MemoryStream memoryStream = new MemoryStream();
			using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true))
			{
				binaryWriter.Write(1);
				binaryWriter.Write(packages.Count);
				foreach (KeyValuePair<int, SailpackRecord> package in packages)
				{
					float[] damage = package.Value.damage;
					binaryWriter.Write(package.Key);
					binaryWriter.Write((damage != null) ? damage.Length : 0);
					if (damage != null)
					{
						float[] array = damage;
						foreach (float value in array)
						{
							binaryWriter.Write(value);
						}
					}
					binaryWriter.Write(package.Value.holeKey != null);
					binaryWriter.Write(package.Value.holeKey ?? string.Empty);
				}
				binaryWriter.Write(installed.Count);
				foreach (KeyValuePair<string, string> item in installed)
				{
					binaryWriter.Write(item.Key);
					binaryWriter.Write(item.Value ?? string.Empty);
				}
			}
			return "SSD1:" + Convert.ToBase64String(memoryStream.ToArray());
		}

		private static void Decode(string payload, out Dictionary<int, SailpackRecord> packages, out Dictionary<string, string> installed)
		{
			if (payload == null || !payload.StartsWith("SSD1:", StringComparison.Ordinal))
			{
				throw new InvalidDataException("Sail Damage data does not use the SSD1 format.");
			}
			using MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(payload.Substring("SSD1:".Length)), writable: false);
			using BinaryReader binaryReader = new BinaryReader(memoryStream, Encoding.UTF8, leaveOpen: true);
			int num = binaryReader.ReadInt32();
			if (num != 1)
			{
				throw new InvalidDataException($"Unsupported Sail Damage data version {num}.");
			}
			int num2 = ReadCount(binaryReader);
			packages = new Dictionary<int, SailpackRecord>(num2);
			for (int i = 0; i < num2; i++)
			{
				int num3 = binaryReader.ReadInt32();
				int num4 = binaryReader.ReadInt32();
				if (num3 <= 0 || packages.ContainsKey(num3) || (num4 != 0 && num4 != 6))
				{
					throw new InvalidDataException($"Invalid Sail Damage entry for sail package {num3}.");
				}
				float[] array = null;
				if (num4 > 0)
				{
					array = new float[num4];
					for (int j = 0; j < num4; j++)
					{
						float num5 = binaryReader.ReadSingle();
						array[j] = ((float.IsNaN(num5) || float.IsInfinity(num5)) ? 0f : Mathf.Clamp01(num5));
					}
				}
				bool flag = binaryReader.ReadBoolean();
				string text = binaryReader.ReadString();
				packages.Add(num3, new SailpackRecord
				{
					damage = array,
					holeKey = (flag ? text : null)
				});
			}
			int num6 = ReadCount(binaryReader);
			installed = new Dictionary<string, string>(num6);
			for (int k = 0; k < num6; k++)
			{
				installed[binaryReader.ReadString()] = binaryReader.ReadString();
			}
			if (memoryStream.Position != memoryStream.Length)
			{
				throw new InvalidDataException("Sail Damage data contains unexpected trailing data.");
			}
		}

		private static int ReadCount(BinaryReader reader)
		{
			int num = reader.ReadInt32();
			if (num < 0 || num > 10000)
			{
				throw new InvalidDataException($"Invalid Sail Damage entry count {num}.");
			}
			return num;
		}
	}
	[HarmonyPatch(typeof(SaveableBoatCustomization), "GetData")]
	internal static class ExcludeSailmakerPreviewsFromSavePatch
	{
		[HarmonyPostfix]
		private static void Postfix(SaveableBoatCustomization __instance, SaveBoatCustomizationData __result)
		{
			if (__result?.sails == null || SailmakerSession.GetPreviews().Count == 0)
			{
				return;
			}
			BoatRefs component = ((Component)__instance).GetComponent<BoatRefs>();
			if (component?.masts == null)
			{
				return;
			}
			List<int> list = new List<int>();
			int num = 0;
			Mast[] masts = component.masts;
			foreach (Mast val in masts)
			{
				if ((Object)(object)val == (Object)null || !((Component)val).gameObject.activeSelf || val.sails == null)
				{
					continue;
				}
				foreach (GameObject sail in val.sails)
				{
					if (SailmakerSession.IsPreview(((Object)(object)sail != (Object)null) ? sail.GetComponent<Sail>() : null))
					{
						list.Add(num);
					}
					num++;
				}
			}
			for (int num2 = list.Count - 1; num2 >= 0; num2--)
			{
				int num3 = list[num2];
				if (num3 >= 0 && num3 < __result.sails.Count)
				{
					__result.sails.RemoveAt(num3);
				}
			}
		}
	}
	[HarmonyPatch(typeof(ShipyardDocuments), "Update")]
	internal static class SailmakerDeliveryPointPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ShipyardDocuments __instance)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Expected O, but got Unknown
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || (Object)(object)__instance.shipyard == (Object)null || (Object)(object)((Component)__instance).GetComponent<SailmakerDeliveryInstalled>() != (Object)null)
			{
				return;
			}
			((Component)__instance).gameObject.AddComponent<SailmakerDeliveryInstalled>();
			try
			{
				Transform transform = ((Component)__instance).transform;
				GameObject val = new GameObject("sail maker delivery anchor");
				val.transform.SetParent(transform.parent, false);
				val.transform.localScale = transform.localScale;
				val.transform.rotation = transform.rotation;
				Scene scene = ((Component)__instance).gameObject.scene;
				if (TryGetAuthoredPose(((Scene)(ref scene)).name, out var localPosition, out var localEulerAngles))
				{
					val.transform.position = transform.TransformPoint(localPosition);
					val.transform.rotation = transform.rotation * Quaternion.Euler(localEulerAngles);
				}
				else
				{
					val.transform.position = transform.position + GetFallbackOffset(((Component)__instance).GetComponent<Collider>(), transform);
				}
				GameObject val2 = new GameObject("sail package delivery point");
				val2.transform.SetParent(val.transform, false);
				val2.transform.localPosition = new Vector3(0f, 0.55f, 0.8f);
				SailmakerSession.RegisterDeliveryPoint(__instance.shipyard, val2.transform);
			}
			catch (Exception arg)
			{
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogError((object)$"Could not create the Sail Maker delivery point: {arg}");
				}
			}
		}

		private static Vector3 GetFallbackOffset(Collider collider, Transform source)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			Vector3 surfaceLateral = GetSurfaceLateral(collider, source);
			Vector3 val = surfaceLateral * (GetProjectedHalfExtent(collider, surfaceLateral) * 2f + 0.45f);
			if ((Object)(object)collider == (Object)null)
			{
				return val;
			}
			Bounds bounds = collider.bounds;
			Bounds val2 = bounds;
			for (int i = 0; i < 8; i++)
			{
				((Bounds)(ref val2)).center = ((Bounds)(ref bounds)).center + val;
				if (!((Bounds)(ref bounds)).Intersects(val2))
				{
					break;
				}
				val += surfaceLateral * 0.25f;
			}
			return val;
		}

		private static bool TryGetAuthoredPose(string sceneName, out Vector3 localPosition, out Vector3 localEulerAngles)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: 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_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			switch (sceneName)
			{
			case "island 1 A Gold Rock":
				localPosition = new Vector3(-0.646f, -0.66f, 0f);
				localEulerAngles = new Vector3(-1.716f, 0f, -27.634f);
				return true;
			case "island 9 E Dragon Cliffs":
				localPosition = new Vector3(-0.267f, -0.758f, 0f);
				localEulerAngles = new Vector3(0f, 0f, 20.456f);
				return true;
			case "island 15 M (Fort)":
				localPosition = new Vector3(-0.993f, -1.933f, 0f);
				localEulerAngles = new Vector3(0f, 0f, -15.067f);
				return true;
			default:
				localPosition = Vector3.zero;
				localEulerAngles = Vector3.zero;
				return false;
			case "island 27 Lagoon SwampShipyard":
				localPosition = new Vector3(-0.699f, -0.891f, 0f);
				localEulerAngles = new Vector3(0f, 0f, -157.151f);
				return true;
			}
		}

		private static float GetProjectedHalfExtent(Collider collider, Vector3 direction)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: 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_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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)
			if ((Object)(object)collider == (Object)null)
			{
				return 0.6f;
			}
			Bounds bounds = collider.bounds;
			Vector3 extents = ((Bounds)(ref bounds)).extents;
			Vector3 normalized = ((Vector3)(ref direction)).normalized;
			return Mathf.Abs(normalized.x) * extents.x + Mathf.Abs(normalized.y) * extents.y + Mathf.Abs(normalized.z) * extents.z;
		}

		private static Vector3 GetSurfaceLateral(Collider collider, Transform source)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = source.forward;
			BoxCollider val2 = (BoxCollider)(object)((collider is BoxCollider) ? collider : null);
			if ((Object)(object)val2 != (Object)null)
			{
				Vector3 size = val2.size;
				if (size.x <= size.y && size.x <= size.z)
				{
					val = source.right;
				}
				else if (size.y <= size.x && size.y <= size.z)
				{
					val = source.up;
				}
			}
			Vector3 val3 = Vector3.Cross(Vector3.up, val);
			if (((Vector3)(ref val3)).sqrMagnitude < 0.01f)
			{
				val3 = Vector3.ProjectOnPlane(source.right, Vector3.up);
			}
			if (((Vector3)(ref val3)).sqrMagnitude < 0.01f)
			{
				val3 = source.right;
			}
			((Vector3)(ref val3)).Normalize();
			if (Vector3.Dot(val3, source.right) < 0f)
			{
				val3 = -val3;
			}
			return val3;
		}
	}
	internal sealed class SailmakerDeliveryInstalled : MonoBehaviour
	{
	}
	[HarmonyPatch(typeof(ShipyardUI), "Awake")]
	internal static class SailmakerModeButtonInstallPatch
	{
		private const float GapAboveCleanShip = 0.3f;

		[HarmonyPostfix]
		private static void Postfix(ShipyardUI __instance)
		{
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ShipyardButton val = ((IEnumerable<ShipyardButton>)((Component)__instance).GetComponentsInChildren<ShipyardButton>(true)).FirstOrDefault((Func<ShipyardButton, bool>)((ShipyardButton button) => (int)button.function == 12));
				if ((Object)(object)val == (Object)null)
				{
					ManualLogSource log = SwappableStaysailPlugin.Log;
					if (log != null)
					{
						log.LogError((object)"Could not find the shipyard's Clean Ship button; the Sail Maker button was not added.");
					}
					return;
				}
				Transform transform = ((Component)val).transform;
				GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, transform.parent);
				((Object)val2).name = "shipyard ui button sail maker";
				ShipyardButton[] componentsInChildren = val2.GetComponentsInChildren<ShipyardButton>(true);
				for (int num = 0; num < componentsInChildren.Length; num++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren[num]);
				}
				Outline[] componentsInChildren2 = val2.GetComponentsInChildren<Outline>(true);
				for (int num2 = 0; num2 < componentsInChildren2.Length; num2++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren2[num2]);
				}
				val2.transform.localRotation = transform.localRotation;
				val2.transform.localScale = transform.localScale;
				val2.transform.localPosition = transform.localPosition + Vector3.up * (transform.localScale.y + 0.3f);
				TextMesh text = ((val2.transform.childCount > 0) ? ((Component)val2.transform.GetChild(0)).GetComponent<TextMesh>() : null);
				val2.AddComponent<SailmakerModeButton>().Initialize(text);
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = SwappableStaysailPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Could not add the Sail Maker button: {arg}");
				}
			}
		}
	}
	[HarmonyPatch(typeof(ShipyardDocuments), "OnActivate")]
	internal static class NormalShipyardEntryPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			SailmakerSession.End();
		}
	}
	[HarmonyPatch(typeof(Shipyard), "ActivateDocuments")]
	internal static class ShipyardActivatePatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			StaysailInteractionVisuals.ResetForShipyard();
		}

		[HarmonyPostfix]
		private static void Postfix(Shipyard __instance)
		{
			SailmakerSession.TryBegin(__instance);
		}
	}
	[HarmonyPatch(typeof(Shipyard), "DischargeShip")]
	internal static class ShipyardDischargePatch
	{
		[HarmonyPrefix]
		private static void Prefix(Shipyard __instance, bool ___movingShip)
		{
			if (!___movingShip)
			{
				SailmakerCollisionChecks.Cancel(__instance.sailInstaller);
				SailmakerSession.End();
			}
		}

		[HarmonyPostfix]
		private static void Postfix(Shipyard __instance, bool ___movingShip)
		{
			if (!___movingShip)
			{
				SailmakerCollisionChecks.Cancel(__instance.sailInstaller);
			}
		}
	}
	[HarmonyPatch(typeof(ShipyardSailInstaller), "RecheckAllSailsCols")]
	internal static class ShipyardCollisionRecheckPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(ShipyardSailInstaller __instance, Shipyard ___shipyard)
		{
			SailmakerCollisionChecks.Request(__instance, ___shipyard);
			return false;
		}
	}
	internal sealed class SailmakerCollisionChecks : MonoBehaviour
	{
		private Shipyard shipyard;

		private GameObject boat;

		private Coroutine worker;

		private int revision;

		private bool ready;

		internal static void Request(ShipyardSailInstaller installer, Shipyard yard)
		{
			if ((Object)(object)installer == (Object)null)
			{
				return;
			}
			SailmakerCollisionChecks sailmakerCollisionChecks = ((Component)installer).GetComponent<SailmakerCollisionChecks>();
			if ((Object)(object)yard == (Object)null || (Object)(object)GameState.currentShipyard != (Object)(object)yard || (Object)(object)yard.GetCurrentBoat() == (Object)null)
			{
				if ((Object)(object)sailmakerCollisionChecks != (Object)null)
				{
					sailmakerCollisionChecks.Stop();
				}
				return;
			}
			if ((Object)(object)sailmakerCollisionChecks == (Object)null)
			{
				sailmakerCollisionChecks = ((Component)installer).gameObject.AddComponent<SailmakerCollisionChecks>();
			}
			sailmakerCollisionChecks.Stop();
			sailmakerCollisionChecks.shipyard = yard;
			sailmakerCollisionChecks.boat = yard.GetCurrentBoat();
			sailmakerCollisionChecks.worker = ((MonoBehaviour)sailmakerCollisionChecks).StartCoroutine(sailmakerCollisionChecks.Check(sailmakerCollisionChecks.revision));
		}

		internal static bool IsReady(Shipyard yard)
		{
			SailmakerCollisionChecks sailmakerCollisionChecks = (((Object)(object)yard != (Object)null && (Object)(object)yard.sailInstaller != (Object)null) ? ((Component)yard.sailInstaller).GetComponent<SailmakerCollisionChecks>() : null);
			if ((Object)(object)sailmakerCollisionChecks != (Object)null && sailmakerCollisionChecks.ready)
			{
				return sailmakerCollisionChecks.IsCurrent(sailmakerCollisionChecks.revision);
			}
			return false;
		}

		internal static void Cancel(ShipyardSailInstaller installer)
		{
			SailmakerCollisionChecks sailmakerCollisionChecks = (((Object)(object)installer != (Object)null) ? ((Component)installer).GetComponent<SailmakerCollisionChecks>() : null);
			if ((Object)(object)sailmakerCollisionChecks != (Object)null)
			{
				sailmakerCollisionChecks.Stop();
			}
		}

		private void Stop()
		{
			revision++;
			ready = false;
			if (worker != null)
			{
				((MonoBehaviour)this).StopCoroutine(worker);
			}
			worker = null;
			shipyard = null;
			boat = null;
		}

		private bool IsCurrent(int request)
		{
			if (request == revision && (Object)(object)shipyard != (Object)null && (Object)(object)boat != (Object)null && (Object)(object)GameState.currentShipyard == (Object)(object)shipyard)
			{
				return (Object)(object)shipyard.GetCurrentBoat() == (Object)(object)boat;
			}
			return false;
		}

		private IEnumerator Check(int request)
		{
			yield return (object)new WaitForEndOfFrame();
			yield return (object)new WaitForEndOfFrame();
			yield return (object)new WaitForFixedUpdate();
			yield return (object)new WaitForFixedUpdate();
			yield return (object)new WaitForFixedUpdate();
			if (!IsCurrent(request))
			{
				yield break;
			}
			BoatRefs component = boat.GetComponent<BoatRefs>();
			if ((Object)(object)component == (Object)null || component.masts == null)
			{
				yield break;
			}
			Sail[] array = (from s in component.masts.Where((Mast m) => (Object)(object)m != (Object)null && ((Component)m).gameObject.activeInHierarchy && m.sails != null).SelectMany((Mast m) => m.sails.ToArray())
				where (Object)(object)s != (Object)null && s.activeInHierarchy
				select s.GetComponent<Sail>() into s
				where (Object)(object)s != (Object)null
				select s).ToArray();
			List<ShipyardSailColChecker> checkers = new List<ShipyardSailColChecker>();
			Sail[] array2 = array;
			foreach (Sail val in array2)
			{
				if (!IsCurrent(request) || (Object)(object)val == (Object)null)
				{
					yield break;
				}
				SailConnections component2 = ((Component)val).GetComponent<SailConnections>();
				ShipyardSailColChecker val2 = (((Object)(object)component2 != (Object)null) ? component2.colChecker : null);
				if ((Object)(object)val2 == (Object)null)
				{
					yield break;
				}
				checkers.Add(val2);
				val2.RunColCheck();
				yield return (object)new WaitForFixedUpdate();
				yield return (object)new WaitForEndOfFrame();
			}
			while (IsCurrent(request) && checkers.Any((ShipyardSailColChecker c) => (Object)(object)c != (Object)null && c.checking))
			{
				yield return (object)new WaitForFixedUpdate();
			}
			yield return (object)new WaitForFixedUpdate();
			yield return (object)new WaitForEndOfFrame();
			if (IsCurrent(request) && !checkers.Any((ShipyardSailColChecker c) => (Object)(object)c == (Object)null || c.checking || !c.readyToInstall))
			{
				ready = true;
				worker = null;
				shipyard.UpdateOrder();
				if ((Object)(object)ShipyardUI.instance != (Object)null)
				{
					ShipyardUI.instance.RefreshButtons();
				}
			}
		}

		private void OnDisable()
		{
			Stop();
		}
	}
	[HarmonyPatch(typeof(Shipyard), "CancelOrder")]
	internal static class ShipyardCancelPatch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			if (SailmakerSession.Active)
			{
				SailmakerSession.Cancel();
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Shipyard), "SelectMast")]
	internal static class ShipyardSelectMastPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(Shipyard __instance, int index)
		{
			if (!SailmakerSession.Active)
			{
				return true;
			}
			GameObject currentBoat = __instance.GetCurrentBoat();
			BoatRefs val = ((currentBoat != null) ? currentBoat.GetComponent<BoatRefs>() : null);
			if (!SailmakerSession.IsAllowedMast((val?.masts != null && index >= 0 && index < val.masts.Length) ? val.masts[index] : null))
			{
				NotificationUi instance = NotificationUi.instance;
				if (instance != null)
				{
					instance.ShowNotification("Select a supported staysail stay.");
				}
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Shipyard), "SelectSail")]
	internal static class ShipyardSelectSailPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(Shipyard __instance, int index)
		{
			if (!SailmakerSession.Active)
			{
				return true;
			}
			SailmakerSession.SelectPreview(index);
			return false;
		}
	}
	[HarmonyPatch(typeof(Shipyard), "AddNewSail")]
	internal static class ShipyardAddSailPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(Shipyard __instance, GameObject prefab)
		{
			if (!SailmakerSession.Active)
			{
				return true;
			}
			if (!SailmakerSession.IsAllowedMast(__instance.sailInstaller.GetCurrentMast()) || !SailmakerSession.IsAllowedSailPrefab(prefab))
			{
				NotificationUi instance = NotificationUi.instance;
				if (instance != null)
				{
					instance.ShowNotification("Swappable Staysail only accepts staysails on supported stays.");
				}
				return false;
			}
			SailmakerSession.AddPreview(prefab);
			return false;
		}
	}
	[HarmonyPatch(typeof(Shipyard), "RemoveSelectedSail")]
	internal static class ShipyardRemoveSailPatch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			if (!SailmakerSession.Active)
			{
				return true;
			}
			SailmakerSession.RemoveSelectedPreview();
			return false;
		}
	}
	[HarmonyPatch(typeof(ShipyardSailInstaller), "ApplySailPosition")]
	internal static class SailmakerApplyPositionSafetyPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(ShipyardSailInstaller __instance)
		{
			if ((Object)(object)GameState.currentShipyard != (Object)null && (Object)(object)__instance.GetCurrentMast() != (Object)null)
			{
				return (Object)(object)__instance.GetCurrentSail() != (Object)null;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Shipyard), "UpdateOrder", new Type[] { typeof(bool) })]
	internal static class ShipyardOrderPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(Shipyard __instance)
		{
			return !SailmakerSession.RefreshOrder(__instance);
		}
	}
	[HarmonyPatch(typeof(Shipyard), "ConfirmOrder")]
	internal static class ShipyardConfirmPatch
	{
		[HarmonyPrefix]
		private static bool Prefix()
		{
			if (!SailmakerSession.Active)
			{
				return true;
			}
			SailmakerSession.Buy();
			return false;
		}
	}
	[HarmonyPatch(typeof(ShipyardUI), "SailMastCompatible")]
	internal static class SailCompatibilityPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ref bool __result, GameObject sailPrefab)
		{
			if (SailmakerSession.Active)
			{
				Shipyard currentShipyard = GameState.currentShipyard;
				Mast mast = ((currentShipyard != null) ? currentShipyard.sailInstaller.GetCurrentMast() : null);
				__result = SailmakerSession.IsAllowedMast(mast) && SailmakerSession.IsAllowedSailPrefab(sailPrefab);
			}
		}
	}
	[HarmonyPatch(typeof(ShipyardButton), "OnActivate")]
	internal static class SailmakerButtonGuardPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(ShipyardButton __instance)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Invalid comparison between Unknown and I4
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Invalid comparison between Unknown and I4
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Invalid comparison between Unknown and I4
			if (!SailmakerSession.Active)
			{
				return true;
			}
			ButtonFunction function = __instance.function;
			if ((int)function <= 15)
			{
				if ((int)function == 2)
				{
					return __instance.index == 5;
				}
				if (function - 12 <= 3)
				{
					goto IL_002f;
				}
			}
			else if ((int)function == 18 || (int)function == 1000)
			{
				goto IL_002f;
			}
			return true;
			IL_002f:
			return false;
		}
	}
	[HarmonyPatch(typeof(ShipyardUI), "UpdateMastSailsList")]
	internal static class SailmakerSailListPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(ShipyardUI __instance)
		{
			if (!SailmakerSession.Active)
			{
				return true;
			}
			SailmakerSession.RenderPreviewList(__instance);
			return false;
		}
	}
	[HarmonyPatch(typeof(ShipyardUI), "UpdateButtonSelections")]
	internal static class SailmakerSelectionPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ShipyardUI __instance)
		{
			if (SailmakerSession.Active)
			{
				SailmakerSession.RenderPreviewSelections(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(ShipyardUI), "UpdateSailsCountText")]
	internal static class SailmakerSailCountPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(ShipyardUI __instance)
		{
			if (!SailmakerSession.Active)
			{
				return true;
			}
			SailmakerSession.HideSailCount(__instance);
			return false;
		}
	}
	[HarmonyPatch(typeof(ShipyardUI), "RefreshButtons")]
	internal static class SailmakerUiPatch
	{
		private sealed class ButtonLayoutState
		{
			private const float ConfirmWidthMultiplier = 1.45f;

			private const float CancelLeftOffset = 0.55f;

			private readonly Transform button;

			private readonly Transform label;

			private readonly Vector3 buttonLocalPosition;

			private readonly Vector3 buttonLocalScale;

			private readonly Vector3 labelLocalScale;

			internal ButtonLayoutState(ShipyardButton source)
			{
				//IL_006b: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0091: 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_0096: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
				button = (((Object)(object)source != (Object)null) ? ((Component)source).transform : null);
				label = (((Object)(object)button != (Object)null && button.childCount > 0) ? button.GetChild(0) : null);
				buttonLocalPosition = (((Object)(object)button != (Object)null) ? button.localPosition : Vector3.zero);
				buttonLocalScale = (((Object)(object)button != (Object)null) ? button.localScale : Vector3.one);
				labelLocalScale = (((Object)(object)label != (Object)null) ? label.localScale : Vector3.one);
			}

			internal void ApplyConfirm()
			{
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0081: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)button == (Object)null))
				{
					button.localScale = new Vector3(buttonLocalScale.x * 1.45f, buttonLocalScale.y, buttonLocalScale.z);
					if ((Object)(object)label != (Object)null)
					{
						label.localScale = new Vector3(labelLocalScale.x / 1.45f, labelLocalScale.y, labelLocalScale.z);
					}
				}
			}

			internal void ApplyCancel()
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)button != (Object)null)
				{
					button.localPosition = buttonLocalPosition + Vector3.left * 0.55f;
				}
			}

			internal void Restore()
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)button != (Object)null)
				{
					button.localPosition = buttonLocalPosition;
					button.localScale = buttonLocalScale;
				}
				if ((Object)(object)label != (Object)null)
				{
					label.localScale = labelLocalScale;
				}
			}
		}

		private static readonly Dictionary<Collider, bool> ColliderStates = new Dictionary<Collider, bool>();

		private static readonly Dictionary<Renderer, Material> RendererStates = new Dictionary<Renderer, Material>();

		private static readonly Dictionary<ShipyardButton, string> ButtonTexts = new Dictionary<ShipyardButton, string>();

		private static readonly Dictionary<ShipyardButton, ButtonLayoutState> ButtonLayouts = new Dictionary<ShipyardButton, ButtonLayoutState>();

		[HarmonyPostfix]
		private static void Postfix(ShipyardUI __instance)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Invalid comparison between Unknown and I4
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Invalid comparison between Unknown and I4
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Invalid comparison between Unknown and I4
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Invalid comparison between Unknown and I4
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Invalid comparison between Unknown and I4
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Invalid comparison between Unknown and I4
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Invalid comparison between Unknown and I4
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Invalid comparison between Unknown and I4
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Invalid comparison between Unknown and I4
			if (!SailmakerSession.Active)
			{
				RestoreUi();
				return;
			}
			int count = SailmakerSession.GetPreviews().Count;
			ShipyardButton[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<ShipyardButton>(true);
			foreach (ShipyardButton val in componentsInChildren)
			{
				bool num = (int)val.function == 12 || (int)val.function == 18 || (int)val.function == 13 || (int)val.function == 14 || (int)val.function == 15 || (int)val.function == 1000 || ((int)val.function == 2 && val.index != 5);
				Collider component = ((Component)val).GetComponent<Collider>();
				Renderer component2 = ((Component)val).GetComponent<Renderer>();
				if (num)
				{
					if ((Object)(object)component != (Object)null)
					{
						if (!ColliderStates.ContainsKey(component))
						{
							ColliderStates[component] = component.enabled;
						}
						component.enabled = false;
					}
					if ((Object)(object)component2 != (Object)null)
					{
						if (!RendererStates.ContainsKey(component2))
						{
							RendererStates[component2] = component2.sharedMaterial;
						}
						component2.sharedMaterial = __instance.darkParchmentMaterial;
					}
				}
				if ((int)val.function == 8)
				{
					if (!ButtonTexts.ContainsKey(val) && ((Component)val).transform.childCount > 0)
					{
						TextMesh component3 = ((Component)((Component)val).transform.GetChild(0)).GetComponent<TextMesh>();
						if ((Object)(object)component3 != (Object)null)
						{
							ButtonTexts[val] = component3.text;
						}
					}
					val.SetText($"Buy Staysails ({count})");
					GetLayout(val).ApplyConfirm();
				}
				else if ((int)val.function == 9)
				{
					GetLayout(val).ApplyCancel();
				}
			}
		}

		private static ButtonLayoutState GetLayout(ShipyardButton button)
		{
			if (!ButtonLayouts.TryGetValue(button, out var value))
			{
				value = new ButtonLayoutState(button);
				ButtonLayouts[button] = value;
			}
			return value;
		}

		internal static void RestoreUi()
		{
			foreach (KeyValuePair<Collider, bool> colliderState in ColliderStates)
			{
				if ((Object)(object)colliderState.Key != (Object)null)
				{
					colliderState.Key.enabled = colliderState.Value;
				}
			}
			foreach (KeyValuePair<Renderer, Material> rendererState in RendererStates)
			{
				if ((Object)(object)rendererState.Key != (Object)null)
				{
					rendererState.Key.sharedMaterial = rendererState.Value;
				}
			}
			foreach (KeyValuePair<ShipyardButton, string> buttonText in ButtonTexts)
			{
				if ((Object)(object)buttonText.Key != (Object)null)
				{
					buttonText.Key.SetText(buttonText.Value);
				}
			}
			foreach (ButtonLayoutState value in ButtonLayouts.Values)
			{
				value.Restore();
			}
			ColliderStates.Clear();
			RendererStates.Clear();
			ButtonTexts.Clear();
			ButtonLayouts.Clear();
		}
	}
	[HarmonyPatch(typeof(WindCloth), "Update")]
	internal static class SailmakerHiddenClothPatch
	{
		[HarmonyPostfix]
		private static void Postfix(Sail ___sail, Renderer ___renderer)
		{
			if ((Object)(object)___renderer != (Object)null && SailmakerSession.IsHiddenSail(___sail))
			{
				___renderer.enabled = false;
			}
		}
	}
	[HarmonyPatch(typeof(ShipyardSailColChecker), "OnTriggerEnter")]
	internal static class SailmakerPreviewCollisionPatch
	{
		private static readonly FieldInfo SailField = AccessTools.Field(typeof(ShipyardSailColChecker), "sail");

		[HarmonyPostfix]
		private static void Postfix(ShipyardSailColChecker __instance, Collider other, Sail ___sail)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Invalid comparison between Unknown and I4
			if (!SailmakerSession.Active || (Object)(object)other == (Object)null || __instance.currentAngle != 0 || ((Component)__instance).transform.position.y >= 900f || !SailmakerSession.IsPreview(___sail))
			{
				return;
			}
			GameObject gameObject = ((Component)other).gameObject;
			if (gameObject.CompareTag("SailColCheckerSub") && (Object)(object)gameObject.transform.parent != (Object)null)
			{
				gameObject = ((Component)gameObject.transform.parent).gameObject;
			}
			if (!((Object)(object)gameObject == (Object)(object)((Component)__instance).gameObject) && gameObject.CompareTag("SailColChecker"))
			{
				ShipyardSailColChecker component = gameObject.GetComponent<ShipyardSailColChecker>();
				Sail val;
				if (!((Object)(object)component != (Object)null))
				{
					val = null;
				}
				else
				{
					FieldInfo sailField = SailField;
					object? obj = ((sailField != null) ? sailField.GetValue(component) : null);
					val = (Sail)((obj is Sail) ? obj : null);
				}
				Sail val2 = val;
				if (!((Object)(object)component == (Object)null) && component.currentAngle == 0 && !((Object)(object)val2 == (Object)null) && (int)val2.category != 5)
				{
					__instance.collisionsWithSails++;
					SailmakerSession.RefreshOrder(GameState.currentShipyard);
				}
			}
		}
	}
	internal static class SailmakerSession
	{
		private static readonly FieldInfo CurrentOrderTotalField = AccessTools.Field(typeof(Shipyard), "currentOrderTotal");

		private static readonly FieldInfo CurrentOrderTextField = AccessTools.Field(typeof(Shipyard), "currentOrderText");

		private static readonly FieldInfo InstallErrorField = AccessTools.Field(typeof(Shipyard), "installError");

		private static readonly FieldInfo SelectSailButtonsField = AccessTools.Field(typeof(ShipyardUI), "selectSailButtons");

		private static readonly FieldInfo SailCountTextField = AccessTools.Field(typeof(ShipyardUI), "sailCountText");

		private static readonly Dictionary<Shipyard, Transform> DeliveryPoints = new Dictionary<Shipyard, Transform>();

		private static readonly List<SailmakerPreview> Previews = new List<SailmakerPreview>();

		private static readonly Dictionary<Mast, SailmakerMastRigState> RigStates = new Dictionary<Mast, SailmakerMastRigState>();

		private static readonly HashSet<Sail> HiddenSails = new HashSet<Sail>();

		private static readonly Dictionary<Renderer, bool> HiddenClothRenderers = new Dictionary<Renderer, bool>();

		private static readonly FieldRef<Shipyard, SaveBoatCustomizationData> OriginalData = AccessTools.FieldRefAccess<Shipyard, SaveBoatCustomizationData>("originalData");

		internal static bool Pending { get; private set; }

		internal static Shipyard ActiveShipyard { get; private set; }

		internal static bool Active
		{
			get
			{
				if ((Object)(object)ActiveShipyard != (Object)null)
				{
					return (Object)(object)GameState.currentShipyard == (Object)(object)ActiveShipyard;
				}
				return false;
			}
		}

		internal static void RegisterDeliveryPoint(Shipyard shipyard, Transform point)
		{
			PruneDeliveryPoints();
			if ((Object)(object)shipyard != (Object)null && (Object)(object)point != (Object)null)
			{
				DeliveryPoints[shipyard] = point;
			}
		}

		internal static void Request(Shipyard shipyard)
		{
			Pending = (Object)(object)shipyard != (Object)null;
		}

		internal static void TryBegin(Shipyard shipyard)
		{
			if (Pending && !((Object)(object)shipyard == (Object)null) && !((Object)(object)GameState.currentShipyard != (Object)(object)shipyard))
			{
				StayInstallTargeting.Deactivate();
				Pending = false;
				ActiveShipyard = shipyard;
				ClearPreviews(refresh: false);
				HideInstalledSails(shipyard);
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"Opened Sail Maker at shipyard region {shipyard.region}.");
				}
				RefreshOrder(shipyard);
				ShipyardUI instance = ShipyardUI.instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.ChangeMenuCategory(-1);
					instance.CloseSailCategoryMenu();
					instance.HideNewSailButtons();
					instance.RefreshButtons();
				}
			}
		}

		internal static void End()
		{
			Pending = false;
			StayInstallTargeting.Deactivate();
			try
			{
				ClearPreviews(refresh: false);
			}
			catch (Exception arg)
			{
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogError((object)$"Sail Maker cleanup failed during exit: {arg}");
				}
			}
			finally
			{
				ShowInstalledSails();
				ActiveShipyard = null;
				SailmakerUiPatch.RestoreUi();
			}
		}

		internal static bool IsHiddenSail(Sail sail)
		{
			if (HiddenSails.Count > 0 && (Object)(object)sail != (Object)null)
			{
				return HiddenSails.Contains(sail);
			}
			return false;
		}

		private static void HideInstalledSails(Shipyard shipyard)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Invalid comparison between Unknown and I4
			ShowInstalledSails();
			GameObject currentBoat = shipyard.GetCurrentBoat();
			BoatRefs val = (((Object)(object)currentBoat != (Object)null) ? currentBoat.GetComponent<BoatRefs>() : null);
			if ((((Object)(object)val != (Object)null) ? val.masts : null) == null)
			{
				return;
			}
			Mast[] masts = val.masts;
			foreach (Mast val2 in masts)
			{
				if ((Object)(object)val2 == (Object)null || val2.sails == null)
				{
					continue;
				}
				foreach (GameObject sail in val2.sails)
				{
					Sail val3 = (((Object)(object)sail != (Object)null) ? sail.GetComponent<Sail>() : null);
					if ((Object)(object)val3 == (Object)null || (int)val3.category != 5 || IsPreview(val3))
					{
						continue;
					}
					HiddenSails.Add(val3);
					WindCloth[] componentsInChildren = sail.GetComponentsInChildren<WindCloth>(true);
					for (int j = 0; j < componentsInChildren.Length; j++)
					{
						Renderer component = ((Component)componentsInChildren[j]).GetComponent<Renderer>();
						if ((Object)(object)component != (Object)null && !HiddenClothRenderers.ContainsKey(component))
						{
							HiddenClothRenderers[component] = component.enabled;
							component.enabled = false;
						}
					}
				}
			}
		}

		private static void ShowInstalledSails()
		{
			foreach (KeyValuePair<Renderer, bool> hiddenClothRenderer in HiddenClothRenderers)
			{
				if ((Object)(object)hiddenClothRenderer.Key != (Object)null)
				{
					hiddenClothRenderer.Key.enabled = hiddenClothRenderer.Value;
				}
			}
			HiddenClothRenderers.Clear();
			HiddenSails.Clear();
		}

		internal static void ToggleFromShipyardMenu()
		{
			Shipyard currentShipyard = GameState.currentShipyard;
			if ((Object)(object)currentShipyard == (Object)null || (Object)(object)currentShipyard.GetCurrentBoat() == (Object)null)
			{
				return;
			}
			if (Active)
			{
				if (GetPreviews().Count > 0)
				{
					Notify("Buy or cancel the\nstaysails first.");
					return;
				}
				End();
				ShowSailPage(currentShipyard);
				currentShipyard.UpdateOrder();
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"Switched from Sail Maker back to the shipyard.");
				}
			}
			else if (HasUnconfirmedShipyardOrder(currentShipyard))
			{
				Notify("Confirm or cancel the\ncurrent order first.");
			}
			else if (!HasSupportedStay(currentShipyard.GetCurrentBoat()))
			{
				Notify("This ship has no\nsupported staysail stay.");
			}
			else
			{
				currentShipyard.sailInstaller.SelectMast((Mast)null);
				Request(currentShipyard);
				TryBegin(currentShipyard);
			}
		}

		private static void ShowSailPage(Shipyard shipyard)
		{
			shipyard.sailInstaller.SelectMast((Mast)null);
			ShipyardUI instance = ShipyardUI.instance;
			if ((Object)(object)instance != (Object)null)
			{
				instance.ChangeMenuCategory(-1);
				instance.CloseSailCategoryMenu();
				instance.HideNewSailButtons();
			}
		}

		private static bool HasUnpaidPaint(Shipyard shipyard)
		{
			int[] array = OriginalData.Invoke(shipyard)?.customColors;
			GameObject currentBoat = shipyard.GetCurrentBoat();
			SaveableBoatCustomization val = ((currentBoat != null) ? currentBoat.GetComponent<SaveableBoatCustomization>() : null);
			int[] array2 = ((!((Object)(object)val != (Object)null)) ? null : val.GetData()?.customColors);
			if (array != null && array2 != null)
			{
				return !array2.SequenceEqual(array);
			}
			return false;
		}

		private static bool HasUnconfirmedShipyardOrder(Shipyard shipyard)
		{
			if (shipyard.IncludeHullCleaning() || shipyard.IncludeRepair() || SailDamageBridge.PatchSailsOrdered() || HasUnpaidPaint(shipyard))
			{
				return true;
			}
			List<ShipyardRefund> currentRefunds = shipyard.GetCurrentRefunds();
			if (currentRefunds != null && currentRefunds.Count > 0)
			{
				return true;
			}
			GameObject currentBoat = shipyard.GetCurrentBoat();
			BoatRefs component = currentBoat.GetComponent<BoatRefs>();
			if ((((Object)(object)component != (Object)null) ? component.masts : null) != null)
			{
				Mast[] masts = component.masts;
				foreach (Mast val in masts)
				{
					if ((Object)(object)val == (Object)null || val.sails == null)
					{
						continue;
					}
					foreach (GameObject sail in val.sails)
					{
						Sail val2 = (((Object)(object)sail != (Object)null) ? sail.GetComponent<Sail>() : null);
						if ((Object)(object)val2 != (Object)null && !val2.IsInstalled())
						{
							return true;
						}
					}
				}
			}
			BoatCustomParts component2 = currentBoat.GetComponent<BoatCustomParts>();
			BoatPartsOrder val3 = (((Object)(object)shipyard.partsInstaller != (Object)null) ? shipyard.partsInstaller.GetCurrentOrder() : null);
			if ((((Object)(object)component2 != (Object)null) ? component2.availableParts : null) != null && val3?.orderedOptions != null)
			{
				int num = Math.Min(component2.availableParts.Count, val3.orderedOptions.Length);
				for (int j = 0; j < num; j++)
				{
					if (component2.availableParts[j].activeOption != val3.orderedOptions[j])
					{
						return true;
					}
				}
			}
			return false;
		}

		private static bool HasSupportedStay(GameObject boat)
		{
			BoatRefs component = boat.GetComponent<BoatRefs>();
			if ((((Object)(object)component != (Object)null) ? component.masts : null) != null)
			{
				return component.masts.Any((Mast mast) => (Object)(object)mast != (Object)null && ((Component)mast).gameObject.activeInHierarchy && StaysailTargets.IsEligible(mast));
			}
			return false;
		}

		internal static bool IsAllowedMast(Mast mast)
		{
			if (Active)
			{
				return StaysailTargets.IsEligible(mast);
			}
			return false;
		}

		internal static bool IsAllowedSailPrefab(GameObject prefab)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Invalid comparison between Unknown and I4
			Sail val = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<Sail>() : null);
			if ((Object)(object)val != (Object)null)
			{
				return (int)val.category == 5;
			}
			return false;
		}

		internal static IReadOnlyList<SailmakerPreview> GetPreviews()
		{
			Previews.RemoveAll((SailmakerPreview preview) => preview == null || (Object)(object)preview.Mast == (Object)null || (Object)(object)preview.Sail == (Object)null);
			return Previews;
		}

		internal static List<SailmakerPreview> GetPreviews(Mast mast)
		{
			return (from preview in GetPreviews()
				where (Object)(object)preview.Mast == (Object)(object)mast
				select preview).ToList();
		}

		internal static bool IsPreview(Sail sail)
		{
			if ((Object)(object)sail != (Object)null)
			{
				return GetPreviews().Any((SailmakerPreview preview) => (Object)(object)preview.Sail == (Object)(object)sail);
			}
			return false;
		}

		internal static bool AddPreview(GameObject prefab)
		{
			if (!Active || !IsAllowedSailPrefab(prefab))
			{
				return false;
			}
			Mast currentMast = ActiveShipyard.sailInstaller.GetCurrentMast();
			if (!IsAllowedMast(currentMast))
			{
				Notify("Select a supported staysail stay.");
				return false;
			}
			GameObject[] obj = (((Object)(object)ShipyardUI.instance != (Object)null) ? (SelectSailButtonsField?.GetValue(ShipyardUI.instance) as GameObject[]) : null);
			int num = ((obj != null) ? obj.Length : 0);
			if (GetPreviews(currentMast).Count >= num)
			{
				Notify((num > 0) ? $"Order at most {num} staysails per stay.\nBuy or remove one first." : "The staysail selection menu is unavailable.");
				return false;
			}
			GameObject val = null;
			try
			{
				val = Object.Instantiate<GameObject>(prefab);
				Sail component = val.GetComponent<Sail>();
				SailConnections component2 = val.GetComponent<SailConnections>();
				if (!CanSupplyPreviewControllers(currentMast, component2))
				{
					Object.Destroy((Object)(object)val);
					Notify("That stay does not have the required sail controllers.");
					return false;
				}
				EnsurePreviewRigCapacity(currentMast, (currentMast.sails?.Count ?? 0) + 1);
				ActiveShipyard.sailInstaller.AddNewSail(val);
				Previews.Add(new SailmakerPreview(currentMast, component));
				ActiveShipyard.sailInstaller.RecheckAllSailsCols();
				RefreshPreviewUi();
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)("Added registered Sail Maker preview '" + component.sailName + "' for " + StaysailTargets.GetStayName(currentMast) + "."));
				}
				return true;
			}
			catch (Exception arg)
			{
				if ((Object)(object)val != (Object)null)
				{
					if (currentMast.sails != null && currentMast.sails.Contains(val))
					{
						currentMast.DetachSailFromMast(val);
					}
					else
					{
						Object.Destroy((Object)(object)val);
					}
				}
				RestorePreviewRigIfUnused(currentMast);
				ManualLogSource log2 = SwappableStaysailPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Could not add Sail Maker preview: {arg}");
				}
				Notify("Could not add that staysail.");
				return false;
			}
		}

		internal static bool SelectPreview(int index)
		{
			if (!Active)
			{
				return false;
			}
			List<SailmakerPreview> previews = GetPreviews(ActiveShipyard.sailInstaller.GetCurrentMast());
			if (index < 0 || index >= previews.Count)
			{
				return false;
			}
			ActiveShipyard.sailInstaller.SelectSail(((Component)previews[index].Sail).gameObject);
			RefreshPreviewUi();
			return true;
		}

		internal static bool RemoveSelectedPreview()
		{
			if (!Active)
			{
				return false;
			}
			Sail selected = ActiveShipyard.sailInstaller.GetCurrentSail();
			SailmakerPreview sailmakerPreview = Previews.FirstOrDefault((SailmakerPreview candidate) => (Object)(object)candidate.Sail == (Object)(object)selected);
			if (sailmakerPreview == null)
			{
				return false;
			}
			Previews.Remove(sailmakerPreview);
			ActiveShipyard.sailInstaller.SelectSail((GameObject)null);
			DestroyPreview(sailmakerPreview);
			RestorePreviewRigIfUnused(sailmakerPreview.Mast);
			ActiveShipyard.sailInstaller.RecheckAllSailsCols();
			RefreshPreviewUi();
			return true;
		}

		internal static bool Cancel()
		{
			if (!Active)
			{
				return false;
			}
			ClearPreviews(refresh: true);
			return true;
		}

		internal static bool RefreshOrder(Shipyard shipyard)
		{
			if (!Active || (Object)(object)shipyard != (Object)(object)ActiveShipyard || (Object)(object)ShipyardUI.instance == (Object)null)
			{
				return false;
			}
			IReadOnlyList<SailmakerPreview> previews = GetPreviews();
			ShipyardUIOrderText shipyardOrderText = ShipyardUI.instance.shipyardOrderText;
			shipyardOrderText.ResetOrderText();
			int num = 0;
			bool flag = false;
			foreach (SailmakerPreview item in previews)
			{
				bool error = false;
				string arg = ValidatePreview(item.Mast, item.Sail, ref error);
				int num2 = Mathf.RoundToInt(item.Sail.GetSailPrice() * shipyard.GetCurrencyRate());
				num += num2;
				flag = flag || error;
				shipyardOrderText.AddLine($"{num2}: {item.Sail.sailName}{arg}");
			}
			if (previews.Count > 0)
			{
				shipyardOrderText.AddLine(" ");
			}
			shipyardOrderText.SetTotalLine($"TOTAL: {num} {PlayerGold.GetCurrencyName(shipyard.region)}");
			shipyardOrderText.DisplayCurrentText();
			CurrentOrderTotalField?.SetValue(shipyard, num);
			CurrentOrderTextField?.SetValue(shipyard, $"{previews.Count} spare staysail(s), total {num}");
			InstallErrorField?.SetValue(shipyard, flag);
			return true;
		}

		internal static bool Buy()
		{
			//IL_014c: 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_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			if (!Active)
			{
				return false;
			}
			List<SailmakerPreview> list = GetPreviews().ToList();
			if (list.Count == 0)
			{
				Notify("Add at least one staysail first.");
				return false;
			}
			int num = 0;
			List<SailpackRecord> list2 = new List<SailpackRecord>();
			List<Mast> list3 = new List<Mast>();
			foreach (SailmakerPreview item in list)
			{
				bool error = false;
				string text = ValidatePreview(item.Mast, item.Sail, ref error);
				if (error)
				{
					Notify("A staysail cannot be packed: " + text.Trim());
					return false;
				}
				list2.Add(SailpackRecord.FromSail(item.Sail, item.Mast));
				list3.Add(item.Mast);
				num += Mathf.RoundToInt(item.Sail.GetSailPrice() * ActiveShipyard.GetCurrencyRate());
			}
			if (PlayerGold.currency[ActiveShipyard.region] < num)
			{
				Notify("Not enough money.");
				return false;
			}
			Transform val = GetDeliveryPoint(ActiveShipyard) ?? ActiveShipyard.editedShipPosition;
			if ((Object)(object)val == (Object)null)
			{
				Notify("Could not find the Sail Maker delivery point.");
				return false;
			}
			List<SailpackData> list4 = new List<SailpackData>();
			bool flag = false;
			try
			{
				for (int i = 0; i < list2.Count; i++)
				{
					Vector3 position = val.position + val.right * (0.45f * (float)(i % 3)) + val.forward * (0.4f * (float)(i / 3));
					SailpackData sailpackData = SailpackFactory.CreateStaged(list2[i], position, val.rotation, registerToSave: false, list3[i]);
					if ((Object)(object)sailpackData == (Object)null)
					{
						throw new InvalidOperationException("A staged sail package could not be created.");
					}
					list4.Add(sailpackData);
				}
				foreach (SailpackData item2 in list4)
				{
					SaveablePrefab component = ((Component)item2).GetComponent<SaveablePrefab>();
					if ((Object)(object)component == (Object)null)
					{
						throw new InvalidOperationException("A staged sail package has no save component.");
					}
					component.RegisterToSave();
					SailpackPersistence.Register(component.instanceId, item2.Record);
				}
				ClearPreviews(refresh: true);
				foreach (SailpackData item3 in list4)
				{
					SailpackFactory.ActivateStaged(item3);
				}
				PlayerGold.currency[ActiveShipyard.region] -= num;
				flag = true;
			}
			catch (Exception arg)
			{
				if (!flag)
				{
					foreach (SailpackData item4 in list4)
					{
						if (!((Object)(object)item4 == (Object)null))
						{
							SailpackFactory.DiscardStaged(item4, unregisterFromSave: true);
						}
					}
				}
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogError((object)$"Sail package purchase failed before commit: {arg}");
				}
				Notify("Could not create the sail packages; nothing was charged.");
				return false;
			}
			UISoundPlayer instance = UISoundPlayer.instance;
			if (instance != null)
			{
				instance.PlayGoldSound();
			}
			try
			{
				DayLogs instance2 = DayLogs.instance;
				if (instance2 != null)
				{
					instance2.dayLogs[ActiveShipyard.region].LogTransaction(-num, (TransactionCategory)11);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = SwappableStaysailPlugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("Sail package purchase succeeded but day-log entry failed: " + ex));
				}
			}
			Notify($"Created {list4.Count} sail package(s).");
			ManualLogSource log3 = SwappableStaysailPlugin.Log;
			if (log3 != null)
			{
				log3.LogInfo((object)($"Purchased {list4.Count} spare sail package(s) for {num}; " + "installed staysails were unchanged."));
			}
			return true;
		}

		internal static void RenderPreviewList(ShipyardUI ui)
		{
			if (SelectSailButtonsField?.GetValue(ui) is GameObject[] array)
			{
				Shipyard activeShipyard = ActiveShipyard;
				List<SailmakerPreview> previews = GetPreviews((activeShipyard != null) ? activeShipyard.sailInstaller.GetCurrentMast() : null);
				for (int i = 0; i < array.Length; i++)
				{
					bool flag = i < previews.Count && (Object)(object)previews[i].Sail != (Object)null;
					array[i].SetActive(flag);
					array[i].GetComponent<ShipyardButton>().SetText(flag ? previews[i].Sail.sailName : "-");
				}
			}
		}

		internal static void RenderPreviewSelections(ShipyardUI ui)
		{
			if (SelectSailButtonsField?.GetValue(ui) is GameObject[] array)
			{
				Shipyard activeShipyard = ActiveShipyard;
				List<SailmakerPreview> previews = GetPreviews((activeShipyard != null) ? activeShipyard.sailInstaller.GetCurrentMast() : null);
				Shipyard activeShipyard2 = ActiveShipyard;
				Sail val = ((activeShipyard2 != null) ? activeShipyard2.sailInstaller.GetCurrentSail() : null);
				for (int i = 0; i < array.Length; i++)
				{
					bool flag = i < previews.Count && (Object)(object)previews[i].Sail == (Object)(object)val;
					array[i].GetComponent<Renderer>().sharedMaterial = (flag ? ui.selectedButtonMaterial : ui.defaultButtonMaterial);
				}
			}
		}

		internal static void HideSailCount(ShipyardUI ui)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			object? obj = SailCountTextField?.GetValue(ui);
			TextMesh val = (TextMesh)((obj is TextMesh) ? obj : null);
			if ((Object)(object)val != (Object)null)
			{
				val.text = "";
				val.color = Color.black;
			}
		}

		internal static void Dispose()
		{
			try
			{
				End();
			}
			finally
			{
				DeliveryPoints.Clear();
				Previews.Clear();
				RigStates.Clear();
			}
		}

		private static Transform GetDeliveryPoint(Shipyard shipyard)
		{
			PruneDeliveryPoints();
			if (!((Object)(object)shipyard != (Object)null) || !DeliveryPoints.TryGetValue(shipyard, out var value) || !((Object)(object)value != (Object)null))
			{
				return null;
			}
			return value;
		}

		private static void PruneDeliveryPoints()
		{
			Shipyard[] array = (from pair in DeliveryPoints
				where (Object)(object)pair.Key == (Object)null || (Object)(object)pair.Value == (Object)null
				select pair.Key).ToArray();
			foreach (Shipyard key in array)
			{
				DeliveryPoints.Remove(key);
			}
		}

		private static string ValidatePreview(Mast mast, Sail sail, ref bool error)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			if (!StaysailTargets.IsEligible(mast))
			{
				error = true;
				return " (NOT A SUPPORTED STAY)";
			}
			if ((Object)(object)sail == (Object)null || (int)sail.category != 5)
			{
				error = true;
				return " (NOT A STAYSAIL)";
			}
			float num = sail.GetCurrentInstallHeight() - sail.GetScaledHeight();
			if (sail.GetScaledHeight() > mast.mastHeight || num < -0.1f)
			{
				error = true;
				return " (DOES NOT FIT STAY)";
			}
			SailConnections component = ((Component)sail).GetComponent<SailConnections>();
			ShipyardSailColChecker val = (((Object)(object)component != (Object)null) ? component.colChecker : null);
			if ((Object)(object)val == (Object)null || !val.readyToInstall || val.checking || !SailmakerCollisionChecks.IsReady(ActiveShipyard))
			{
				error = true;
				return " (checking collision...)";
			}
			if (val.IsCollidingWithSail())
			{
				error = true;
				return " (SAILS COLLISION)";
			}
			return "";
		}

		private static void ClearPreviews(bool refresh)
		{
			Shipyard activeShipyard = ActiveShipyard;
			Sail selected = (((Object)(object)activeShipyard?.sailInstaller != (Object)null) ? activeShipyard.sailInstaller.GetCurrentSail() : null);
			bool flag = Previews.Any((SailmakerPreview preview) => (Object)(object)preview.Sail == (Object)(object)selected);
			SailmakerPreview[] array = Previews.ToArray();
			Previews.Clear();
			SailmakerPreview[] array2 = array;
			for (int num = 0; num < array2.Length; num++)
			{
				DestroyPreview(array2[num]);
			}
			Mast[] array3 = RigStates.Keys.ToArray();
			for (int num = 0; num < array3.Length; num++)
			{
				RestorePreviewRig(array3[num]);
			}
			if ((Object)(object)activeShipyard?.sailInstaller != (Object)null)
			{
				if ((Object)(object)selected == (Object)null || flag)
				{
					activeShipyard.sailInstaller.SelectSail((GameObject)null);
				}
				if (refresh)
				{
					activeShipyard.sailInstaller.RecheckAllSailsCols();
				}
			}
			if (refresh && Active)
			{
				RefreshPreviewUi();
			}
		}

		private static void DestroyPreview(SailmakerPreview preview)
		{
			if ((Object)(object)preview?.Sail == (Object)null)
			{
				return;
			}
			GameObject gameObject = ((Component)preview.Sail).gameObject;
			Mast mast = preview.Mast;
			if ((Object)(object)mast != (Object)null && mast.sails != null && mast.sails.Contains(gameObject))
			{
				if (!StaysailDetacher.TryDetach(mast, preview.Sail, out var error))
				{
					ManualLogSource log = SwappableStaysailPlugin.Log;
					if (log != null)
					{
						log.LogWarning((object)("Could not fully detach Sail Maker preview: " + error));
					}
					mast.sails.Remove(gameObject);
					Object.Destroy((Object)(object)gameObject);
				}
			}
			else
			{
				Object.Destroy((Object)(object)gameObject);
			}
		}

		private static bool CanSupplyPreviewControllers(Mast mast, SailConnections connections)
		{
			if ((Object)(object)mast == (Object)null || (Object)(object)connections == (Object)null)
			{
				return false;
			}
			if ((Object)(object)connections.reefController != (Object)null && (mast.reefWinch == null || mast.reefWinch.Length == 0))
			{
				return false;
			}
			if ((Object)(object)connections.angleControllerMid != (Object)null && (mast.midAngleWinch == null || mast.midAngleWinch.Length == 0))
			{
				return false;
			}
			if (((Object)(object)connections.angleControllerLeft != (Object)null || (Object)(object)connections.angleControllerRight != (Object)null) && (mast.leftAngleWinch == null || mast.leftAngleWinch.Length == 0 || mast.rightAngleWinch == null || mast.rightAngleWinch.Length == 0))
			{
				return false;
			}
			if ((Object)(object)connections.mastReefAttachment != (Object)null && (mast.mastReefAtt == null || mast.mastReefAtt.Length == 0))
			{
				return false;
			}
			if ((Object)(object)connections.midRopeAttachment != (Object)null && (mast.midRopeAtt == null || mast.midRopeAtt.Length == 0) && (mast.midAngleWinch == null || mast.midAngleWinch.Length == 0))
			{
				return false;
			}
			return true;
		}

		private static void EnsurePreviewRigCapacity(Mast mast, int count)
		{
			if (!RigStates.TryGetValue(mast, out var value))
			{
				value = new SailmakerMastRigState(mast);
				RigStates[mast] = value;
			}
			value.EnsureCapacity(mast, count);
		}

		private static void RestorePreviewRigIfUnused(Mast mast)
		{
			if ((Object)(object)mast != (Object)null && !Previews.Any((SailmakerPreview preview) => (Object)(object)preview.Mast == (Object)(object)mast))
			{
				RestorePreviewRig(mast);
			}
		}

		private static void RestorePreviewRig(Mast mast)
		{
			if (!((Object)(object)mast == (Object)null) && RigStates.TryGetValue(mast, out var value))
			{
				value.Restore(mast);
				RigStates.Remove(mast);
				mast.UpdateSailOrder();
				mast.UpdateControllerAttachments();
			}
		}

		private static void RefreshPreviewUi()
		{
			if (Active)
			{
				RefreshOrder(ActiveShipyard);
				ShipyardUI instance = ShipyardUI.instance;
				if (instance != null)
				{
					instance.RefreshButtons();
				}
			}
		}

		private static void Notify(string message)
		{
			NotificationUi instance = NotificationUi.instance;
			if (instance != null)
			{
				instance.ShowNotification(message);
			}
		}
	}
	internal sealed class SailmakerPreview
	{
		internal Mast Mast { get; }

		internal Sail Sail { get; }

		internal SailmakerPreview(Mast mast, Sail sail)
		{
			Mast = mast;
			Sail = sail;
		}
	}
	internal sealed class SailmakerMastRigState
	{
		private readonly GPButtonRopeWinch[] leftAngleWinch;

		private readonly GPButtonRopeWinch[] rightAngleWinch;

		private readonly GPButtonRopeWinch[] midAngleWinch;

		private readonly GPButtonRopeWinch[] reefWinch;

		private readonly Transform[] midRopeAtt;

		private readonly Transform[] mastReefAtt;

		private readonly Transform[] mastReefAttExtension;

		internal SailmakerMastRigState(Mast mast)
		{
			leftAngleWinch = mast.leftAngleWinch;
			rightAngleWinch = mast.rightAngleWinch;
			midAngleWinch = mast.midAngleWinch;
			reefWinch = mast.reefWinch;
			midRopeAtt = mast.midRopeAtt;
			mastReefAtt = mast.mastReefAtt;
			mastReefAttExtension = mast.mastReefAttExtension;
		}

		internal void EnsureCapacity(Mast mast, int count)
		{
			mast.leftAngleWinch = Expand(leftAngleWinch, count);
			mast.rightAngleWinch = Expand(rightAngleWinch, count);
			mast.midAngleWinch = Expand(midAngleWinch, count);
			mast.reefWinch = Expand(reefWinch, count);
			mast.midRopeAtt = Expand(midRopeAtt, count);
			mast.mastReefAtt = Expand(mastReefAtt, count);
			mast.mastReefAttExtension = Expand(mastReefAttExtension, count);
		}

		internal void Restore(Mast mast)
		{
			mast.leftAngleWinch = leftAngleWinch;
			mast.rightAngleWinch = rightAngleWinch;
			mast.midAngleWinch = midAngleWinch;
			mast.reefWinch = reefWinch;
			mast.midRopeAtt = midRopeAtt;
			mast.mastReefAtt = mastReefAtt;
			mast.mastReefAttExtension = mastReefAttExtension;
		}

		private static T[] Expand<T>(T[] source, int count)
		{
			if (source == null || source.Length == 0 || source.Length >= count)
			{
				return source;
			}
			T[] array = new T[count];
			Array.Copy(source, array, source.Length);
			T val = source[^1];
			for (int i = source.Length; i < array.Length; i++)
			{
				array[i] = val;
			}
			return array;
		}
	}
	internal sealed class SailmakerModeButton : GoPointerButton
	{
		private TextMesh label;

		private Renderer buttonRenderer;

		private bool hasShownState;

		private bool shownActive;

		internal void Initialize(TextMesh text)
		{
			label = text;
			buttonRenderer = ((Component)this).GetComponent<Renderer>();
			hasShownState = false;
			RefreshAppearance();
		}

		public override void ExtraLateUpdate()
		{
			RefreshAppearance();
		}

		public override void OnActivate()
		{
			UISoundPlayer instance = UISoundPlayer.instance;
			if ((Object)(object)instance != (Object)null)
			{
				instance.PlayUISound((UISounds)1, 0.33f, 3f);
			}
			ShipyardUI instance2 = ShipyardUI.instance;
			if ((Object)(object)instance2 != (Object)null)
			{
				instance2.HideNewSailButtons();
				instance2.CloseSailCategoryMenu();
			}
			SailmakerSession.ToggleFromShipyardMenu();
			RefreshAppearance();
			if ((Object)(object)instance2 != (Object)null)
			{
				instance2.RefreshButtons();
			}
		}

		private void RefreshAppearance()
		{
			bool active = SailmakerSession.Active;
			if (!hasShownState || active != shownActive)
			{
				ShipyardUI instance = ShipyardUI.instance;
				if ((Object)(object)label != (Object)null)
				{
					label.text = (active ? "X Sail Maker" : "Sail Maker");
				}
				if ((Object)(object)buttonRenderer != (Object)null && (Object)(object)instance != (Object)null)
				{
					buttonRenderer.sharedMaterial = (active ? instance.darkParchmentMaterial : instance.parchmentMaterial);
				}
				hasShownState = (Object)(object)instance != (Object)null;
				shownActive = active;
			}
		}
	}
	[HarmonyPatch(typeof(PrefabsDirectory), "Start")]
	internal static class PrefabsDirectoryPatch
	{
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		private static void Prefix(PrefabsDirectory __instance)
		{
			SailpackFactory.EnsureRegistered(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void Postfix(PrefabsDirectory __instance)
		{
			SailpackFactory.PopulateItemCache(__instance);
		}
	}
	[HarmonyPatch(typeof(SaveablePrefab), "Load")]
	internal static class ActivateLoadedSailPackagePatch
	{
		[HarmonyPostfix]
		private static void Postfix(SaveablePrefab __instance)
		{
			if (!((Object)(object)__instance == (Object)null) && !((Component)__instance).gameObject.activeSelf && !((Object)(object)((Component)__instance).GetComponent<SailpackData>() == (Object)null))
			{
				((Component)__instance).gameObject.SetActive(true);
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)($"Activated loaded sail package {__instance.instanceId} " + $"from prefab {__instance.prefabIndex}."));
				}
			}
		}
	}
	[HarmonyPatch(typeof(SaveLoadManager), "SaveModData")]
	internal static class SaveModDataPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			SailpackPersistence.Save();
		}
	}
	[HarmonyPatch(typeof(SaveLoadManager), "LoadModData")]
	internal static class LoadModDataPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			SailpackPersistence.Load();
		}
	}
	[HarmonyPatch(typeof(ShipItem), "UpdateLookText")]
	internal static class SailpackLookTextPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ShipItem __instance)
		{
			SailpackData component = ((Component)__instance).GetComponent<SailpackData>();
			if ((Object)(object)component != (Object)null && component.HasRecord)
			{
				((GoPointerButton)__instance).lookText = component.Record.GetDisplayName();
			}
		}
	}
	[HarmonyPatch(typeof(PickupableItemCollisionChecker), "GetDecollision")]
	internal static class SailPackageBigItemDecollisionPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(ShipItem ___item, ref Vector3 __result)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			SailpackData sailpackData = (((Object)(object)___item != (Object)null) ? ((Component)___item).GetComponent<SailpackData>() : null);
			if ((Object)(object)sailpackData == (Object)null || !sailpackData.SuppressBigItemDecollision)
			{
				return true;
			}
			__result = Vector3.zero;
			return false;
		}
	}
	[HarmonyPatch(typeof(GoPointer), "PickUpItem")]
	internal static class SailPackageHeldLayerPatch
	{
		[HarmonyPostfix]
		private static void Postfix(PickupableItem item)
		{
			SailpackData sailpackData = (((Object)(object)item != (Object)null) ? ((Component)item).GetComponent<SailpackData>() : null);
			if (!((Object)(object)sailpackData == (Object)null))
			{
				Transform[] componentsInChildren = ((Component)sailpackData).GetComponentsInChildren<Transform>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					((Component)componentsInChildren[i]).gameObject.layer = 2;
				}
				ShipItem val = (ShipItem)(object)((item is ShipItem) ? item : null);
				if ((Object)(object)val?.itemRigidbodyC != (Object)null)
				{
					((Component)val.itemRigidbodyC).gameObject.layer = 2;
				}
			}
		}
	}
	[HarmonyPatch(typeof(GoPointer), "DropItem")]
	internal static class SailPackageDroppedLayerPatch
	{
		[HarmonyPrefix]
		private static void Prefix(GoPointer __instance, out SailpackData __state)
		{
			PickupableItem heldItem = __instance.GetHeldItem();
			__state = (((Object)(object)heldItem != (Object)null) ? ((Component)heldItem).GetComponent<SailpackData>() : null);
		}

		[HarmonyPostfix]
		private static void Postfix(SailpackData __state)
		{
			if (!((Object)(object)__state == (Object)null))
			{
				Transform[] componentsInChildren = ((Component)__state).GetComponentsInChildren<Transform>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					((Component)componentsInChildren[i]).gameObject.layer = 0;
				}
				ShipItem component = ((Component)__state).GetComponent<ShipItem>();
				if ((Object)(object)component?.itemRigidbodyC != (Object)null)
				{
					((Component)component.itemRigidbodyC).gameObject.layer = 2;
				}
			}
		}
	}
	internal static class SailpackFactory
	{
		internal const int StandardDonorPrefabIndex = 219;

		internal const int SmallDonorPrefabIndex = 221;

		internal const int LegacyPrefabIndex = 390;

		internal const int StandardPrefabIndex = 600;

		internal const int SmallPrefabIndex = 601;

		internal const float SmallPackageMaximumMass = 25f;

		private static GameObject templateHolder;

		private static GameObject legacyPrefab;

		private static GameObject standardPrefab;

		private static GameObject smallPrefab;

		private static bool registrationLogged;

		internal static bool EnsureRegistered(PrefabsDirectory directory)
		{
			if ((Object)(object)directory == (Object)null || directory.directory == null)
			{
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogError((object)"Cannot register sail packages: the prefab directory is unavailable.");
				}
				return false;
			}
			if (!HasDonor(directory, 219, "standard") || !HasDonor(directory, 221, "small"))
			{
				return false;
			}
			if (directory.directory.Length <= 601)
			{
				Array.Resize(ref directory.directory, 602);
			}
			if (!CanClaimSlot(directory, 390, legacyPrefab) || !CanClaimSlot(directory, 600, standardPrefab) || !CanClaimSlot(directory, 601, smallPrefab))
			{
				return false;
			}
			if ((Object)(object)legacyPrefab == (Object)null)
			{
				legacyPrefab = BuildPrefab(directory.directory[219], 390);
			}
			if ((Object)(object)standardPrefab == (Object)null)
			{
				standardPrefab = BuildPrefab(directory.directory[219], 600);
			}
			if ((Object)(object)smallPrefab == (Object)null)
			{
				smallPrefab = BuildPrefab(directory.directory[221], 601);
			}
			directory.directory[390] = legacyPrefab;
			directory.directory[600] = standardPrefab;
			directory.directory[601] = smallPrefab;
			if (!registrationLogged)
			{
				registrationLogged = true;
				ManualLogSource log2 = SwappableStaysailPlugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)("Registered sail package prefabs: " + $"legacy loader={390}, " + $"standard={600} (donor {219}), " + $"small={601} (donor {221})."));
				}
			}
			return true;
		}

		internal static void PopulateItemCache(PrefabsDirectory directory)
		{
			if (EnsureRegistered(directory))
			{
				if (directory.shipItems == null)
				{
					directory.shipItems = (ShipItem[])(object)new ShipItem[directory.directory.Length];
				}
				else if (directory.shipItems.Length < directory.directory.Length)
				{
					Array.Resize(ref directory.shipItems, directory.directory.Length);
				}
				directory.shipItems[390] = legacyPrefab.GetComponent<ShipItem>();
				directory.shipItems[600] = standardPrefab.GetComponent<ShipItem>();
				directory.shipItems[601] = smallPrefab.GetComponent<ShipItem>();
			}
		}

		internal static SailpackData CreateStaged(SailpackRecord record, Vector3 position, Quaternion rotation, bool registerToSave, Mast runtimeTarget = null)
		{
			//IL_003b: 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)
			if (record == null || (Object)(object)PrefabsDirectory.instance == (Object)null || !EnsureRegistered(PrefabsDirectory.instance))
			{
				return null;
			}
			GameObject val = null;
			SaveablePrefab val2 = null;
			try
			{
				val = Object.Instantiate<GameObject>(UsesSmallPackage(record.packageMass) ? smallPrefab : standardPrefab, position, rotation);
				val.SetActive(false);
				SailpackData component = val.GetComponent<SailpackData>();
				component.Initialize(record, runtimeTarget);
				if (registerToSave)
				{
					val2 = val.GetComponent<SaveablePrefab>();
					val2.RegisterToSave();
					SailpackPersistence.Register(val2.instanceId, record);
				}
				return component;
			}
			catch (Exception arg)
			{
				if ((Object)(object)val2 != (Object)null && val2.instanceId > 0)
				{
					SailpackPersistence.Remove(val2.instanceId);
					TryUnregister(val2, "staging failure");
				}
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogError((object)$"Could not stage a sail package: {arg}");
				}
				return null;
			}
		}

		internal static void ActivateStaged(SailpackData data)
		{
			if ((Object)(object)data != (Object)null)
			{
				((Component)data).gameObject.SetActive(true);
			}
		}

		internal static void DiscardStaged(SailpackData data, bool unregisterFromSave)
		{
			if ((Object)(object)data == (Object)null)
			{
				return;
			}
			if (unregisterFromSave)
			{
				SaveablePrefab component = ((Component)data).GetComponent<SaveablePrefab>();
				if ((Object)(object)component != (Object)null && component.instanceId > 0)
				{
					SailpackPersistence.Remove(component.instanceId);
					TryUnregister(component, "staged-package rollback");
				}
			}
			Object.Destroy((Object)(object)((Component)data).gameObject);
		}

		private static void TryUnregister(SaveablePrefab saveable, string context)
		{
			try
			{
				saveable.Unregister();
			}
			catch (Exception ex)
			{
				ManualLogSource log = SwappableStaysailPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Could not unregister a sail package during " + context + ": " + ex));
				}
			}
		}

		internal static void Dispose()
		{
			PrefabsDirectory instance = PrefabsDirectory.instance;
			if ((Object)(object)instance != (Object)null)
			{
				UnregisterPrefab(instance, 390, legacyPrefab);
				UnregisterPrefab(instance, 600, standardPrefab);
				UnregisterPrefab(instance, 601, smallPrefab);
			}
			if ((Object)(object)templateHolder != (Object)null)
			{
				Object.Destroy((Object)(object)templateHolder);
			}
			templateHolder = null;
			legacyPrefab = null;
			standardPrefab = null;
			smallPrefab = null;
			registrationLogged = false;
		}

		private static bool HasDonor(PrefabsDirectory directory, int donorIndex, string packageKind)
		{
			if (directory.directory.Length > donorIndex && (Object)(object)directory.directory[donorIndex] != (Object)null)
			{
				return true;
			}
			ManualLogSource log = SwappableStaysailPlugin.Log;
			if (log != null)
			{
				log.LogError((object)("Cannot register sail packages: " + packageKind + " package donor " + $"{donorIndex} is unavailable."));
			}
			return false;
		}

		private static bool CanClaimSlot(PrefabsDirectory directory, int prefabIndex, GameObject ownedPrefab)
		{
			GameObject val = directory.directory[prefabIndex];
			if ((Object)(object)val == (Object)null || (Object)(object)val == (Object)(object)ownedPrefab || (Object)(object)val.GetComponent<SailpackData>() != (Object)null)
			{
				return true;
			}
			ManualLogSource log = SwappableStaysailPlugin.Log;
			if (log != null)
			{
				log.LogError((object)($"Cannot register sail package: prefab index {prefabIndex} is " + "occupied by '" + ((Object)val).name + "'."));
			}
			return false;
		}

		private static bool UsesSmallPackage(float packageMass)
		{
			if (!float.IsNaN(packageMass) && !float.IsInfinity(packageMass))
			{
				return packageMass <= 25f;
			}
			return false;
		}

		private static void UnregisterPrefab(PrefabsDirectory d