Decompiled source of ExtraInventorySlots v1.2.1

ExtraInventorySlots.dll

Decompiled 2 weeks 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.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExtraInventorySlots.Configuration;
using ExtraInventorySlots.Input;
using ExtraInventorySlots.Interaction;
using ExtraInventorySlots.Ownership;
using ExtraInventorySlots.Slots;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ExtraInventorySlots
{
	internal static class MyPluginInfo
	{
		internal const string PLUGIN_GUID = "DarkSpider90.ExtraInventorySlots";

		internal const string PLUGIN_NAME = "Extra Inventory Slots";

		internal const string PLUGIN_VERSION = "1.2.1";
	}
	[BepInPlugin("DarkSpider90.ExtraInventorySlots", "Extra Inventory Slots", "1.2.1")]
	public sealed class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		internal static Plugin Instance { get; private set; }

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			SlotSettings.Bind(((BaseUnityPlugin)this).Config);
			ApplyPatches();
			Log.LogInfo((object)"Extra Inventory Slots v1.2.1 loaded for R.E.P.O. v0.5.0.");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private void ApplyPatches()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			_harmony = new Harmony("DarkSpider90.ExtraInventorySlots");
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(Assembly.GetExecutingAssembly());
			foreach (Type type in typesFromAssembly)
			{
				try
				{
					List<MethodInfo> list = _harmony.CreateClassProcessor(type).Patch();
					if ((list == null || list.Count <= 0) && DeclaresPatchMethods(type))
					{
						Log.LogError((object)(type.FullName + " declares Harmony patch methods but carries no [HarmonyPatch] attribute on the class itself, so none of them were applied."));
					}
				}
				catch (Exception arg)
				{
					Log.LogError((object)$"Failed to apply patches from {type.FullName}; continuing. {arg}");
				}
			}
		}

		private static bool DeclaresPatchMethods(Type type)
		{
			foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(type))
			{
				if (((MemberInfo)declaredMethod).GetCustomAttribute<HarmonyPrefix>() != null || ((MemberInfo)declaredMethod).GetCustomAttribute<HarmonyPostfix>() != null || ((MemberInfo)declaredMethod).GetCustomAttribute<HarmonyTranspiler>() != null || ((MemberInfo)declaredMethod).GetCustomAttribute<HarmonyFinalizer>() != null)
				{
					return true;
				}
			}
			return false;
		}
	}
}
namespace ExtraInventorySlots.Slots
{
	internal static class InventorySlotList
	{
		internal static void EnsureSlots(Inventory inventory, int minimumSlotCount = -1)
		{
			if ((Object)(object)inventory == (Object)null)
			{
				return;
			}
			List<InventorySpot> allSpots = inventory.GetAllSpots();
			if (allSpots != null)
			{
				int num = Math.Max(SlotSettings.EffectiveSlotCount, minimumSlotCount);
				while (allSpots.Count < num)
				{
					allSpots.Add(null);
				}
			}
		}

		internal static InventorySpot GetSpot(int slotIndex)
		{
			if ((Object)(object)Inventory.instance == (Object)null || slotIndex < 0)
			{
				return null;
			}
			EnsureSlots(Inventory.instance, slotIndex + 1);
			List<InventorySpot> allSpots = Inventory.instance.GetAllSpots();
			if (allSpots == null || slotIndex >= allSpots.Count)
			{
				return null;
			}
			return allSpots[slotIndex];
		}
	}
	internal static class SlotBatteryBinder
	{
		private static readonly FieldInfo BatteryVisualLogicField = AccessTools.Field(typeof(InventorySpot), "batteryVisualLogic");

		private static readonly FieldInfo BarsField = AccessTools.Field(typeof(BatteryVisualLogic), "bars");

		private static readonly FieldInfo TargetScaleField = AccessTools.Field(typeof(BatteryVisualLogic), "targetScale");

		private static readonly FieldInfo TargetScaleOriginalField = AccessTools.Field(typeof(BatteryVisualLogic), "targetScaleOriginal");

		private static readonly FieldInfo TargetRotationField = AccessTools.Field(typeof(BatteryVisualLogic), "targetRotation");

		private static readonly FieldInfo TargetRotationOriginalField = AccessTools.Field(typeof(BatteryVisualLogic), "targetRotationOriginal");

		private static readonly FieldInfo TargetPositionField = AccessTools.Field(typeof(BatteryVisualLogic), "targetPosition");

		private static readonly FieldInfo TargetPositionOriginalField = AccessTools.Field(typeof(BatteryVisualLogic), "targetPositionOriginal");

		private static readonly FieldInfo DoOutroField = AccessTools.Field(typeof(BatteryVisualLogic), "doOutro");

		private static readonly FieldInfo SpringScaleField = AccessTools.Field(typeof(BatteryVisualLogic), "springScale");

		private static readonly FieldInfo SpringRotationField = AccessTools.Field(typeof(BatteryVisualLogic), "springRotation");

		private static readonly FieldInfo SpringPositionField = AccessTools.Field(typeof(BatteryVisualLogic), "springPosition");

		private static readonly FieldInfo SpringFloatLastPositionField = AccessTools.Field(typeof(SpringFloat), "lastPosition");

		private static readonly FieldInfo SpringVectorLastPositionField = AccessTools.Field(typeof(SpringVector3), "lastPosition");

