Decompiled source of MoreCupboards v1.1.1

ScienceBird.MoreCupboards.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LethalLib.Modules;
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: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: AssemblyCompany("ScienceBird.MoreCupboards")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+d4888a145162d3cdc3a1fe038780d264164c7b6d")]
[assembly: AssemblyProduct("MoreCupboards")]
[assembly: AssemblyTitle("ScienceBird.MoreCupboards")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.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 MoreCupboards
{
	public class AddCupboards
	{
		public static AssetBundle CupboardAssets;

		public static ContentLoader ContentLoader;

		public static Dictionary<string, GameObject> Prefabs = new Dictionary<string, GameObject>();

		private static int price = 100;

		public static void RegisterCupboard()
		{
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			if (MoreCupboards.cupboardPrice.Value >= 0)
			{
				price = MoreCupboards.cupboardPrice.Value;
			}
			CupboardAssets = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "cupboardunlockable"));
			ContentLoader = new ContentLoader(MoreCupboards.pluginInfo, CupboardAssets, (Action<CustomContent, GameObject>)delegate(CustomContent content, GameObject prefab)
			{
				Prefabs.Add(content.ID, prefab);
			});
			string text = "";
			if (MoreCupboards.noDoors.Value)
			{
				text = "Alt";
			}
			List<CustomContent> list = new List<CustomContent>();
			for (int i = 1; i <= MoreCupboards.maximumCupboards.Value; i++)
			{
				list.Add((CustomContent)new Unlockable(i + "Cupboard", "Assets/LethalCompany/Mods/MoreCupboards/Cupboard" + i + text + "UnlockableItemDef.asset", price, (string)null, (string)null, "Assets/LethalCompany/Mods/MoreCupboards/CupboardInfo.asset", (StoreType)1, (Action<UnlockableItem>)null));
			}
			CustomContent[] array = list.ToArray();
			ContentLoader.RegisterAll(array);
		}
	}
	[BepInPlugin("ScienceBird.MoreCupboards", "MoreCupboards", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class MoreCupboards : BaseUnityPlugin
	{
		public static PluginInfo pluginInfo;

		public static ConfigFile config;

		public static ConfigEntry<int> cupboardPrice;

		public static ConfigEntry<int> maximumCupboards;

		public static ConfigEntry<bool> noDoors;

		public static MoreCupboards Instance { get; private set; }

		internal static ManualLogSource Logger { get; private set; }

		internal static Harmony? Harmony { get; set; }

		private void Awake()
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			pluginInfo = ((BaseUnityPlugin)this).Info;
			cupboardPrice = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Cupboard Price", 100, "How much it costs to buy cupboards from the store.");
			maximumCupboards = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Maximum Cupboards", 5, new ConfigDescription("Maximum extra cupboards you're allowed to buy for your ship. This is in addition to the vanilla cupboard, so the actual number of cupboards you can have on the ship will be one higher than this.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 5), Array.Empty<object>()));
			noDoors = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "No Doors", false, "Remove doors from purchased cupboards (does not affect vanilla cupboard).");
			AddCupboards.RegisterCupboard();
			Patch();
			Logger.LogInfo((object)"ScienceBird.MoreCupboards v1.0.0 has loaded!");
		}

		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("ScienceBird.MoreCupboards");
			}
			Logger.LogDebug((object)"Patching...");
			Harmony.PatchAll();
			Logger.LogDebug((object)"Finished patching!");
		}

		internal static void Unpatch()
		{
			Logger.LogDebug((object)"Unpatching...");
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			Logger.LogDebug((object)"Finished unpatching!");
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "ScienceBird.MoreCupboards";

		public const string PLUGIN_NAME = "MoreCupboards";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace MoreCupboards.Patches
{
	[HarmonyPatch]
	internal class CupboardMattyFix
	{
		internal struct ClosetHolder
		{
			public readonly UnlockableItem Unlockable;

			public readonly GameObject gameObject;

			public readonly List<ShelfHolder> Shelves;

			public readonly Collider Collider;

			public bool IsInitialized;

			public ClosetHolder(int index)
			{
				Unlockable = null;
				Shelves = null;
				Collider = null;
				IsInitialized = false;
				string indexString = index.ToString();
				if (index == 0)
				{
					indexString = string.Empty;
					gameObject = GameObject.Find("/Environment/HangarShip/StorageCloset");
				}
				else
				{
					gameObject = GameObject.Find("StorageCloset" + indexString + "(Clone)");
					if ((Object)(object)gameObject == (Object)null)
					{
						gameObject = GameObject.Find("StorageCloset" + indexString + "Alt(Clone)");
					}
					if ((Object)(object)gameObject == (Object)null)
					{
						MoreCupboards.Logger.LogDebug((object)("Unable to find specified cupboard! StorageCloset" + indexString));
						return;
					}
				}
				Unlockable = StartOfRound.Instance.unlockablesList.unlockables.Find((UnlockableItem u) => u.unlockableName == indexString + "Cupboard");
				Collider = gameObject.GetComponent<Collider>();
				Shelves = gameObject.GetComponentsInChildren<PlaceableObjectsSurface>().Select(delegate(PlaceableObjectsSurface s)
				{
					ShelfHolder result = default(ShelfHolder);
					result.Shelf = s;
					result.Collider = ((Component)s).GetComponent<Collider>();
					return result;
				}).ToList();
			}
		}

		internal struct ShelfHolder
		{
			public PlaceableObjectsSurface Shelf;

			public Collider Collider;
		}

		[HarmonyPatch(typeof(NetworkBehaviour), "OnNetworkSpawn")]
		internal static class NetworkSpawnPatch
		{
			[HarmonyPostfix]
			[HarmonyPriority(-900)]
			private static void Postfix(NetworkBehaviour __instance)
			{
				//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_010d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0127: Unknown result type (might be due to invalid IL or missing references)
				GrabbableObject val = (GrabbableObject)(object)((__instance is GrabbableObject) ? __instance : null);
				if (val == null || val is ClipboardItem || (val is PhysicsProp && val.itemProperties.itemName == "Sticky note") || (Object.op_Implicit((Object)(object)StartOfRound.Instance.localPlayerController) && !StartOfRoundPatch.IsInitializingGame))
				{
					return;
				}
				try
				{
					val.isInElevator = true;
					val.isInShipRoom = true;
					LungProp val2 = (LungProp)(object)((val is LungProp) ? val : null);
					if (val2 != null)
					{
						val2.isLungDocked = false;
						val2.isLungPowered = false;
						val2.isLungDockedInElevator = false;
						AudioSource component = ((Component)val2).GetComponent<AudioSource>();
						if (component != null)
						{
							component.Stop();
						}
					}
					val.floorYRot = (int)Math.Floor(((Component)val).transform.eulerAngles.y - 90f - (float)val.itemProperties.floorYOffset);
					((Component)val).transform.rotation = Quaternion.Euler(val.itemProperties.restingRotation.x, ((Component)val).transform.eulerAngles.y, val.itemProperties.restingRotation.z);
				}
				catch (Exception arg)
				{
					MoreCupboards.Logger.LogError((object)$"MattyFix: Exception while setting rotation, {arg}");
				}
			}
		}

		[HarmonyPatch]
		internal class StartOfRoundPatch
		{
			internal static bool IsInitializingGame;

			[HarmonyPrefix]
			[HarmonyPatch(typeof(StartOfRound), "Start")]
			private static void MarkServerStart(StartOfRound __instance)
			{
				IsInitializingGame = true;
				((MonoBehaviour)__instance).StartCoroutine(WaitCoupleOfFrames());
			}

			private static IEnumerator WaitCoupleOfFrames()
			{
				yield return (object)new WaitForEndOfFrame();
				yield return (object)new WaitForEndOfFrame();
				yield return (object)new WaitForEndOfFrame();
				IsInitializingGame = false;
			}
		}

		[HarmonyPatch]
		internal class GrabbableStartPatch
		{
			[HarmonyTranspiler]
			[HarmonyPatch(typeof(GrabbableObject), "Start")]
			private static IEnumerable<CodeInstruction> RedirectSpawnOnGroundCheck(IEnumerable<CodeInstruction> instructions)
			{
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0052: Expected O, but got Unknown
				//IL_0069: Unknown result type (might be due to invalid IL or missing references)
				//IL_006f: Expected O, but got Unknown
				//IL_007d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: Expected O, but got Unknown
				//IL_0091: Unknown result type (might be due to invalid IL or missing references)
				//IL_0097: Expected O, but got Unknown
				//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ab: Expected O, but got Unknown
				//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ec: Expected O, but got Unknown
				List<CodeInstruction> list = instructions.ToList();
				FieldInfo fieldInfo = AccessTools.Field(typeof(GrabbableObject), "itemProperties");
				FieldInfo fieldInfo2 = AccessTools.Field(typeof(Item), "itemSpawnsOnGround");
				MethodInfo methodInfo = AccessTools.Method(typeof(GrabbableStartPatch), "NewSpawnOnGroundCheck", (Type[])null, (Type[])null);
				CodeMatcher val = new CodeMatcher((IEnumerable<CodeInstruction>)list, (ILGenerator)null);
				val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[4]
				{
					new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldfld, (object)fieldInfo, (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldfld, (object)fieldInfo2, (string)null),
					new CodeMatch((OpCode?)OpCodes.Brfalse, (object)null, (string)null)
				});
				if (val.IsInvalid)
				{
					return list;
				}
				val.Advance(1);
				val.RemoveInstructions(2);
				val.Insert((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)methodInfo)
				});
				MoreCupboards.Logger.LogDebug((object)"MattyFix: GrabbableObject.Start patched!");
				return val.Instructions();
			}

			private static bool NewSpawnOnGroundCheck(GrabbableObject grabbableObject)
			{
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				MoreCupboards.Logger.LogDebug((object)$"MattyFix: {grabbableObject.itemProperties.itemName}({((NetworkBehaviour)grabbableObject).NetworkObjectId}) processing GrabbableObject pos {((Component)grabbableObject).transform.position}");
				bool flag = ShouldSpawnOnGround(grabbableObject);
				MoreCupboards.Logger.LogDebug((object)($"MattyFix: {grabbableObject.itemProperties.itemName}({((NetworkBehaviour)grabbableObject).NetworkObjectId}) processing GrabbableObject spawnState " + $"OnGround - was: {grabbableObject.itemProperties.itemSpawnsOnGround} new:{flag}"));
				return flag;
			}

			private static bool ShouldSpawnOnGround(GrabbableObject grabbableObject)
			{
				bool itemSpawnsOnGround = grabbableObject.itemProperties.itemSpawnsOnGround;
				if (grabbableObject is ClipboardItem || (grabbableObject is PhysicsProp && grabbableObject.itemProperties.itemName == "Sticky note"))
				{
					return itemSpawnsOnGround;
				}
				itemSpawnsOnGround = ((NetworkBehaviour)StartOfRound.Instance).IsServer;
				if (_closet != null)
				{
					foreach (ClosetHolder item in _closet)
					{
						if ((Object)(object)((Component)grabbableObject).transform.parent == (Object)(object)item.gameObject.transform)
						{
							MoreCupboards.Logger.LogDebug((object)"Found parent for spawning!");
							itemSpawnsOnGround = false;
						}
					}
				}
				return itemSpawnsOnGround;
			}
		}

		private static List<ClosetHolder>? _closet;

		internal static List<ClosetHolder> Closets
		{
			get
			{
				if (_closet != null && _closet.Count() > 0)
				{
					return _closet;
				}
				for (int i = 0; i <= MoreCupboards.maximumCupboards.Value; i++)
				{
					MoreCupboards.Logger.LogInfo((object)$"Loading closet {i}...");
					ClosetHolder? closetHolder = new ClosetHolder(i);
					if ((Object)(object)closetHolder.Value.gameObject != (Object)null)
					{
						MoreCupboards.Logger.LogInfo((object)$"Loaded closet {i}!");
						_closet?.Add(closetHolder.Value);
					}
				}
				return _closet;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(StartOfRound), "SceneManager_OnLoadComplete1")]
		private static void PreSpawnInitialization(GrabbableObject __instance)
		{
			_closet = new List<ClosetHolder>();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "OnLocalDisconnect")]
		[HarmonyPatch(typeof(StartOfRound), "OnDestroy")]
		private static void ResetOnDisconnect()
		{
			_closet = null;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")]
		private static void AfterCupboardSync(StartOfRound __instance)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager;
			if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening || (int)((NetworkBehaviour)__instance).__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost) || ((NetworkBehaviour)__instance).IsServer)
			{
				return;
			}
			List<ClosetHolder> closets = Closets;
			if (closets == null)
			{
				MoreCupboards.Logger.LogError((object)"Null closet list!");
				return;
			}
			if (closets.Count() == 0)
			{
				MoreCupboards.Logger.LogInfo((object)"Empty closet list!");
				return;
			}
			for (int i = 0; i < closets.Count(); i++)
			{
				ClosetHolder closetHolder = closets[i];
				if (closetHolder.IsInitialized)
				{
					MoreCupboards.Logger.LogDebug((object)$"MattyFix: SyncShipUnlockablesClientRpc Cupboard Triggered but was already Initialized! index: {i}");
					break;
				}
				closetHolder.IsInitialized = true;
				if (closetHolder.Unlockable.inStorage)
				{
					break;
				}
				closetHolder.gameObject.GetComponent<AutoParentToShip>().MoveToOffset();
				Physics.SyncTransforms();
				GrabbableObject[] source = Object.FindObjectsOfType<GrabbableObject>();
				foreach (GrabbableObject item in source.Where((GrabbableObject g) => g.isInShipRoom))
				{
					float offset = 0f;
					if (item.hasHitGround)
					{
						offset = item.itemProperties.verticalOffset;
					}
					ShelfCheck(item, offset, i);
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPriority(0)]
		[HarmonyPatch(typeof(StartOfRound), "LoadShipGrabbableItems")]
		private static void OnServerSpawn(GrabbableObject __instance)
		{
			List<ClosetHolder> closets = Closets;
			if (closets == null)
			{
				MoreCupboards.Logger.LogError((object)"Null closet list!");
				return;
			}
			if (closets.Count() == 0)
			{
				MoreCupboards.Logger.LogInfo((object)"Empty closet list!");
				return;
			}
			for (int i = 0; i < closets.Count(); i++)
			{
				ClosetHolder closetHolder = closets[i];
				if (closetHolder.IsInitialized)
				{
					MoreCupboards.Logger.LogDebug((object)$"MattyFix: LoadShipGrabbableItems Cupboard Triggered but was already Initialized! index: {i}");
					break;
				}
				closetHolder.IsInitialized = true;
				if (closetHolder.Unlockable.inStorage)
				{
					break;
				}
				closetHolder.gameObject.GetComponent<AutoParentToShip>().MoveToOffset();
				Physics.SyncTransforms();
				GrabbableObject[] source = Object.FindObjectsOfType<GrabbableObject>();
				foreach (GrabbableObject item in source.Where((GrabbableObject g) => g.isInShipRoom))
				{
					ShelfCheck(item, 0f, i);
				}
			}
		}

		private static void ShelfCheck(GrabbableObject grabbable, float offset = 0f, int index = 0)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: 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_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: 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_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_032b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0330: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Unknown result type (might be due to invalid IL or missing references)
			//IL_034a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			MoreCupboards.Logger.LogDebug((object)$"MattyFix: {grabbable.itemProperties.itemName}({((NetworkBehaviour)grabbable).NetworkObjectId}) - Cupboard Triggered! index: {index}");
			if (grabbable is ClipboardItem || (grabbable is PhysicsProp && grabbable.itemProperties.itemName == "Sticky note"))
			{
				return;
			}
			double num = 0.05;
			double num2 = num * num;
			try
			{
				Vector3 val = ((Component)grabbable).transform.position + Vector3.down * offset;
				MoreCupboards.Logger.LogDebug((object)$"MattyFix: {grabbable.itemProperties.itemName}({((NetworkBehaviour)grabbable).NetworkObjectId}) - Item pos {val}! index: {index}");
				List<ClosetHolder> closets = Closets;
				ClosetHolder closetHolder = closets[index];
				float num3 = float.MaxValue;
				PlaceableObjectsSurface val2 = null;
				Vector3? val3 = null;
				ManualLogSource logger = MoreCupboards.Logger;
				object[] obj = new object[4]
				{
					grabbable.itemProperties.itemName,
					((NetworkBehaviour)grabbable).NetworkObjectId,
					null,
					null
				};
				Bounds bounds = closetHolder.Collider.bounds;
				obj[2] = ((Bounds)(ref bounds)).min;
				obj[3] = index;
				logger.LogDebug((object)string.Format("MattyFix: {0}({1}) - Cupboard pos {2}! index: {3}", obj));
				Collider collider = closetHolder.Collider;
				float y = val.y;
				bounds = collider.bounds;
				if (y < ((Bounds)(ref bounds)).max.y)
				{
					bounds = collider.bounds;
					if ((double)((Bounds)(ref bounds)).SqrDistance(val) <= num2)
					{
						foreach (ShelfHolder shelf in closetHolder.Shelves)
						{
							Vector3 val4 = shelf.Collider.ClosestPointOnBounds(val);
							float num4 = val.y - val4.y;
							MoreCupboards.Logger.LogDebug((object)$"MattyFix: {grabbable.itemProperties.itemName}({((NetworkBehaviour)grabbable).NetworkObjectId}) - Shelve is {num4} away! index: {index}");
							if (num4 >= 0f && num4 < num3)
							{
								val2 = shelf.Shelf;
								num3 = num4;
								val3 = val4;
							}
						}
						MoreCupboards.Logger.LogDebug((object)$"MattyFix: {grabbable.itemProperties.itemName}({((NetworkBehaviour)grabbable).NetworkObjectId}) - Chosen Shelve is {num3} away! index: {index}");
						MoreCupboards.Logger.LogDebug((object)$"MattyFix: {grabbable.itemProperties.itemName}({((NetworkBehaviour)grabbable).NetworkObjectId}) - With hitpoint at {val3}! index: {index}");
					}
				}
				Transform transform = ((Component)grabbable).transform;
				if ((Object)(object)val2 != (Object)null)
				{
					Vector3 val5 = val3.Value + Vector3.up * grabbable.itemProperties.verticalOffset;
					transform.parent = closetHolder.gameObject.transform;
					MoreCupboards.Logger.LogDebug((object)$"Parenting {grabbable.itemProperties.itemName} to {((Object)closetHolder.gameObject).name}, index: {index} index: {index}");
					transform.position = val5;
					grabbable.targetFloorPosition = transform.localPosition;
					MoreCupboards.Logger.LogDebug((object)$"MattyFix: {grabbable.itemProperties.itemName}({((NetworkBehaviour)grabbable).NetworkObjectId}) - Pos on shelf {val5}! index: {index}");
				}
			}
			catch (Exception arg)
			{
				MoreCupboards.Logger.LogError((object)$"MattyFix: Exception while checking for Cupboard {arg}, index: {index}");
			}
		}

		private static void UpdateItemRotation(Item item, string itemPath = null)
		{
			//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_0017: Unknown result type (might be due to invalid IL or missing references)
			Vector3 restingRotation = item.restingRotation;
			restingRotation.y = item.floorYOffset;
			item.floorYOffset = (int)Math.Round(restingRotation.y);
		}
	}
	[HarmonyPatch]
	internal class CupboardPatches
	{
		internal static bool storeFlag;

		public static bool mrovPresent;

		[HarmonyPatch(typeof(StartOfRound), "SceneManager_OnLoadComplete1")]
		[HarmonyPostfix]
		private static void DestroyCupboardDoors(StartOfRound __instance, string sceneName)
		{
			if (sceneName == "SampleSceneRelay" && MoreCupboards.noDoors.Value)
			{
				GameObject val = GameObject.Find("StorageCloset");
				Animator[] componentsInChildren = val.GetComponentsInChildren<Animator>();
				Animator[] array = componentsInChildren;
				foreach (Animator val2 in array)
				{
					Object.Destroy((Object)(object)((Component)val2).gameObject);
				}
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (assembly.GetName().Name == "TerminalFormatter")
				{
					mrovPresent = true;
					break;
				}
			}
		}

		[HarmonyPatch(typeof(Terminal), "LoadNewNode")]
		[HarmonyPrefix]
		[HarmonyBefore(new string[] { "mrov.terminalformatter" })]
		private static void TerminalTextCheck(Terminal __instance, TerminalNode node)
		{
			if (node.displayText.Contains("[buyableItemsList]"))
			{
				storeFlag = true;
			}
		}

		[HarmonyPatch(typeof(Terminal), "LoadNewNode")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		[HarmonyAfter(new string[] { "mrov.terminalformatter" })]
		private static void TerminalTextOverride(Terminal __instance)
		{
			string text = "";
			if (mrovPresent && storeFlag)
			{
				text = " ";
			}
			for (int i = 1; i <= MoreCupboards.maximumCupboards.Value; i++)
			{
				string text2 = i + "Cupboard";
				if (__instance.currentText.Contains(text2))
				{
					__instance.currentText = __instance.currentText.Replace(text2, "Cupboard" + text);
				}
			}
			if (storeFlag)
			{
				int num = __instance.currentText.Split("Cupboard").Length - 1;
				if (MoreCupboards.maximumCupboards.Value > 1 && __instance.currentText.IndexOf("Cupboard") > 0 && num > 1)
				{
					string text3 = __instance.currentText.Substring(__instance.currentText.IndexOf("Cupboard"));
					string text4 = text3.Substring(text3.IndexOf("\n") + 2);
					string text5 = text4.Substring(text4.LastIndexOf("Cupboard"));
					string text6 = text4.Substring(0, text5.IndexOf("\n") + text4.LastIndexOf("Cupboard") + 2);
					if (num == 2)
					{
						__instance.currentText = __instance.currentText.Remove(__instance.currentText.LastIndexOf(text6), text6.Length);
					}
					else
					{
						__instance.currentText = __instance.currentText.Replace(text6, "");
					}
				}
				storeFlag = false;
			}
			__instance.screenText.text = __instance.currentText;
		}

		[HarmonyPatch(typeof(Terminal), "OnSubmit")]
		[HarmonyPrefix]
		private static void CupboardCommandOverride(Terminal __instance)
		{
			string text = __instance.screenText.text.Substring(__instance.screenText.text.Length - __instance.textAdded);
			if (!(text.ToLower() == "cupboard") && text.ToLower().IndexOf("cupb") != 0 && text.ToLower().IndexOf("cupb") != 1)
			{
				return;
			}
			text = "cupboard";
			UnlockableItem[] array = StartOfRound.Instance.unlockablesList.unlockables.ToArray();
			int num = 0;
			int num2 = 0;
			for (int i = 1; i <= MoreCupboards.maximumCupboards.Value; i++)
			{
				string text2 = i + "Cupboard";
				UnlockableItem[] array2 = array;
				foreach (UnlockableItem val in array2)
				{
					if (val.unlockableName == "Cupboard" && val.inStorage)
					{
						num = -1;
						break;
					}
					if (val.unlockableName == text2 && val.inStorage)
					{
						num = i;
						break;
					}
				}
				if (num2 == 0 && num == 0)
				{
					UnlockableItem[] array3 = array;
					foreach (UnlockableItem val2 in array3)
					{
						if (val2.unlockableName == text2 && !val2.hasBeenUnlockedByPlayer)
						{
							num2 = i;
							break;
						}
					}
				}
				if (num != 0)
				{
					break;
				}
			}
			switch (num)
			{
			default:
				MoreCupboards.Logger.LogInfo((object)$"Retrieving cupboard{num}");
				text = num + text;
				break;
			case 0:
				if (num2 != 0)
				{
					MoreCupboards.Logger.LogInfo((object)$"Buying cupboard{num2}");
					text = num2 + text;
					break;
				}
				MoreCupboards.Logger.LogInfo((object)"Unable to find cupboards!");
				return;
			case -1:
				break;
			}
			if (num != -1)
			{
				__instance.screenText.text = __instance.screenText.text.Substring(0, __instance.screenText.text.Length - __instance.textAdded) + text;
			}
		}

		[HarmonyPatch(typeof(ShipBuildModeManager), "StoreObjectLocalClient")]
		[HarmonyPrefix]
		private static void UnparentItemsOnStore(ShipBuildModeManager __instance)
		{
			if (__instance.timeSincePlacingObject <= 0.25f || !__instance.InBuildMode || (Object)(object)__instance.placingObject == (Object)null || !StartOfRound.Instance.unlockablesList.unlockables[__instance.placingObject.unlockableID].canBeStored)
			{
				return;
			}
			UnlockableItem val = StartOfRound.Instance.unlockablesList.unlockables[__instance.placingObject.unlockableID];
			if (!val.unlockableName.Contains("Cupboard"))
			{
				return;
			}
			StartOfRound val2 = Object.FindObjectOfType<StartOfRound>();
			PlaceableShipObject placingObject = __instance.placingObject;
			object obj;
			if (placingObject == null)
			{
				obj = null;
			}
			else
			{
				AutoParentToShip parentObject = placingObject.parentObject;
				if (parentObject == null)
				{
					obj = null;
				}
				else
				{
					GameObject gameObject = ((Component)parentObject).gameObject;
					obj = ((gameObject != null) ? gameObject.GetComponentsInChildren<GrabbableObject>() : null);
				}
			}
			GrabbableObject[] array = (GrabbableObject[])obj;
			GrabbableObject[] array2 = array;
			foreach (GrabbableObject val3 in array2)
			{
				val3.parentObject = null;
				((Component)val3).transform.SetParent(val2.elevatorTransform, true);
			}
		}

		[HarmonyPatch(typeof(ShipBuildModeManager), "StoreObjectServerRpc")]
		[HarmonyPrefix]
		private static void UnparentItemsOnStoreServer(ShipBuildModeManager __instance, NetworkObjectReference objectRef)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			NetworkObjectReference val = objectRef;
			NetworkObject val2 = default(NetworkObject);
			if (!((NetworkObjectReference)(ref val)).TryGet(ref val2, (NetworkManager)null))
			{
				return;
			}
			PlaceableShipObject componentInChildren = ((Component)val2).gameObject.GetComponentInChildren<PlaceableShipObject>();
			if (!StartOfRound.Instance.unlockablesList.unlockables[componentInChildren.unlockableID].unlockableName.Contains("Cupboard"))
			{
				return;
			}
			StartOfRound val3 = Object.FindObjectOfType<StartOfRound>();
			object obj;
			if (componentInChildren == null)
			{
				obj = null;
			}
			else
			{
				AutoParentToShip parentObject = componentInChildren.parentObject;
				if (parentObject == null)
				{
					obj = null;
				}
				else
				{
					GameObject gameObject = ((Component)parentObject).gameObject;
					obj = ((gameObject != null) ? gameObject.GetComponentsInChildren<GrabbableObject>() : null);
				}
			}
			GrabbableObject[] array = (GrabbableObject[])obj;
			GrabbableObject[] array2 = array;
			foreach (GrabbableObject val4 in array2)
			{
				val4.parentObject = null;
				((Component)val4).transform.SetParent(val3.elevatorTransform, true);
			}
		}

		[HarmonyPatch(typeof(ShipBuildModeManager), "StoreShipObjectClientRpc")]
		[HarmonyPrefix]
		private static void UnparentItemsOnStoreClient(ShipBuildModeManager __instance, NetworkObjectReference objectRef, int playerWhoStored)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)NetworkManager.Singleton == (Object)null || ((NetworkBehaviour)__instance).NetworkManager.ShutdownInProgress || ((NetworkBehaviour)__instance).IsServer || playerWhoStored == (int)GameNetworkManager.Instance.localPlayerController.playerClientId)
			{
				return;
			}
			NetworkObjectReference val = objectRef;
			NetworkObject val2 = default(NetworkObject);
			if (!((NetworkObjectReference)(ref val)).TryGet(ref val2, (NetworkManager)null))
			{
				return;
			}
			PlaceableShipObject componentInChildren = ((Component)val2).gameObject.GetComponentInChildren<PlaceableShipObject>();
			if (!StartOfRound.Instance.unlockablesList.unlockables[componentInChildren.unlockableID].unlockableName.Contains("Cupboard"))
			{
				return;
			}
			StartOfRound val3 = Object.FindObjectOfType<StartOfRound>();
			object obj;
			if (componentInChildren == null)
			{
				obj = null;
			}
			else
			{
				AutoParentToShip parentObject = componentInChildren.parentObject;
				if (parentObject == null)
				{
					obj = null;
				}
				else
				{
					GameObject gameObject = ((Component)parentObject).gameObject;
					obj = ((gameObject != null) ? gameObject.GetComponentsInChildren<GrabbableObject>() : null);
				}
			}
			GrabbableObject[] array = (GrabbableObject[])obj;
			GrabbableObject[] array2 = array;
			foreach (GrabbableObject val4 in array2)
			{
				val4.parentObject = null;
				((Component)val4).transform.SetParent(val3.elevatorTransform, true);
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}