Decompiled source of ShipSort v2.2.2

baer1.ShipSort.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ChatCommandAPI;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("baer1.ShipSort")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("2.2.2.0")]
[assembly: AssemblyInformationalVersion("2.2.2+459e0490f2a99000b01e6cbf71a8a389bb95377a")]
[assembly: AssemblyProduct("LethalShipSort")]
[assembly: AssemblyTitle("baer1.ShipSort")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.2.2.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 LethalShipSort
{
	public struct ItemPosition
	{
		public Vector3 position;

		public GameObject? parentTo;

		public ItemPosition(string s)
		{
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: 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)
			parentTo = null;
			Match match = new Regex("(?:([\\w/\\\\]+):)?(?:([\\d-.]+),){2}([\\d-.]+)$", RegexOptions.Multiline).Match(s);
			if (!match.Success)
			{
				throw new ArgumentException("Invalid format");
			}
			StringBuilder stringBuilder = new StringBuilder(">> ItemPosition init \"" + s + "\"");
			if (!float.TryParse(match.Groups[2].Captures[0].Value, out var result) || !float.TryParse(match.Groups[2].Captures[1].Value, out var result2) || !float.TryParse(match.Groups[3].Value, out var result3))
			{
				throw new ArgumentException("Invalid float");
			}
			position = new Vector3(result, result2, result3);
			stringBuilder.Append($"\n   position is {position}");
			if (match.Groups[1].Success)
			{
				switch (match.Groups[1].Value.ToLower().Trim('/', '\\'))
				{
				case "cupboard":
				case "closet":
					stringBuilder.Append("\n   parent object is closet");
					parentTo = GameObject.Find("Environment/HangarShip/StorageCloset");
					if ((Object)(object)parentTo == (Object)null)
					{
						throw new Exception("Storage closet not found");
					}
					break;
				case "file":
				case "cabinet":
				case "cabinets":
				case "file_cabinet":
				case "file_cabinets":
				case "filecabinet":
				case "filecabinets":
					stringBuilder.Append("\n   parent object is file cabinet");
					parentTo = GameObject.Find("Environment/HangarShip/FileCabinet");
					if ((Object)(object)parentTo == (Object)null)
					{
						throw new Exception("File cabinet not found");
					}
					break;
				case "ship":
					stringBuilder.Append("\n   parent object is ship");
					parentTo = null;
					break;
				case "environment":
				case "none":
					stringBuilder.Append("\n   parent object is none (environment)");
					parentTo = GameObject.Find("Environment");
					if ((Object)(object)parentTo == (Object)null)
					{
						throw new Exception("Environment not found, what the actual fuck");
					}
					break;
				default:
					stringBuilder.Append("\n   parent object is custom (" + match.Groups[1].Value + ") ");
					parentTo = GameObject.Find(match.Groups[1].Value);
					if ((Object)(object)parentTo == (Object)null)
					{
						throw new ArgumentException("Invalid parent object");
					}
					stringBuilder.Append(((object)parentTo).ToString());
					break;
				}
			}
			else
			{
				stringBuilder.Append("\n   parent object not specified");
			}
			LethalShipSort.Logger.LogDebug((object)stringBuilder.ToString());
		}

		public override string ToString()
		{
			string text = "";
			if ((Object)(object)parentTo != (Object)null)
			{
				text = ((Object)parentTo).name;
				Transform parent = parentTo.transform.parent;
				while ((Object)(object)parent != (Object)null)
				{
					text = ((Object)parent).name + "/" + text;
					parent = parent.parent;
				}
				text += ":";
			}
			return text + $"{position.x},{position.y},{position.z}";
		}
	}
	[BepInPlugin("baer1.ShipSort", "LethalShipSort", "2.2.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class LethalShipSort : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(NetworkManager), "StartClient")]
		[HarmonyPatch(typeof(NetworkManager), "StartServer")]
		[HarmonyPatch(typeof(NetworkManager), "StartHost")]
		internal class RoundOverrideResetPatch
		{
			private static void Postfix()
			{
				int count = Instance.roundOverrides.Count;
				Instance.roundOverrides.Clear();
				Logger.LogDebug((object)$"roundOverrides cleared (was {count} items, now {Instance.roundOverrides.Count})");
			}
		}

		private ConfigEntry<bool> autoSort = null;

		private ConfigEntry<string> excludeItems = null;

		private ConfigEntry<bool> useRaycast = null;

		private ConfigEntry<uint> sortDelay = null;

		private ConfigEntry<string> defaultOneHand = null;

		private ConfigEntry<string> defaultTwoHand = null;

		private ConfigEntry<string> defaultTool = null;

		private ConfigEntry<string> customItemPositions = null;

		internal Dictionary<string, ConfigEntry<string>> itemPositions = new Dictionary<string, ConfigEntry<string>>();

		internal Dictionary<string, string> vanillaItems = new Dictionary<string, string>();

		internal Dictionary<string, (Vector3, GameObject?)> roundOverrides = new Dictionary<string, (Vector3, GameObject)>();

		private const float CUPBOARD_ABOVE = 3.2f;

		private const float CUPBOARD_TOP = 2.4f;

		private const float CUPBOARD_MIDDLE_1 = 2f;

		private const float CUPBOARD_MIDDLE_2 = 1.5f;

		private const float CUPBOARD_BOTTOM = 0.5f;

		public static LethalShipSort Instance { get; private set; }

		internal static ManualLogSource Logger { get; private set; }

		internal static Harmony? Harmony { get; set; }

		public bool AutoSort
		{
			get
			{
				return autoSort.Value;
			}
			set
			{
				autoSort.Value = value;
			}
		}

		public string[] ExcludeItems
		{
			get
			{
				return excludeItems.Value.Split(",");
			}
			set
			{
				excludeItems.Value = GeneralExtensions.Join<string>((IEnumerable<string>)value, (Func<string, string>)null, ",");
			}
		}

		public bool UseRaycast
		{
			get
			{
				return useRaycast.Value;
			}
			set
			{
				useRaycast.Value = value;
			}
		}

		public uint SortDelay
		{
			get
			{
				return sortDelay.Value;
			}
			set
			{
				sortDelay.Value = value;
			}
		}

		public ItemPosition DefaultOneHand
		{
			get
			{
				try
				{
					return new ItemPosition(defaultOneHand.Value);
				}
				catch (ArgumentException)
				{
					Logger.LogError((object)("Invalid DefaultOneHand position (" + defaultOneHand.Value + "), using fallback"));
					return new ItemPosition((string)((ConfigEntryBase)defaultOneHand).DefaultValue);
				}
			}
			set
			{
				defaultOneHand.Value = value.ToString();
			}
		}

		public ItemPosition DefaultTwoHand
		{
			get
			{
				try
				{
					return new ItemPosition(defaultTwoHand.Value);
				}
				catch (ArgumentException)
				{
					Logger.LogError((object)("Invalid DefaultTwoHand position (" + defaultTwoHand.Value + "), using fallback"));
					return new ItemPosition((string)((ConfigEntryBase)defaultTwoHand).DefaultValue);
				}
			}
			set
			{
				defaultTwoHand.Value = value.ToString();
			}
		}

		public ItemPosition DefaultTool
		{
			get
			{
				try
				{
					return new ItemPosition(defaultTool.Value);
				}
				catch (ArgumentException)
				{
					Logger.LogError((object)("Invalid DefaultTool position (" + defaultTool.Value + "), using fallback"));
					return new ItemPosition((string)((ConfigEntryBase)defaultTool).DefaultValue);
				}
			}
			set
			{
				defaultTool.Value = value.ToString();
			}
		}

		public Dictionary<string, ItemPosition> CustomItemPositions
		{
			get
			{
				Dictionary<string, ItemPosition> dictionary = new Dictionary<string, ItemPosition>();
				string[] array = customItemPositions.Value.Split(';');
				foreach (string text in array)
				{
					string[] array2 = text.Split(':', 2);
					if (array2.Length != 2)
					{
						Logger.LogDebug((object)"split.Length != 2");
						goto IL_00bf;
					}
					if (dictionary.ContainsKey(array2[0]))
					{
						Logger.LogWarning((object)("Multiple CustomItemPositions for item " + array2[0]));
					}
					try
					{
						dictionary[array2[0]] = new ItemPosition(array2[1]);
					}
					catch (ArgumentException arg)
					{
						Logger.LogDebug((object)$"{array2[0]} {array2[1]} {arg}");
						goto IL_00bf;
					}
					continue;
					IL_00bf:
					Logger.LogError((object)("Invalid CustomItemPosition (" + text + ")"));
				}
				return dictionary;
			}
			set
			{
				customItemPositions.Value = GeneralExtensions.Join<string>(value.Select<KeyValuePair<string, ItemPosition>, string>((KeyValuePair<string, ItemPosition> kvp) => $"{kvp.Key}:{kvp.Value}"), (Func<string, string>)null, ";");
			}
		}

		public Dictionary<string, ItemPosition?> VanillaItemPositions
		{
			get
			{
				Dictionary<string, ItemPosition?> dictionary = new Dictionary<string, ItemPosition?>();
				foreach (KeyValuePair<string, ConfigEntry<string>> itemPosition in itemPositions)
				{
					try
					{
						dictionary[itemPosition.Key] = ((itemPosition.Value.Value == "") ? null : new ItemPosition?(new ItemPosition(itemPosition.Value.Value)));
					}
					catch (ArgumentException)
					{
						Logger.LogError((object)("Invalid item position for " + itemPosition.Key + " (" + itemPosition.Value.Value + "), using fallback"));
						dictionary[itemPosition.Key] = (((string)((ConfigEntryBase)itemPosition.Value).DefaultValue == "") ? null : new ItemPosition?(new ItemPosition((string)((ConfigEntryBase)itemPosition.Value).DefaultValue)));
					}
				}
				return dictionary;
			}
		}

		public ItemPosition GetPosition(GrabbableObject item)
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			string text = Utils.RemoveClone(((Object)item).name);
			ItemPosition? itemPosition = null;
			Logger.LogDebug((object)$">> GetPosition({item}) itemName:{text} isScrap:{item.itemProperties.isScrap} twoHanded:{item.itemProperties.twoHanded}");
			ConfigEntry<string> value2;
			ItemPosition value3;
			if (roundOverrides.TryGetValue(text.ToLower(), out (Vector3, GameObject) value))
			{
				itemPosition = new ItemPosition
				{
					position = value.Item1,
					parentTo = value.Item2
				};
				Logger.LogDebug((object)$"<< GetPosition (roundOverrides) {itemPosition} ({value.Item1}, {value.Item2})");
			}
			else if (itemPositions.TryGetValue(text, out value2))
			{
				try
				{
					if (!Utility.IsNullOrWhiteSpace(value2.Value))
					{
						itemPosition = new ItemPosition(value2.Value);
						Logger.LogDebug((object)$"<< GetPosition (itemPositions) {itemPosition} ({value2.Value})");
					}
				}
				catch (ArgumentException)
				{
					Logger.LogError((object)("Invalid item position for " + text + " (" + value2.Value + "), using fallback"));
					if (!Utility.IsNullOrWhiteSpace((string)((ConfigEntryBase)value2).DefaultValue))
					{
						itemPosition = new ItemPosition((string)((ConfigEntryBase)value2).DefaultValue);
						Logger.LogDebug((object)$"<< GetPosition (itemPositions - DefaultValue) {itemPosition} ({((ConfigEntryBase)value2).DefaultValue})");
					}
				}
			}
			else if (CustomItemPositions.TryGetValue(text, out value3))
			{
				itemPosition = value3;
				Logger.LogDebug((object)$"<< GetPosition (CustomItemPositions) {itemPosition}");
			}
			if (!itemPosition.HasValue)
			{
				itemPosition = ((!item.itemProperties.isScrap) ? DefaultTool : (item.itemProperties.twoHanded ? DefaultTwoHand : DefaultOneHand));
				Logger.LogDebug((object)string.Format("<< GetPosition ({0}) {1}", (!item.itemProperties.isScrap) ? "DefaultTool" : (item.itemProperties.twoHanded ? "DefaultTwoHand" : "DefaultOneHand"), itemPosition));
			}
			return itemPosition.Value;
		}

		private void Awake()
		{
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			autoSort = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AutoSort", false, "Whether to automatically sort the ship when leaving a planet (toggle ingame with /autosort)");
			useRaycast = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "UseRaycast", true, "If enabled, items will be put on the closest surface below the given position, instead of the exact coordinates");
			sortDelay = ((BaseUnityPlugin)this).Config.Bind<uint>("General", "SortDelay", 0u, "The amount of milliseconds to wait between moving items, mostly for the satisfying visual effect.\nYou can't pick anything up while sorting items.");
			BindItemPositionConfigs();
			Patch();
			new SortItemsCommand();
			new AutoSortToggle();
			new SetItemPositionCommand();
			Logger.LogInfo((object)"baer1.ShipSort v2.2.2 has loaded!");
		}

		private void BindItemPositionConfigs()
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_043d: Unknown result type (might be due to invalid IL or missing references)
			//IL_046c: Unknown result type (might be due to invalid IL or missing references)
			//IL_055c: Unknown result type (might be due to invalid IL or missing references)
			//IL_059d: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_062a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0659: Unknown result type (might be due to invalid IL or missing references)
			//IL_0688: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0710: Unknown result type (might be due to invalid IL or missing references)
			//IL_073f: Unknown result type (might be due to invalid IL or missing references)
			//IL_076e: Unknown result type (might be due to invalid IL or missing references)
			//IL_07c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_081f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0849: Unknown result type (might be due to invalid IL or missing references)
			//IL_0878: Unknown result type (might be due to invalid IL or missing references)
			excludeItems = ((BaseUnityPlugin)this).Config.Bind<string>("Items", "ExcludeItems", "", "Comma-separated list of item names to never sort (by internal name)");
			defaultOneHand = ((BaseUnityPlugin)this).Config.Bind<string>("Items", "DefaultOneHand", "-2.25,2,-5.25", "Default position for one-handed items.");
			defaultTwoHand = ((BaseUnityPlugin)this).Config.Bind<string>("Items", "DefaultTwoHand", "-4.5,3,-5.25", "Default position for two-handed items.");
			defaultTool = ((BaseUnityPlugin)this).Config.Bind<string>("Items", "DefaultTool", $"cupboard:-2,0.6,{0.5f}", "Default position for tool items.");
			ItemPositionConfig("Airhorn");
			ItemPositionConfig("LungApparatus", "Apparatice", new Vector3(-6.8f, 4.4f, -6.65f));
			itemPositions["LungApparatusTurnedOff"] = itemPositions["LungApparatus"];
			ItemPositionConfig("HandBell", "Brass bell");
			ItemPositionConfig("BigBolt", "Big bolt");
			ItemPositionConfig("BinFullOfBottles", "Bottles");
			ItemPositionConfig("Hairbrush", "Hair brush");
			ItemPositionConfig("Candy");
			ItemPositionConfig("CashRegisterItem", "Cash register");
			ItemPositionConfig("ChemicalJug", "Chemical jug");
			ItemPositionConfig("Clock");
			ItemPositionConfig("Clownhorn", "Clown horn");
			ItemPositionConfig("ComedyMask", "Comedy");
			ItemPositionConfig("ControlPad", "Control pad");
			ItemPositionConfig("CookieMoldPan", "Cookie mold pan");
			ItemPositionConfig("Dustpan", "Dust pan");
			ItemPositionConfig("EasterEgg", "Easter egg");
			ItemPositionConfig("KiwiBabyItem", "Egg", new Vector3(4.85f, 2f, -4f));
			ItemPositionConfig("EggBeater", "Egg beater");
			ItemPositionConfig("FancyLamp", "Fancy lamp");
			ItemPositionConfig("Flask");
			ItemPositionConfig("GarbageLid", "Garbage lid");
			ItemPositionConfig("GiftBox", "Gift box");
			ItemPositionConfig("GoldBar", "Gold Bar");
			ItemPositionConfig("FancyGlass", "Golden cup");
			ItemPositionConfig("Hairdryer");
			ItemPositionConfig("RedLocustHive", "Bee hive", new Vector3(-6.8f, 4.4f, -5.65f));
			ItemPositionConfig("DiyFlashbang", "Homemade Flashbang");
			ItemPositionConfig("PickleJar", "Jar of pickles");
			ItemPositionConfig("KnifeItem", "Kitchen knife");
			ItemPositionConfig("Cog", "Large axle");
			ItemPositionConfig("LaserPointer", "Laser pointer");
			ItemPositionConfig("Magic7Ball", "Magic 7 ball");
			ItemPositionConfig("MagnifyingGlass", "Magnifying glass");
			ItemPositionConfig("MetalSheet", "Tattered metal sheet");
			ItemPositionConfig("Mug", "Coffee mug");
			ItemPositionConfig("OldPhone", "Old phone");
			ItemPositionConfig("Painting");
			ItemPositionConfig("PerfumeBottle", "Perfume bottle");
			ItemPositionConfig("PillBottle", "Pill bottle");
			ItemPositionConfig("PlasticCup", "Plastic cup");
			ItemPositionConfig("FishTestProp", "Plastic fish");
			ItemPositionConfig("RedSodaCan", "Red soda");
			ItemPositionConfig("Remote");
			ItemPositionConfig("FancyRing", "Wedding ring");
			ItemPositionConfig("RubberDucky", "Rubber ducky");
			ItemPositionConfig("ShotgunItem", "Double-barrel", new Vector3(8.75f, 2f, -5.5f));
			ItemPositionConfig("SoccerBall", "Soccer ball", new Vector3(-6.8f, 4.4f, -7.75f));
			ItemPositionConfig("SteeringWheel", "Steering wheel");
			ItemPositionConfig("StopSign", "Stop sign");
			ItemPositionConfig("TeaKettle", "Tea Kettle");
			ItemPositionConfig("Dentures", "Teeth");
			ItemPositionConfig("ToiletPaperRolls", "Toilet paper");
			ItemPositionConfig("Toothpaste");
			ItemPositionConfig("ToyCube", "Toy cube");
			ItemPositionConfig("RobotToy", "Robot Toy");
			ItemPositionConfig("ToyTrain", "Toy train");
			ItemPositionConfig("TragedyMask", "Tragedy");
			ItemPositionConfig("EnginePart", "V-type engine");
			ItemPositionConfig("WhoopieCushion", "Whoopie cushion", new Vector3(9f, 2f, -8.25f));
			ItemPositionConfig("YieldSign", "Yield sign");
			ItemPositionConfig("ZeddogPlushie", "Zed Dog", new Vector3(9f, 1.21f, -5.55f));
			ItemPositionConfig("WalkieTalkie", "Walkie-talkie", new Vector3(-1.4f, 0.6f, 2.4f), isTool: true);
			ItemPositionConfig("BBFlashlight", "Flashlight", new Vector3(-1.3f, 0.2f, 2f), isTool: true);
			ItemPositionConfig("ShovelItem", "Shovel", new Vector3(-1.5f, 0.3f, 1.5f), isTool: true);
			ItemPositionConfig("LockPickerItem", "Lockpicker", new Vector3(-2f, 0.5f, 2.4f), isTool: true);
			ItemPositionConfig("FlashlightItem", "Pro-flashlight", new Vector3(-1.3f, 0.65f, 2f), isTool: true);
			ItemPositionConfig("StunGrenade", "Stun grenade", new Vector3(-1.2f, 0.5f, 2f), isTool: true);
			ItemPositionConfig("Boombox", new Vector3(-0.3f, 0.5f, 3.2f), isTool: true);
			ItemPositionConfig("TZPChemical", "TZP-Inhalant", new Vector3(-0.55f, 0.2f, 2f), isTool: true);
			ItemPositionConfig("PatcherGunItem", "Zap gun", new Vector3(-1.1f, 0.6f, 2.4f), isTool: true);
			ItemPositionConfig("JetpackItem", "Jetpack", new Vector3(-0.3f, 0.2f, 0.5f), isTool: true);
			ItemPositionConfig("ExtensionLadderItem", "Extension ladder", isTool: true);
			ItemPositionConfig("RadarBoosterDevice", "Radar booster", isTool: true);
			ItemPositionConfig("SprayPaintItem", "Spray paint", new Vector3(-1.7f, 0.5f, 2f), isTool: true);
			ItemPositionConfig("WeedKillerItem", "Weed killer", new Vector3(-2.05f, 0.5f, 2f), isTool: true);
			ItemPositionConfig("BeltBagItem", "Belt bag", new Vector3(-0.35f, 0.5f, 2.3000002f), isTool: true);
			ItemPositionConfig("Key", new Vector3(-0.3f, 0.6f, 1.5f), isTool: true);
			ItemPositionConfig("ShotgunShell", "Shotgun Shell", new Vector3(-0.3f, 0.6f, 2f), isTool: true);
			customItemPositions = ((BaseUnityPlugin)this).Config.Bind<string>("Items", "CustomItemPositions", "MyItem1:0,0,0;MyItem2:cupboard:1.5,-2,3", "Semicolon-separated list of internal item names and their positions.");
		}

		[Obsolete]
		private ConfigEntry<string> BindItemPositionConfig(string itemName)
		{
			return ((BaseUnityPlugin)this).Config.Bind<string>("Items", itemName, "", "Position for the " + itemName + " item.");
		}

		private void ItemPositionConfig(string internalName, string itemName, bool isTool = false)
		{
			itemPositions[internalName] = ((BaseUnityPlugin)this).Config.Bind<string>(isTool ? "Tools" : "Scrap", internalName, "", "Position for the " + itemName + " item.");
			vanillaItems[itemName.ToLower()] = internalName.ToLower();
		}

		private void ItemPositionConfig(string itemName, bool isTool = false)
		{
			itemPositions[itemName] = ((BaseUnityPlugin)this).Config.Bind<string>(isTool ? "Tools" : "Scrap", itemName, "", "Position for the " + itemName + " item.");
			vanillaItems[itemName.ToLower()] = itemName.ToLower();
		}

		private void ItemPositionConfig(string internalName, string itemName, Vector3 defaultPosition, bool isTool = false, bool? defaultInCupboard = null)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			itemPositions[internalName] = ((BaseUnityPlugin)this).Config.Bind<string>(isTool ? "Tools" : "Scrap", internalName, string.Format("{0}{1},{2},{3}", defaultInCupboard.GetValueOrDefault(isTool) ? "cupboard:" : "", Math.Round(defaultPosition.x, 2), Math.Round(defaultPosition.y, 2), Math.Round(defaultPosition.z, 2)), "Position for the " + itemName + " item.");
			vanillaItems[itemName.ToLower()] = internalName.ToLower();
		}

		private void ItemPositionConfig(string itemName, Vector3 defaultPosition, bool isTool = false, bool? defaultInCupboard = null)
		{
			//IL_0044: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			itemPositions[itemName] = ((BaseUnityPlugin)this).Config.Bind<string>(isTool ? "Tools" : "Scrap", itemName, string.Format("{0}{1},{2},{3}", defaultInCupboard.GetValueOrDefault(isTool) ? "cupboard:" : "", Math.Round(defaultPosition.x, 2), Math.Round(defaultPosition.y, 2), Math.Round(defaultPosition.z, 2)), "Position for the " + itemName + " item.");
			vanillaItems[itemName.ToLower()] = itemName.ToLower();
		}

		internal static void Patch()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony = new Harmony("baer1.ShipSort");
			}
			Logger.LogDebug((object)"Patching...");
			Harmony.PatchAll();
			Logger.LogDebug((object)"Finished patching!");
		}
	}
	public class SortItemsCommand : Command
	{
		[HarmonyPatch(typeof(StartOfRound), "SetShipReadyToLand")]
		internal static class AutoSortPatch
		{
			private static void Prefix()
			{
				if (LethalShipSort.Instance.AutoSort && GameNetworkManager.Instance.localPlayerController.isHostPlayerObject)
				{
					AutoSortAllItems();
				}
			}
		}

		internal static Coroutine? sorting;

		public override string Name => "SortItems";

		public override string[] Commands => new string[3]
		{
			((Command)this).Name,
			"Sort",
			"Organize"
		};

		public override string Description => "Sorts all items on the ship\n-a: sort all items, even items on cruiser";

		public override string[] Syntax => new string[3] { "", "[ -a | --all ]", "<item> { here | there } [ once | game | always ]" };

		public override bool Invoke(string[] args, Dictionary<string, string> kwargs, out string error)
		{
			error = "The ship must be in orbit";
			return StartOfRound.Instance.inShipPhase && ((args.Length < 2) ? SortAllItems(args.Contains("-a") || args.Contains("--all"), out error) : SetItemPositionCommand.SetItemPosition(args, out error));
		}

		private static bool SortAllItems(bool all, out string error)
		{
			error = "No items to sort";
			GameNetworkManager.Instance.localPlayerController.DropAllHeldItemsAndSync();
			GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
			if (array == null)
			{
				return false;
			}
			array = array.Where((GrabbableObject i) => i != null && i.playerHeldBy == null && !(i is RagdollGrabbableObject)).ToArray();
			if (array.Length == 0)
			{
				return false;
			}
			ChatCommandAPI.Print("Sorting all items...");
			VehicleController[] cars = Object.FindObjectsOfType<VehicleController>() ?? Array.Empty<VehicleController>();
			GrabbableObject[] array2 = array.Where((GrabbableObject i) => i.itemProperties.isScrap && (all || !(Utils.RemoveClone(((Object)i).name) == "ShotgunItem") || !cars.Any((VehicleController car) => (Object)(object)((Component)i).gameObject.transform.parent == (Object)(object)((Component)car).transform))).ToArray();
			GrabbableObject[] array3 = array.Where((GrabbableObject i) => !i.itemProperties.isScrap && (all || cars.All((VehicleController car) => (Object)(object)((Component)i).gameObject.transform.parent != (Object)(object)((Component)car).gameObject.gameObject.transform))).ToArray();
			if (LethalShipSort.Instance.SortDelay < 10)
			{
				int num = 0;
				int num2 = 0;
				if (array2.Length != 0)
				{
					num = SortItems(array2);
				}
				if (array3.Length != 0)
				{
					num2 = SortItems(array3);
				}
				error = ((num > 0) ? string.Format("{0} scrap items {1}", num, (num2 > 0) ? "and " : "") : "") + ((num2 > 0) ? $"{num2} tool items" : "") + " couldn't be sorted";
				if (num != 0 || num2 != 0)
				{
					return false;
				}
				ChatCommandAPI.Print("Finished sorting items");
			}
			else
			{
				if (sorting != null)
				{
					((MonoBehaviour)GameNetworkManager.Instance.localPlayerController).StopCoroutine(sorting);
				}
				sorting = ((MonoBehaviour)GameNetworkManager.Instance.localPlayerController).StartCoroutine(SortAllItemsDelayed(LethalShipSort.Instance.SortDelay, array2, array3));
			}
			return true;
		}

		private static void AutoSortAllItems()
		{
			try
			{
				GameNetworkManager.Instance.localPlayerController.DropAllHeldItemsAndSync();
				GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
				if (array == null)
				{
					return;
				}
				array = array.Where((GrabbableObject i) => i != null && i.playerHeldBy == null && !(i is RagdollGrabbableObject)).ToArray();
				if (array.Length == 0)
				{
					return;
				}
				ChatCommandAPI.Print("Sorting all items...");
				VehicleController[] cars = Object.FindObjectsOfType<VehicleController>() ?? Array.Empty<VehicleController>();
				GrabbableObject[] array2 = array.Where((GrabbableObject i) => i.itemProperties.isScrap && (!(Utils.RemoveClone(((Object)i).name) == "ShotgunItem") || !cars.Any((VehicleController car) => (Object)(object)((Component)i).gameObject.transform.parent == (Object)(object)((Component)car).transform))).ToArray();
				GrabbableObject[] array3 = array.Where((GrabbableObject i) => !i.itemProperties.isScrap && cars.All((VehicleController car) => (Object)(object)((Component)i).gameObject.transform.parent != (Object)(object)((Component)car).gameObject.gameObject.transform)).ToArray();
				if (LethalShipSort.Instance.SortDelay < 10)
				{
					int num = 0;
					int num2 = 0;
					if (array2.Length != 0)
					{
						num = SortItems(array2);
					}
					if (array3.Length != 0)
					{
						num2 = SortItems(array3);
					}
					if (num != 0 || num2 != 0)
					{
						ChatCommandAPI.PrintError("Automatic sorting failed: " + ((num > 0) ? string.Format("{0} scrap items {1}", num, (num2 > 0) ? "and " : "") : "") + ((num2 > 0) ? $"{num2} tool items" : "") + " couldn't be sorted");
					}
					else
					{
						ChatCommandAPI.Print("Finished sorting items");
					}
				}
				else
				{
					if (sorting != null)
					{
						((MonoBehaviour)GameNetworkManager.Instance.localPlayerController).StopCoroutine(sorting);
					}
					sorting = ((MonoBehaviour)GameNetworkManager.Instance.localPlayerController).StartCoroutine(SortAllItemsDelayed(LethalShipSort.Instance.SortDelay, array2, array3, "Automatic sorting failed"));
				}
			}
			catch (Exception arg)
			{
				ChatCommandAPI.PrintError("Automatic sorting failed due to an internal error, check the log for details");
				LethalShipSort.Logger.LogError((object)$"Error while autosorting items: {arg}");
			}
		}

		public static IEnumerator SortAllItemsDelayed(uint delay, GrabbableObject[] scrap, GrabbableObject[] tools, string errorPrefix = "Error running command")
		{
			int scrapFailed = 0;
			int toolsFailed = 0;
			foreach (GrabbableObject item2 in scrap)
			{
				try
				{
					if (!Utils.MoveItem(item2))
					{
						scrapFailed++;
					}
				}
				catch (Exception e)
				{
					LethalShipSort.Logger.LogError((object)e);
					scrapFailed++;
				}
				yield return (object)new WaitForSeconds((float)delay / 1000f);
			}
			foreach (GrabbableObject item in tools)
			{
				try
				{
					if (!Utils.MoveItem(item))
					{
						toolsFailed++;
					}
				}
				catch (Exception e2)
				{
					LethalShipSort.Logger.LogError((object)e2);
					toolsFailed++;
				}
				yield return (object)new WaitForSeconds((float)delay / 1000f);
			}
			string error = ((scrapFailed > 0) ? string.Format("{0} scrap items {1}", scrapFailed, (toolsFailed > 0) ? "and " : "") : "") + ((toolsFailed > 0) ? $"{toolsFailed} tool items" : "") + " couldn't be sorted";
			if (scrapFailed != 0 || toolsFailed != 0)
			{
				ChatCommandAPI.PrintError(errorPrefix + ": <noparse>" + error + "</noparse>");
			}
			else
			{
				ChatCommandAPI.Print("Finished sorting items");
			}
		}

		public static int SortItems(GrabbableObject[] items)
		{
			return items.Count(delegate(GrabbableObject item)
			{
				try
				{
					return !Utils.MoveItem(item);
				}
				catch (Exception ex)
				{
					LethalShipSort.Logger.LogError((object)ex);
					return true;
				}
			});
		}
	}
	public class SetItemPositionCommand : Command
	{
		public enum where
		{
			here,
			there,
			error
		}

		public enum when
		{
			once,
			game,
			always,
			error
		}

		public override string Name => "SetItemPosition";

		public override string Description => "Sets the position for an item when sorting";

		public override string[] Commands => new string[2]
		{
			"put",
			((Command)this).Name
		};

		public override string[] Syntax => new string[1] { "\"<item>\" { here | there } [ once | game | always ]\nExample: /put \"easter egg\" there always" };

		public override bool Invoke(string[] args, Dictionary<string, string> kwargs, out string error)
		{
			error = "The ship must be in orbit";
			return StartOfRound.Instance.inShipPhase && SetItemPosition(args, out error);
		}

		public static bool SetItemPosition(string[] args, out string error)
		{
			error = "Invalid arguments";
			switch (args.Length)
			{
			case 2:
			{
				string name2 = args[0];
				string text3 = args[1].ToLower();
				if (1 == 0)
				{
				}
				where where = ((!(text3 == "here")) ? ((text3 == "there") ? where.there : where.error) : where.here);
				if (1 == 0)
				{
				}
				return SetItemPosition(name2, where, when.once, out error);
			}
			case 3:
			{
				string name = args[0];
				string text = args[1].ToLower();
				if (1 == 0)
				{
				}
				where where = ((!(text == "here")) ? ((text == "there") ? where.there : where.error) : where.here);
				if (1 == 0)
				{
				}
				where where2 = where;
				string text2 = args[2].ToLower();
				if (1 == 0)
				{
				}
				when when;
				switch (text2)
				{
				case "once":
				case "now":
					when = when.once;
					break;
				case "game":
				case "round":
					when = when.game;
					break;
				case "always":
				case "save":
					when = when.always;
					break;
				default:
					when = when.error;
					break;
				}
				if (1 == 0)
				{
				}
				return SetItemPosition(name, where2, when, out error);
			}
			default:
				return false;
			}
		}

		public static bool SetItemPosition(string name, where where, when when, out string error)
		{
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0333: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_037b: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0373: Unknown result type (might be due to invalid IL or missing references)
			//IL_046f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0462: Unknown result type (might be due to invalid IL or missing references)
			//IL_0467: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			error = "Invalid arguments";
			if (where == where.error || when == when.error)
			{
				return false;
			}
			error = "Invalid item name";
			if (!LethalShipSort.Instance.vanillaItems.TryGetValue(name.ToLower(), out string internalName))
			{
				if (!LethalShipSort.Instance.vanillaItems.ContainsValue(name.ToLower()))
				{
					return false;
				}
				internalName = name;
			}
			LethalShipSort.Logger.LogDebug((object)("internalName: " + internalName + " (" + name + ")"));
			ConfigEntry<string> val = null;
			if (when == when.always)
			{
				if (LethalShipSort.Instance.itemPositions.All<KeyValuePair<string, ConfigEntry<string>>>((KeyValuePair<string, ConfigEntry<string>> kvp) => !string.Equals(kvp.Key, internalName, StringComparison.CurrentCultureIgnoreCase)))
				{
					return false;
				}
				val = LethalShipSort.Instance.itemPositions.First<KeyValuePair<string, ConfigEntry<string>>>((KeyValuePair<string, ConfigEntry<string>> kvp) => string.Equals(kvp.Key, internalName, StringComparison.CurrentCultureIgnoreCase)).Value;
			}
			error = "Error getting position";
			if (!GetPosition(where, out Vector3 position, out GameObject relativeTo))
			{
				return false;
			}
			LethalShipSort.Logger.LogDebug((object)string.Format("position: {0} relative to {1} ({2}, {3})", position, relativeTo, ((Object)(object)relativeTo == (Object)null) ? "null" : Utils.GameObjectPath(relativeTo), ((Object)(object)relativeTo == (Object)null) ? "" : ((string)(object)GameObject.Find(Utils.GameObjectPath(relativeTo)))));
			switch (when)
			{
			case when.once:
			{
				ChatCommandAPI.Print($"Moving all items of type {internalName} to position {(((Object)(object)relativeTo == (Object)null) ? position : relativeTo.transform.InverseTransformPoint(position))}");
				error = "No items to sort";
				GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
				if (array == null)
				{
					return false;
				}
				array = array.Where((GrabbableObject i) => i != null && i.playerHeldBy == null && !(i is RagdollGrabbableObject) && string.Equals(Utils.RemoveClone(((Object)i).name), internalName, StringComparison.CurrentCultureIgnoreCase)).ToArray();
				if (array.Length == 0)
				{
					return false;
				}
				if (LethalShipSort.Instance.SortDelay < 10)
				{
					int num = array.Count(delegate(GrabbableObject item)
					{
						//IL_000e: Unknown result type (might be due to invalid IL or missing references)
						//IL_0013: Unknown result type (might be due to invalid IL or missing references)
						try
						{
							return !Utils.MoveItem(item, new ItemPosition
							{
								position = position,
								parentTo = relativeTo
							});
						}
						catch (Exception ex)
						{
							LethalShipSort.Logger.LogError((object)ex);
							return true;
						}
					});
					error = $"{num} items couldn't be sorted";
					ChatCommandAPI.Print("Finished sorting items");
					return num == 0;
				}
				if (SortItemsCommand.sorting != null)
				{
					((MonoBehaviour)GameNetworkManager.Instance.localPlayerController).StopCoroutine(SortItemsCommand.sorting);
				}
				SortItemsCommand.sorting = ((MonoBehaviour)GameNetworkManager.Instance.localPlayerController).StartCoroutine(SortItemsDelayed(LethalShipSort.Instance.SortDelay, array, position, relativeTo));
				return true;
			}
			case when.game:
				LethalShipSort.Instance.roundOverrides[internalName.ToLower()] = (position, relativeTo);
				ChatCommandAPI.Print($"Items of type {internalName} will be put on position {(((Object)(object)relativeTo == (Object)null) ? position : relativeTo.transform.InverseTransformPoint(position))} for this game");
				break;
			case when.always:
				val.Value = (((Object)(object)relativeTo == (Object)null) ? $"none:{position.x},{position.y},{position.z}" : $"{Utils.GameObjectPath(relativeTo)}:{position.x},{position.y},{position.z}");
				ChatCommandAPI.Print($"Items of type {internalName} will be put on position {(((Object)(object)relativeTo == (Object)null) ? position : relativeTo.transform.InverseTransformPoint(position))}");
				return true;
			}
			return true;
		}

		private static IEnumerator SortItemsDelayed(uint delay, GrabbableObject[] items, Vector3 position, GameObject? relativeTo, string errorPrefix = "Error running command")
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			int itemsFailed = 0;
			foreach (GrabbableObject item in items)
			{
				try
				{
					if (!Utils.MoveItem(item, new ItemPosition
					{
						position = position,
						parentTo = relativeTo
					}))
					{
						itemsFailed++;
					}
				}
				catch (Exception e)
				{
					LethalShipSort.Logger.LogError((object)e);
					itemsFailed++;
				}
				yield return (object)new WaitForSeconds((float)delay / 1000f);
			}
			string error = $"{itemsFailed} items couldn't be sorted";
			if (itemsFailed != 0)
			{
				ChatCommandAPI.PrintError(errorPrefix + ": <noparse>" + error + "</noparse>");
			}
			else
			{
				ChatCommandAPI.Print("Finished sorting items");
			}
		}

		private static bool GetPosition(where where, out Vector3 position, out GameObject? relativeTo)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: 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_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			position = default(Vector3);
			relativeTo = null;
			RaycastHit val = default(RaycastHit);
			switch (where)
			{
			case where.here:
				if (Physics.Raycast(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, Vector3.down, ref val, 80f, 67111680, (QueryTriggerInteraction)1))
				{
					position = ((Component)((RaycastHit)(ref val)).collider).gameObject.transform.InverseTransformPoint(((RaycastHit)(ref val)).point + new Vector3(0f, 0.2f, 0f));
					relativeTo = ((Component)((RaycastHit)(ref val)).collider).gameObject;
					return true;
				}
				break;
			case where.there:
				if (Physics.Raycast(((Component)GameNetworkManager.Instance.localPlayerController.gameplayCamera).transform.position, ((Component)GameNetworkManager.Instance.localPlayerController.gameplayCamera).transform.forward, ref val, 80f, 67111680, (QueryTriggerInteraction)1))
				{
					position = ((Component)((RaycastHit)(ref val)).collider).gameObject.transform.InverseTransformPoint(((RaycastHit)(ref val)).point + new Vector3(0f, 0.2f, 0f));
					relativeTo = ((Component)((RaycastHit)(ref val)).collider).gameObject;
					return true;
				}
				break;
			}
			return false;
		}
	}
	[Obsolete]
	internal class PrintLayerMasks : Command
	{
		public override bool Hidden => true;

		public override bool Invoke(string[] args, Dictionary<string, string> kwargs, out string error)
		{
			LethalShipSort.Logger.LogInfo((object)"LayerMask MoveItemRelativeTo:");
			for (int i = 0; i < 32; i++)
			{
				LethalShipSort.Logger.LogInfo((object)(" " + (((0x10000900u & (uint)(1 << i)) != 0) ? "o" : "-") + " " + LayerMask.LayerToName(i)));
			}
			LethalShipSort.Logger.LogInfo((object)"LayerMask MoveItem:");
			for (int j = 0; j < 32; j++)
			{
				LethalShipSort.Logger.LogInfo((object)(" " + (((0x40000B00u & (uint)(1 << j)) != 0) ? "o" : "-") + " " + LayerMask.LayerToName(j)));
			}
			ChatCommandAPI.Print("layer masks printed to log");
			error = null;
			return true;
		}
	}
	public class AutoSortToggle : ToggleCommand
	{
		public override string Name => "AutoSort";

		public override string ToggleDescription => "Toggles automatic item sorting when leaving a planet";

		public override bool Value
		{
			get
			{
				return LethalShipSort.Instance.AutoSort;
			}
			set
			{
				LethalShipSort.Instance.AutoSort = value;
			}
		}
	}
	public static class Utils
	{
		[Flags]
		internal enum Layers
		{
			Default = 1,
			TransparentFX = 2,
			IgnoreRaycast = 4,
			Player = 8,
			Water = 0x10,
			UI = 0x20,
			Props = 0x40,
			HelmetVisor = 0x80,
			Room = 0x100,
			InteractableObject = 0x200,
			Foliage = 0x400,
			Colliders = 0x800,
			PhysicsObject = 0x1000,
			Triggers = 0x2000,
			MapRadar = 0x4000,
			NavigationSurface = 0x8000,
			MoldSpore = 0x10000,
			Anomaly = 0x20000,
			LineOfSight = 0x40000,
			Enemies = 0x80000,
			PlayerRagdoll = 0x100000,
			MapHazards = 0x200000,
			ScanNode = 0x400000,
			EnemiesNotRendered = 0x800000,
			MiscLevelGeometry = 0x1000000,
			Terrain = 0x2000000,
			PlaceableShipObjects = 0x4000000,
			PlacementBlocker = 0x8000000,
			Railing = 0x10000000,
			DecalStickableSurface = 0x20000000,
			Vehicle = 0x40000000
		}

		private const string CLONE = "(Clone)";

		public static string RemoveClone(string name)
		{
			string result;
			if (!name.EndsWith("(Clone)"))
			{
				result = name;
			}
			else
			{
				int length = "(Clone)".Length;
				result = name.Substring(0, name.Length - length);
			}
			return result;
		}

		public static bool MoveItem(GrabbableObject item)
		{
			return LethalShipSort.Instance.ExcludeItems.Contains(RemoveClone(((Object)item).name)) || MoveItem(item, LethalShipSort.Instance.GetPosition(item));
		}

		public static bool MoveItem(GrabbableObject item, ItemPosition position)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			return ((Object)(object)position.parentTo == (Object)(object)GameObject.Find("Environment/HangarShip/StorageCloset")) ? MoveItem(item, position.position, position.parentTo) : MoveItemRelativeTo(item, position.position, position.parentTo);
		}

		public static bool MoveItemRelativeTo(GrabbableObject item, Vector3 position, GameObject? relativeTo)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: 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_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			LethalShipSort.Logger.LogDebug((object)string.Format(">> Moving item {0} to position {1} relative to {2}", RemoveClone(((Object)item).name), position, ((Object)(object)relativeTo == (Object)null) ? "ship" : RemoveClone(((Object)relativeTo).name)));
			GameObject val = GameObject.Find("Environment/HangarShip");
			if ((Object)(object)val == (Object)null)
			{
				LethalShipSort.Logger.LogWarning((object)"   Couldn't find ship");
				return false;
			}
			if ((Object)(object)relativeTo == (Object)null)
			{
				relativeTo = val;
			}
			if (LethalShipSort.Instance.UseRaycast)
			{
				RaycastHit val2 = default(RaycastHit);
				if (!Physics.Raycast(relativeTo.transform.TransformPoint(position), Vector3.down, ref val2, 80f, 1409288960, (QueryTriggerInteraction)1))
				{
					LethalShipSort.Logger.LogWarning((object)"   Raycast unsuccessful");
					return false;
				}
				position = Randomize(val.transform.InverseTransformPoint(((RaycastHit)(ref val2)).point + item.itemProperties.verticalOffset * Vector3.up));
			}
			else
			{
				position = Randomize(position + item.itemProperties.verticalOffset * Vector3.up);
			}
			GameNetworkManager.Instance.localPlayerController.SetObjectAsNoLongerHeld(true, true, position, item, -1);
			GameNetworkManager.Instance.localPlayerController.ThrowObjectServerRpc(NetworkObjectReference.op_Implicit(((NetworkBehaviour)item).NetworkObject), true, true, position, -1);
			return true;
		}

		public static bool MoveItem(GrabbableObject item, Vector3 position, GameObject parentTo)
		{
			//IL_0016: 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_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			LethalShipSort.Logger.LogDebug((object)$">> Moving item {RemoveClone(((Object)item).name)} to position {position} in {RemoveClone(((Object)parentTo).name)}");
			if (LethalShipSort.Instance.UseRaycast)
			{
				RaycastHit val = default(RaycastHit);
				if (!Physics.Raycast(parentTo.transform.TransformPoint(position), Vector3.down, ref val, 80f, 1073744640, (QueryTriggerInteraction)1))
				{
					LethalShipSort.Logger.LogWarning((object)"   Raycast unsuccessful");
					return false;
				}
				position = parentTo.transform.InverseTransformPoint(Randomize(((RaycastHit)(ref val)).point + item.itemProperties.verticalOffset * Vector3.up - new Vector3(0f, 0.05f, 0f), 0.02f));
			}
			else
			{
				position = Randomize(position + item.itemProperties.verticalOffset * Vector3.up - new Vector3(0f, 0.05f, 0f), 0.02f);
			}
			GameNetworkManager.Instance.localPlayerController.SetObjectAsNoLongerHeld(true, true, position, item, 0);
			GameNetworkManager.Instance.localPlayerController.ThrowObjectServerRpc(NetworkObjectReference.op_Implicit(((NetworkBehaviour)item).NetworkObject), true, true, position, 0);
			GameNetworkManager.Instance.localPlayerController.PlaceGrabbableObject(parentTo.transform, position, false, item);
			GameNetworkManager.Instance.localPlayerController.PlaceObjectServerRpc(NetworkObjectReference.op_Implicit(((NetworkBehaviour)item).NetworkObject), NetworkObjectReference.op_Implicit(parentTo), position, false);
			return true;
		}

		public static Vector3 Randomize(Vector3 position, float maxDistance = 0.05f)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (maxDistance <= 0f)
			{
				throw new ArgumentException("Invalid maxDistance (must be positive)");
			}
			Random random = new Random();
			return new Vector3(position.x + (float)random.NextDouble() * maxDistance * 2f - maxDistance, position.y, position.z + (float)random.NextDouble() * maxDistance * 2f - maxDistance);
		}

		public static string GameObjectPath(GameObject gameObject)
		{
			Transform parent = gameObject.transform.parent;
			string text = ((Object)gameObject).name;
			while ((Object)(object)parent != (Object)null)
			{
				text = ((Object)parent).name + "/" + text;
				parent = ((Component)parent).transform.parent;
			}
			return text;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "baer1.ShipSort";

		public const string PLUGIN_NAME = "LethalShipSort";

		public const string PLUGIN_VERSION = "2.2.2";
	}
}