		internal static BatteryVisualLogic Bind(InventorySpot spot, bool activateForVanillaStart)
		{
			if ((Object)(object)spot == (Object)null)
			{
				return null;
			}
			object? obj = BatteryVisualLogicField?.GetValue(spot);
			BatteryVisualLogic val = (BatteryVisualLogic)((obj is BatteryVisualLogic) ? obj : null);
			if ((Object)(object)val != (Object)null && ((Component)val).transform.IsChildOf(((Component)spot).transform))
			{
				if (activateForVanillaStart && !((Component)val).gameObject.activeSelf)
				{
					((Component)val).gameObject.SetActive(true);
				}
				return val;
			}
			BatteryVisualLogic val2 = ((Component)spot).GetComponentsInChildren<BatteryVisualLogic>(true).FirstOrDefault();
			if ((Object)(object)val2 == (Object)null)
			{
				return null;
			}
			if (activateForVanillaStart && !((Component)val2).gameObject.activeSelf)
			{
				((Component)val2).gameObject.SetActive(true);
			}
			BatteryVisualLogicField?.SetValue(spot, val2);
			return val2;
		}

		internal static void PrepareFreshClone(InventorySpot spot, BatteryVisualLogic templateVisual)
		{
			BatteryVisualLogic val = Bind(spot, activateForVanillaStart: true);
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)$"Inventory slot {((spot != null) ? new int?(spot.inventorySpotIndex + 1) : ((int?)null))} has no BatteryVisualLogic child.");
				return;
			}
			BarsField?.SetValue(val, new List<GameObject>());
			ResetCloneTargets(val, templateVisual);
			ResetSprings(val, GetTargetScale(val, templateVisual));
		}

		internal static void Refresh(InventorySpot spot)
		{
			BatteryVisualLogic val = Bind(spot, activateForVanillaStart: false);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			ItemEquippable currentItem = spot.CurrentItem;
			ItemBattery val2 = (((Object)(object)currentItem == (Object)null) ? null : ((Component)currentItem).GetComponent<ItemBattery>());
			if (!((Object)(object)val2 == (Object)null))
			{
				val.itemBattery = val2;
				if (!((Component)val).gameObject.activeSelf)
				{
					((Component)val).gameObject.SetActive(true);
				}
				val.ResetOutro();
				val.BatteryBarsSet();
				val.BatteryBarsUpdate(-1, true);
			}
		}

		private static void ResetCloneTargets(BatteryVisualLogic visual, BatteryVisualLogic templateVisual)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)visual == (Object)null))
			{
				Vector3 targetPosition = GetTargetPosition(visual, templateVisual);
				float targetScale = GetTargetScale(visual, templateVisual);
				float fieldValue = GetFieldValue(TargetRotationOriginalField, templateVisual, 0f);
				((Component)visual).transform.localPosition = targetPosition;
				((Component)visual).transform.localScale = new Vector3(targetScale, targetScale, targetScale);
				((Component)visual).transform.localRotation = Quaternion.Euler(0f, 0f, fieldValue);
				TargetPositionField?.SetValue(visual, targetPosition);
				TargetPositionOriginalField?.SetValue(visual, targetPosition);
				TargetScaleField?.SetValue(visual, targetScale);
				TargetScaleOriginalField?.SetValue(visual, targetScale);
				TargetRotationField?.SetValue(visual, fieldValue);
				TargetRotationOriginalField?.SetValue(visual, fieldValue);
				DoOutroField?.SetValue(visual, false);
			}
		}

		private static Vector3 GetTargetPosition(BatteryVisualLogic visual, BatteryVisualLogic templateVisual)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: 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)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			Vector3 fieldValue = GetFieldValue<Vector3>(TargetPositionOriginalField, templateVisual, ((Component)visual).transform.localPosition);
			if (float.IsNaN(fieldValue.x) || float.IsInfinity(fieldValue.x))
			{
				return ((Component)visual).transform.localPosition;
			}
			return fieldValue;
		}

		private static float GetTargetScale(BatteryVisualLogic visual, BatteryVisualLogic templateVisual)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			float fieldValue = GetFieldValue(TargetScaleOriginalField, templateVisual, 0f);
			if (fieldValue > 0.001f)
			{
				return fieldValue;
			}
			fieldValue = GetFieldValue(TargetScaleField, templateVisual, 0f);
			if (fieldValue > 0.001f)
			{
				return fieldValue;
			}
			fieldValue = Mathf.Max(((Component)visual).transform.localScale.x, ((Component)visual).transform.localScale.y);
			if (!(fieldValue > 0.001f))
			{
				return 0.5f;
			}
			return fieldValue;
		}

		private static T GetFieldValue<T>(FieldInfo field, object instance, T fallback)
		{
			if (field == null || instance == null)
			{
				return fallback;
			}
			object value = field.GetValue(instance);
			if (value is T)
			{
				return (T)value;
			}
			return fallback;
		}

		private static void ResetSprings(BatteryVisualLogic visual, float targetScale)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0045: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			SpringFloat val = new SpringFloat
			{
				damping = 0.4f,
				speed = 30f
			};
			SpringFloatLastPositionField?.SetValue(val, targetScale);
			SpringScaleField?.SetValue(visual, val);
			SpringFloat val2 = new SpringFloat
			{
				damping = 0.3f,
				speed = 40f
			};
			SpringFloatLastPositionField?.SetValue(val2, 0f);
			SpringRotationField?.SetValue(visual, val2);
			SpringVector3 val3 = new SpringVector3
			{
				damping = 0.35f,
				speed = 30f
			};
			SpringVectorLastPositionField?.SetValue(val3, ((Component)visual).transform.localPosition);
			SpringPositionField?.SetValue(visual, val3);
		}
	}
	internal static class SlotHierarchyReport
	{
		private static bool _reported;

		internal static void ReportOnce(InventorySpot template)
		{
			if (!_reported && !((Object)(object)template == (Object)null))
			{
				_reported = true;
				StringBuilder stringBuilder = new StringBuilder("Template inventory spot hierarchy:");
				Transform[] componentsInChildren = ((Component)template).GetComponentsInChildren<Transform>(true);
				foreach (Transform child in componentsInChildren)
				{
					stringBuilder.AppendLine().Append("  ").Append(DescribePath(((Component)template).transform, child));
					AppendComponents(stringBuilder, template, child);
				}
				Plugin.Log.LogInfo((object)stringBuilder.ToString());
			}
		}

		private static void AppendComponents(StringBuilder builder, InventorySpot template, Transform child)
		{
			Component[] components = ((Component)child).GetComponents<Component>();
			foreach (Component val in components)
			{
				if ((Object)(object)val == (Object)null || val is Transform)
				{
					continue;
				}
				builder.Append(" [").Append(((object)val).GetType().Name);
				TMP_Text val2 = (TMP_Text)(object)((val is TMP_Text) ? val : null);
				if (val2 != null)
				{
					builder.Append(" \"").Append(val2.text).Append('"');
					if ((object)val2 == template.noItem)
					{
						builder.Append(", noItem");
					}
				}
				else
				{
					InputGlyphText val3 = (InputGlyphText)(object)((val is InputGlyphText) ? val : null);
					if (val3 != null)
					{
						builder.Append(" template=\"").Append(val3.template).Append('"');
					}
				}
				builder.Append(']');
			}
		}

		private static string DescribePath(Transform root, Transform child)
		{
			if ((Object)(object)child == (Object)(object)root)
			{
				return ((Object)child).name;
			}
			List<string> list = new List<string>();
			Transform val = child;
			while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)root)
			{
				list.Add(((Object)val).name);
				val = val.parent;
			}
			list.Reverse();
			return string.Join("/", list);
		}
	}
	internal static class SlotLabelPainter
	{
		internal static string TemplateLabel { get; set; } = "1";

		internal static void Apply(InventorySpot spot, int slotIndex)
		{
			if ((Object)(object)spot == (Object)null || slotIndex < 3)
			{
				return;
			}
			string text = SlotSettings.SlotLabel(slotIndex);
			if ((Object)(object)spot.noItem != (Object)null)
			{
				((TMP_Text)spot.noItem).text = text;
			}
			HashSet<TMP_Text> hashSet = new HashSet<TMP_Text>();
			InputGlyphText[] componentsInChildren = ((Component)spot).GetComponentsInChildren<InputGlyphText>(true);
			foreach (InputGlyphText val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null))
				{
					val.SetTemplate(text);
					if ((Object)(object)val.label != (Object)null)
					{
						hashSet.Add(val.label);
					}
				}
			}
			TMP_Text[] componentsInChildren2 = ((Component)spot).GetComponentsInChildren<TMP_Text>(true);
			foreach (TMP_Text val2 in componentsInChildren2)
			{
				if (!((Object)(object)val2 == (Object)null) && (object)val2 != spot.noItem && !hashSet.Contains(val2))
				{
					string text2 = val2.text?.Trim();
					if (!string.IsNullOrEmpty(text2) && (string.Equals(text2, TemplateLabel, StringComparison.Ordinal) || string.Equals(text2, text, StringComparison.Ordinal)))
					{
						val2.text = text;
					}
				}
			}
		}
	}
	internal static class SlotLayoutBuilder
	{
		private static readonly FieldInfo AllChildrenField = AccessTools.Field(typeof(SemiUI), "allChildren");

		private static readonly FieldInfo CurrentStateField = AccessTools.Field(typeof(InventorySpot), "currentState");

		private static readonly FieldInfo CurrentItemBackingField = AccessTools.Field(typeof(InventorySpot), "<CurrentItem>k__BackingField");

		private static readonly FieldInfo StateStartField = AccessTools.Field(typeof(InventorySpot), "stateStart");

		private static readonly MethodInfo LayoutSetupMethod = AccessTools.Method(typeof(InventoryUI), "LayoutSetup", (Type[])null, (Type[])null);

		private const float FallbackSpacing = 40f;

		internal static void Rebuild(InventoryUI inventoryUi)
		{
			//IL_0103: 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_013a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)inventoryUi == (Object)null)
			{
				return;
			}
			int effectiveSlotCount = SlotSettings.EffectiveSlotCount;
			if (effectiveSlotCount <= 3)
			{
				return;
			}
			try
			{
				Transform transform = ((Component)inventoryUi).transform;
				List<InventorySpot> list = (from spot in ((Component)transform).GetComponentsInChildren<InventorySpot>(true)
					orderby spot.inventorySpotIndex, ((Object)spot).name
					select spot).ToList();
				InventorySpot val = ((IEnumerable<InventorySpot>)list).FirstOrDefault((Func<InventorySpot, bool>)((InventorySpot spot) => spot.inventorySpotIndex == 0)) ?? list.FirstOrDefault();
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Log.LogWarning((object)"Could not find an InventorySpot to copy in InventoryUI.");
					return;
				}
				SlotLabelPainter.TemplateLabel = SlotSettings.SlotLabel(Math.Max(0, val.inventorySpotIndex));
				SlotHierarchyReport.ReportOnce(val);
				List<GameObject> list2 = AllChildrenField?.GetValue(inventoryUi) as List<GameObject>;
				float num = MeasureSpacing(list);
				float num2 = MeasureCenterX(list, ((Component)val).transform.localPosition.x) - num * (float)(effectiveSlotCount - 1) * 0.5f;
				float y = ((Component)val).transform.localPosition.y;
				float z = ((Component)val).transform.localPosition.z;
				for (int num3 = 0; num3 < effectiveSlotCount; num3++)
				{
					InventorySpot orCreateSpot = GetOrCreateSpot(transform, val, list, num3);
					if (!((Object)(object)orCreateSpot == (Object)null))
					{
						ConfigureSpot(orCreateSpot, num3, num2 + num * (float)num3, y, z);
						GameObject gameObject = ((Component)orCreateSpot).gameObject;
						if (list2 != null && !list2.Contains(gameObject))
						{
							list2.Add(gameObject);
						}
					}
				}
				InventorySlotList.EnsureSlots(Inventory.instance, effectiveSlotCount);
				HandLayoutToGame(inventoryUi);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogWarning((object)$"Failed to build the inventory row: {arg}");
			}
		}

		private static void HandLayoutToGame(InventoryUI inventoryUi)
		{
			if (LayoutSetupMethod == null)
			{
				return;
			}
			try
			{
				LayoutSetupMethod.Invoke(inventoryUi, Array.Empty<object>());
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("InventoryUI.LayoutSetup could not be run, so the game will lay out only its own slots. " + ex.GetType().Name + ": " + ex.Message));
			}
		}

		private static InventorySpot GetOrCreateSpot(Transform root, InventorySpot template, List<InventorySpot> existingSpots, int index)
		{
			InventorySpot val = ((IEnumerable<InventorySpot>)existingSpots).FirstOrDefault((Func<InventorySpot, bool>)((InventorySpot spot) => spot.inventorySpotIndex == index));
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			Transform val2 = root.Find($"Inventory Spot {index + 1}");
			InventorySpot val3 = default(InventorySpot);
			if ((Object)(object)val2 != (Object)null && ((Component)val2).TryGetComponent<InventorySpot>(ref val3))
			{
				if (!existingSpots.Contains(val3))
				{
					existingSpots.Add(val3);
				}
				return val3;
			}
			Transform obj = Object.Instantiate<Transform>(((Component)template).transform, ((Component)template).transform.parent);
			((Object)obj).name = $"Inventory Spot {index + 1}";
			InventorySpot component = ((Component)obj).GetComponent<InventorySpot>();
			BatteryVisualLogic templateVisual = ((Component)template).GetComponentsInChildren<BatteryVisualLogic>(true).FirstOrDefault();
			SlotBatteryBinder.PrepareFreshClone(component, templateVisual);
			ClearCopiedRuntimeState(component);
			existingSpots.Add(component);
			return component;
		}

		private static void ClearCopiedRuntimeState(InventorySpot spot)
		{
			if (!((Object)(object)spot == (Object)null))
			{
				CurrentItemBackingField?.SetValue(spot, null);
				if (CurrentStateField != null)
				{
					CurrentStateField.SetValue(spot, Enum.ToObject(CurrentStateField.FieldType, 0));
				}
				StateStartField?.SetValue(spot, true);
			}
		}

		private static void ConfigureSpot(InventorySpot spot, int index, float x, float y, float z)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			spot.inventorySpotIndex = index;
			((Object)spot).name = $"Inventory Spot {index + 1}";
			((Component)spot).transform.localPosition = new Vector3(x, y, z);
			((Component)spot).gameObject.SetActive(true);
			SlotBatteryBinder.Bind(spot, activateForVanillaStart: false);
			SlotLabelPainter.Apply(spot, index);
		}

		private static float MeasureSpacing(List<InventorySpot> spots)
		{
			List<float> list = VanillaSlotPositions(spots);
			if (list.Count >= 2)
			{
				float num = Mathf.Abs(list[1] - list[0]);
				if (num > 1f)
				{
					return num;
				}
			}
			return 40f;
		}

		private static float MeasureCenterX(List<InventorySpot> spots, float fallback)
		{
			List<float> list = VanillaSlotPositions(spots);
			if (list.Count >= 3)
			{
				return (list[0] + list[2]) * 0.5f;
			}
			return fallback;
		}

		private static List<float> VanillaSlotPositions(List<InventorySpot> spots)
		{
			return (from spot in spots
				where spot.inventorySpotIndex >= 0 && spot.inventorySpotIndex < 3
				orderby spot.inventorySpotIndex
				select ((Component)spot).transform.localPosition.x).ToList();
		}
	}
}
namespace ExtraInventorySlots.Patches
{
	[HarmonyPatch]
	internal static class InventoryPatches
	{
		[HarmonyPatch(typeof(Inventory), "Awake")]
		[HarmonyPostfix]
		private static void AwakePostfix(Inventory __instance)
		{
			InventorySlotList.EnsureSlots(__instance);
		}

		[HarmonyPatch(typeof(Inventory), "InventorySpotAddAtIndex")]
		[HarmonyPrefix]
		private static void InventorySpotAddAtIndexPrefix(Inventory __instance, int index)
		{
			InventorySlotList.EnsureSlots(__instance, index + 1);
		}
	}
	[HarmonyPatch]
	internal static class InventorySpotPatches
	{
		[HarmonyPatch(typeof(InventorySpot), "Start")]
		[HarmonyPrefix]
		private static void StartPrefix(InventorySpot __instance)
		{
			SlotBatteryBinder.Bind(__instance, activateForVanillaStart: true);
		}

		[HarmonyPatch(typeof(InventorySpot), "Start")]
		[HarmonyPostfix]
		private static void StartPostfix(InventorySpot __instance)
		{
			SlotBatteryBinder.Refresh(__instance);
		}

		[HarmonyPatch(typeof(InventorySpot), "Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(InventorySpot __instance)
		{
			SlotHotkeys.Poll(__instance);
		}

		[HarmonyPatch(typeof(InventorySpot), "HandleInput")]
		[HarmonyPrefix]
		private static bool HandleInputPrefix(InventorySpot __instance)
		{
			return HeldItemSwap.TryStartSwap(__instance);
		}

		[HarmonyPatch(typeof(InventorySpot), "EquipItem")]
		[HarmonyPostfix]
		private static void EquipItemPostfix(InventorySpot __instance)
		{
			SlotBatteryBinder.Refresh(__instance);
		}

		[HarmonyPatch(typeof(InventorySpot), "UpdateUI")]
		[HarmonyPostfix]
		private static void UpdateUiPostfix(InventorySpot __instance)
		{
			SlotBatteryBinder.Refresh(__instance);
		}

		[HarmonyPatch(typeof(InventorySpot), "StateOccupied")]
		[HarmonyPrefix]
		private static void StateOccupiedPrefix(InventorySpot __instance)
		{
			SlotBatteryBinder.Bind(__instance, activateForVanillaStart: false);
		}
	}
	[HarmonyPatch]
	internal static class InventoryUiPatches
	{
		[HarmonyPatch(typeof(InventoryUI), "Start")]
		[HarmonyPostfix]
		private static void StartPostfix(InventoryUI __instance)
		{
			SlotLayoutBuilder.Rebuild(__instance);
		}
	}
	[HarmonyPatch]
	internal static class ItemEquippablePatches
	{
		[HarmonyPatch(typeof(ItemEquippable), "RPC_RequestEquip")]
		[HarmonyPrefix]
		private static bool RequestEquipPrefix(int spotIndex)
		{
			if (ItemNameRestoreScope.InProgress && SlotSettings.EmptyInventoriesBetweenLevels.Value)
			{
				return false;
			}
			if (SemiFunc.IsMultiplayer() && SlotSettings.LimitClientsToHostSlots.Value && spotIndex >= SlotSettings.EffectiveSlotCount)
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class PunManagerPatches
	{
		[HarmonyPatch(typeof(PunManager), "SetItemNameLOGIC")]
		[HarmonyPrefix]
		private static void SetItemNameLogicPrefix()
		{
			ItemNameRestoreScope.Enter();
		}

		[HarmonyPatch(typeof(PunManager), "SetItemNameLOGIC")]
		[HarmonyPostfix]
		private static void SetItemNameLogicPostfix(string _name, int photonViewID, ItemAttributes _itemAttributes)
		{
			ExtraSlotOwnership.Restore(_name, photonViewID, _itemAttributes);
		}

		[HarmonyPatch(typeof(PunManager), "SetItemNameLOGIC")]
		[HarmonyFinalizer]
		private static void SetItemNameLogicFinalizer()
		{
			ItemNameRestoreScope.Exit();
		}
	}
	[HarmonyPatch]
	internal static class StatsManagerPatches
	{
		[HarmonyPatch(typeof(StatsManager), "Start")]
		[HarmonyPostfix]
		private static void StartPostfix(StatsManager __instance)
		{
			ExtraSlotStatsRegistry.EnsureRegistered(__instance);
		}

		[HarmonyPatch(typeof(StatsManager), "PlayerInventoryUpdate")]
		[HarmonyPostfix]
		private static void PlayerInventoryUpdatePostfix(string _steamID, string itemName, int spot)
		{
			ExtraSlotOwnership.Record(_steamID, itemName, spot);
		}

		[HarmonyPatch(typeof(StatsManager), "StuffNeedingResetAtTheEndOfAScene")]
		[HarmonyPostfix]
		private static void StuffNeedingResetAtTheEndOfAScenePostfix(StatsManager __instance)
		{
			ExtraSlotStatsRegistry.ClearTakenMarks(__instance);
		}
	}
}
namespace ExtraInventorySlots.Ownership
{
	internal static class ExtraSlotOwnership
	{
		private const int EmptySlot = -1;

		internal static void Record(string steamId, string itemName, int slotIndex)
		{
			if (SemiFunc.IsMasterClientOrSingleplayer() && slotIndex >= 3 && slotIndex < 10 && !string.IsNullOrEmpty(steamId))
			{
				StatsManager instance = StatsManager.instance;
				if (!((Object)(object)instance == (Object)null))
				{
					ExtraSlotStatsRegistry.EnsureRegistered(instance);
					string dictionaryName = ExtraSlotStatsRegistry.SpotDictionary(slotIndex);
					string dictionaryName2 = ExtraSlotStatsRegistry.TakenDictionary(slotIndex);
					StatsDictionaryAccess.SetValue(instance, dictionaryName, steamId, string.IsNullOrEmpty(itemName) ? (-1) : itemName.GetHashCode());
					StatsDictionaryAccess.Remove(instance, dictionaryName2, steamId);
				}
			}
		}

		internal static bool Restore(string itemName, int photonViewId, ItemAttributes itemAttributes)
		{
			if (SlotSettings.EmptyInventoriesBetweenLevels.Value || string.IsNullOrEmpty(itemName))
			{
				return false;
			}
			StatsManager instance = StatsManager.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			ItemEquippable val = ResolveItem(photonViewId, itemAttributes);
			if ((Object)(object)val == (Object)null || val.IsEquipped())
			{
				return false;
			}
			ExtraSlotStatsRegistry.EnsureRegistered(instance);
			List<PlayerAvatar> list = SemiFunc.PlayerGetList();
			if (list == null)
			{
				return false;
			}
			int hashCode = itemName.GetHashCode();
			foreach (PlayerAvatar item in list)
			{
				string text = SemiFunc.PlayerGetSteamID(item);
				if (string.IsNullOrEmpty(text))
				{
					continue;
				}
				for (int i = 3; i < SlotSettings.EffectiveSlotCount; i++)
				{
					if (HoldsUnclaimedItem(instance, i, text, hashCode))
					{
						StatsDictionaryAccess.SetValue(instance, ExtraSlotStatsRegistry.TakenDictionary(i), text, 1);
						val.RequestEquip(i, OwnerViewId(item));
						return true;
					}
				}
			}
			return false;
		}

		private static bool HoldsUnclaimedItem(StatsManager statsManager, int slotIndex, string steamId, int itemHash)
		{
			if (StatsDictionaryAccess.GetValue(statsManager, ExtraSlotStatsRegistry.SpotDictionary(slotIndex), steamId, -1) != itemHash)
			{
				return false;
			}
			return !StatsDictionaryAccess.Contains(statsManager, ExtraSlotStatsRegistry.TakenDictionary(slotIndex), steamId);
		}

		private static int OwnerViewId(PlayerAvatar player)
		{
			if (!SemiFunc.IsMultiplayer())
			{
				return -1;
			}
			if (!((Object)(object)player == (Object)null) && !((Object)(object)player.photonView == (Object)null))
			{
				return player.photonView.ViewID;
			}
			return -1;
		}

		private static ItemEquippable ResolveItem(int photonViewId, ItemAttributes itemAttributes)
		{
			ItemAttributes val = itemAttributes;
			if (SemiFunc.IsMultiplayer())
			{
				PhotonView val2 = PhotonView.Find(photonViewId);
				if ((Object)(object)val2 == (Object)null)
				{
					return null;
				}
				val = ((Component)val2).GetComponent<ItemAttributes>();
			}
			if (!((Object)(object)val == (Object)null))
			{
				return ((Component)val).GetComponent<ItemEquippable>();
			}
			return null;
		}
	}
	internal static class ExtraSlotStatsRegistry
	{
		private static bool _reportedRegistration;

		internal static string SpotDictionary(int slotIndex)
		{
			return $"playerInventorySpot{slotIndex + 1}";
		}

		internal static string TakenDictionary(int slotIndex)
		{
			return $"playerInventorySpot{slotIndex + 1}Taken";
		}

		internal static void EnsureRegistered(StatsManager statsManager)
		{
			if ((Object)(object)statsManager == (Object)null || !StatsDictionaryAccess.IsAvailable)
			{
				return;
			}
			int num = 0;
			for (int i = 3; i < 10; i++)
			{
				if (StatsDictionaryAccess.EnsureTable(statsManager, SpotDictionary(i)) && StatsDictionaryAccess.EnsureTable(statsManager, TakenDictionary(i)))
				{
					num++;
				}
			}
			if (num > 0 && !_reportedRegistration)
			{
				_reportedRegistration = true;
				Plugin.Log.LogInfo((object)($"Registered stat dictionaries for slots {4}-{10}, " + "so their contents are saved, loaded and synchronised like the vanilla slots."));
			}
		}

		internal static void ClearTakenMarks(StatsManager statsManager)
		{
			if (!((Object)(object)statsManager == (Object)null))
			{
				for (int i = 3; i < 10; i++)
				{
					StatsDictionaryAccess.Clear(statsManager, TakenDictionary(i));
				}
			}
		}
	}
	internal static class ItemNameRestoreScope
	{
		private static int _depth;

		internal static bool InProgress => _depth > 0;

		internal static void Enter()
		{
			_depth++;
		}

		internal static void Exit()
		{
			if (_depth > 0)
			{
				_depth--;
			}
		}
	}
	internal static class StatsDictionaryAccess
	{
		private static readonly FieldInfo RegistryField = AccessTools.Field(typeof(StatsManager), "dictionaryOfDictionaries");

		private static bool _reportedMissingRegistry;

		internal static bool IsAvailable => RegistryField != null;

		internal static IDictionary<string, Dictionary<string, int>> GetRegistry(StatsManager statsManager)
		{
			if ((Object)(object)statsManager == (Object)null)
			{
				return null;
			}
			if (RegistryField == null)
			{
				ReportMissingRegistry();
				return null;
			}
			try
			{
				return RegistryField.GetValue(statsManager) as IDictionary<string, Dictionary<string, int>>;
			}
			catch (Exception ex)
			{
				ReportMissingRegistry(ex);
				return null;
			}
		}

		internal static bool TryGetTable(StatsManager statsManager, string dictionaryName, out Dictionary<string, int> table)
		{
			table = null;
			IDictionary<string, Dictionary<string, int>> registry = GetRegistry(statsManager);
			if (registry != null && registry.TryGetValue(dictionaryName, out table))
			{
				return table != null;
			}
			return false;
		}

		internal static int GetValue(StatsManager statsManager, string dictionaryName, string steamId, int fallback)
		{
			if (string.IsNullOrEmpty(steamId) || !TryGetTable(statsManager, dictionaryName, out var table))
			{
				return fallback;
			}
			if (!table.TryGetValue(steamId, out var value))
			{
				return fallback;
			}
			return value;
		}

		internal static bool Contains(StatsManager statsManager, string dictionaryName, string steamId)
		{
			if (!string.IsNullOrEmpty(steamId) && TryGetTable(statsManager, dictionaryName, out var table))
			{
				return table.ContainsKey(steamId);
			}
			return false;
		}

		internal static void SetValue(StatsManager statsManager, string dictionaryName, string steamId, int value)
		{
			if (!((Object)(object)statsManager == (Object)null) && !string.IsNullOrEmpty(steamId))
			{
				statsManager.DictionaryUpdateValue(dictionaryName, steamId, value);
			}
		}

		internal static void Remove(StatsManager statsManager, string dictionaryName, string steamId)
		{
			if (!string.IsNullOrEmpty(steamId) && TryGetTable(statsManager, dictionaryName, out var table))
			{
				table.Remove(steamId);
			}
		}

		internal static void Clear(StatsManager statsManager, string dictionaryName)
		{
			if (TryGetTable(statsManager, dictionaryName, out var table))
			{
				table.Clear();
			}
		}

		internal static bool EnsureTable(StatsManager statsManager, string dictionaryName)
		{
			IDictionary<string, Dictionary<string, int>> registry = GetRegistry(statsManager);
			if (registry == null)
			{
				return false;
			}
			if (!registry.ContainsKey(dictionaryName))
			{
				registry[dictionaryName] = new Dictionary<string, int>();
			}
			return true;
		}

		private static void ReportMissingRegistry(Exception ex = null)
		{
			if (!_reportedMissingRegistry)
			{
				_reportedMissingRegistry = true;
				Plugin.Log.LogWarning((object)("StatsManager.dictionaryOfDictionaries could not be reached, so extra slots cannot remember which player carried which item between rounds. " + ((ex == null) ? string.Empty : (ex.GetType().Name + ": " + ex.Message))));
			}
		}
	}
}
namespace ExtraInventorySlots.Interaction
{
	internal static class HeldItemSwap
	{
		private const float EquipWaitTimeout = 0.75f;

		private static readonly FieldInfo GrabbedPhysGrabObjectField = AccessTools.Field(typeof(PhysGrabber), "grabbedPhysGrabObject");

		private static readonly FieldInfo PlayerInputDisableTimerField = AccessTools.Field(typeof(PlayerController), "InputDisableTimer");

		private static readonly FieldInfo LastEquipTimeField = AccessTools.Field(typeof(InventorySpot), "lastEquipTime");

		private static readonly FieldInfo EquipCooldownField = AccessTools.Field(typeof(InventorySpot), "equipCooldown");

		private static readonly FieldInfo HandleInputField = AccessTools.Field(typeof(InventorySpot), "handleInput");

		internal static bool TryStartSwap(InventorySpot spot)
		{
			if (!SlotSettings.SwapWithItemInFullSlot.Value || (Object)(object)spot == (Object)null || ShouldLeaveToGame(spot))
			{
				return true;
			}
			ItemEquippable heldItem = GetHeldItem();
			if ((Object)(object)heldItem == (Object)null || !spot.IsOccupied())
			{
				return true;
			}
			ItemEquippable currentItem = spot.CurrentItem;
			if ((Object)(object)currentItem == (Object)null || (Object)(object)currentItem == (Object)(object)heldItem)
			{
				return true;
			}
			int inventorySpotIndex = spot.inventorySpotIndex;
			int ownerViewId = (SemiFunc.IsMultiplayer() ? PhysGrabber.instance.photonView.ViewID : (-1));
			HoldOffFurtherInput(spot);
			currentItem.RequestUnequip();
			((MonoBehaviour)Plugin.Instance).StartCoroutine(EquipWhenSlotIsFree(heldItem, inventorySpotIndex, ownerViewId, currentItem));
			return false;
		}

		private static bool ShouldLeaveToGame(InventorySpot spot)
		{
			if (SemiFunc.RunIsArena())
			{
				return true;
			}
			if ((Object)(object)PlayerController.instance != (Object)null && PlayerInputDisableTimerField != null && (float)PlayerInputDisableTimerField.GetValue(PlayerController.instance) > 0f)
			{
				return true;
			}
			return IsInCooldown(spot);
		}

		private static bool IsInCooldown(InventorySpot spot)
		{
			if (LastEquipTimeField == null || EquipCooldownField == null || HandleInputField == null)
			{
				return false;
			}
			if ((bool)HandleInputField.GetValue(spot))
			{
				return false;
			}
			float num = (float)LastEquipTimeField.GetValue(spot);
			float num2 = (float)EquipCooldownField.GetValue(spot);
			return Time.time - num < num2;
		}

		private static void HoldOffFurtherInput(InventorySpot spot)
		{
			LastEquipTimeField?.SetValue(spot, Time.time);
			HandleInputField?.SetValue(spot, false);
		}

		private static ItemEquippable GetHeldItem()
		{
			PhysGrabber instance = PhysGrabber.instance;
			if ((Object)(object)instance == (Object)null || !instance.grabbed)
			{
				return null;
			}
			object? obj = GrabbedPhysGrabObjectField?.GetValue(instance);
			PhysGrabObject val = (PhysGrabObject)((obj is PhysGrabObject) ? obj : null);
			if (!((Object)(object)val == (Object)null))
			{
				return ((Component)val).GetComponent<ItemEquippable>();
			}
			return null;
		}

		private static IEnumerator EquipWhenSlotIsFree(ItemEquippable heldItem, int slotIndex, int ownerViewId, ItemEquippable previousSlotItem)
		{
			float timeoutAt = Time.time + 0.75f;
			while (Time.time < timeoutAt)
			{
				InventorySpot spot = InventorySlotList.GetSpot(slotIndex);
				if ((Object)(object)spot == (Object)null || !spot.IsOccupied() || (Object)(object)spot.CurrentItem != (Object)(object)previousSlotItem)
				{
					break;
				}
				yield return null;
			}
			if ((Object)(object)heldItem != (Object)null && !heldItem.IsEquipped())
			{
				heldItem.RequestEquip(slotIndex, ownerViewId);
			}
		}
	}
}
namespace ExtraInventorySlots.Input
{
	internal static class SlotHotkeys
	{
		private static readonly MethodInfo HandleInputMethod = AccessTools.Method(typeof(InventorySpot), "HandleInput", (Type[])null, (Type[])null);

		internal static void Poll(InventorySpot spot)
		{
			if (!((Object)(object)spot == (Object)null))
			{
				int inventorySpotIndex = spot.inventorySpotIndex;
				if (SlotSettings.IsExtraSlot(inventorySpotIndex) && WasSlotKeyPressed(inventorySpotIndex))
				{
					HandleInputMethod?.Invoke(spot, Array.Empty<object>());
				}
			}
		}

		private static bool WasSlotKeyPressed(int index)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			Keyboard current = Keyboard.current;
			if (current == null)
			{
				return false;
			}
			if (!WasPressed(current, NumberRowKey(index)))
			{
				if (SlotSettings.NumpadKeys.Value)
				{
					return WasPressed(current, NumpadKey(index));
				}
				return false;
			}
			return true;
		}

		private static bool WasPressed(Keyboard keyboard, Key key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if ((int)key == 0)
			{
				return false;
			}
			KeyControl val = keyboard[key];
			if (val != null)
			{
				return ((ButtonControl)val).wasPressedThisFrame;
			}
			return false;
		}

		private static Key NumberRowKey(int index)
		{
			return (Key)(index switch
			{
				3 => 44, 
				4 => 45, 
				5 => 46, 
				6 => 47, 
				7 => 48, 
				8 => 49, 
				9 => 50, 
				_ => 0, 
			});
		}

		private static Key NumpadKey(int index)
		{
			return (Key)(index switch
			{
				3 => 88, 
				4 => 89, 
				5 => 90, 
				6 => 91, 
				7 => 92, 
				8 => 93, 
				9 => 84, 
				_ => 0, 
			});
		}
	}
}
namespace ExtraInventorySlots.Configuration
{
	internal static class SlotSettings
	{
		internal const int VanillaSlotCount = 3;

		internal const int MaxSlotCount = 10;

		internal static ConfigEntry<int> SlotCount { get; private set; }

		internal static ConfigEntry<bool> EmptyInventoriesBetweenLevels { get; private set; }

		internal static ConfigEntry<bool> SwapWithItemInFullSlot { get; private set; }

		internal static ConfigEntry<bool> LimitClientsToHostSlots { get; private set; }

		internal static ConfigEntry<bool> NumpadKeys { get; private set; }

		internal static int EffectiveSlotCount => Mathf.Clamp(SlotCount?.Value ?? 3, 3, 10);

		internal static bool IsExtraSlot(int slotIndex)
		{
			if (slotIndex >= 3)
			{
				return slotIndex < EffectiveSlotCount;
			}
			return false;
		}

		internal static void Bind(ConfigFile config)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			SlotCount = config.Bind<int>("Slots", "Inventory Slot Count", 5, new ConfigDescription("How many inventory slots you have in total. The game gives you 3. A change takes effect on the next level.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(3, 10), Array.Empty<object>()));
			EmptyInventoriesBetweenLevels = config.Bind<bool>("Slots", "Empty Inventories Between Levels", false, "If on, nobody keeps what they were carrying when a level ends. Every item is left in the truck for the group to pick up again, instead of going back to whoever held it.");
			SwapWithItemInFullSlot = config.Bind<bool>("Slots", "Swap With Item In Full Slot", true, "If on, putting a held item into a slot that is already full swaps the two: the item in the slot comes out and the one you are holding goes in. If off, the slot simply refuses.");
			LimitClientsToHostSlots = config.Bind<bool>("Multiplayer", "Limit Clients To Host Slot Count", true, "If on, nobody in your lobby can use more slots than you have set, even if they configured more for themselves. Only matters when you are the host.");
			NumpadKeys = config.Bind<bool>("Controls", "Numpad Keys For Extra Slots", true, "If on, the numpad numbers work for the extra slots as well as the number row.");
		}

		internal static string SlotLabel(int slotIndex)
		{
			if (slotIndex != 9)
			{
				return (slotIndex + 1).ToString();
			}
			return "0";
		}
	}
}