Decompiled source of TruckArmory v1.0.1

BepInEx/plugins/TruckArmory.dll

Decompiled 4 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
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 Microsoft.CodeAnalysis;
using UnityEngine;

[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("TruckArmory")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+d910f4eafcb32cc585b723613cc57a7682b95ded")]
[assembly: AssemblyProduct("TruckArmory")]
[assembly: AssemblyTitle("TruckArmory")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TruckArmory
{
	internal static class ObjModelLoader
	{
		private static readonly Dictionary<string, (Mesh mesh, Material[] mats)> Cache = new Dictionary<string, (Mesh, Material[])>(StringComparer.OrdinalIgnoreCase);

		public static GameObject? LoadEmbeddedRack(string name = "TruckArmoryRack3D")
		{
			return LoadEmbedded("truck_armory_rack.obj", "truck_armory_rack.mtl", name);
		}

		private static GameObject? LoadEmbedded(string objSuffix, string mtlSuffix, string name)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: 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_0046: Expected O, but got Unknown
			if (Cache.TryGetValue(objSuffix, out (Mesh, Material[]) value) && (Object)(object)value.Item1 != (Object)null)
			{
				GameObject val = new GameObject(name);
				val.AddComponent<MeshFilter>().sharedMesh = value.Item1;
				((Renderer)val.AddComponent<MeshRenderer>()).sharedMaterials = value.Item2;
				return val;
			}
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string text = ReadEmbedded(executingAssembly, objSuffix);
			string text2 = ReadEmbedded(executingAssembly, mtlSuffix);
			if (string.IsNullOrEmpty(text))
			{
				return null;
			}
			Dictionary<string, Material> matMap = ((!string.IsNullOrEmpty(text2)) ? ParseMtl(text2) : new Dictionary<string, Material>());
			GameObject val2 = ParseObj(name, text, matMap);
			MeshFilter component = val2.GetComponent<MeshFilter>();
			MeshRenderer component2 = val2.GetComponent<MeshRenderer>();
			if ((Object)(object)component != (Object)null && (Object)(object)component2 != (Object)null && (Object)(object)component.sharedMesh != (Object)null)
			{
				((Object)component.sharedMesh).hideFlags = (HideFlags)32;
				Material[] sharedMaterials = ((Renderer)component2).sharedMaterials;
				foreach (Material val3 in sharedMaterials)
				{
					if (!((Object)(object)val3 == (Object)null))
					{
						((Object)val3).hideFlags = (HideFlags)32;
						if ((Object)(object)val3.mainTexture != (Object)null)
						{
							((Object)val3.mainTexture).hideFlags = (HideFlags)32;
						}
					}
				}
				Cache[objSuffix] = (component.sharedMesh, ((Renderer)component2).sharedMaterials);
			}
			return val2;
		}

		private static string? ReadEmbedded(Assembly asm, string suffix)
		{
			string[] manifestResourceNames = asm.GetManifestResourceNames();
			foreach (string text in manifestResourceNames)
			{
				if (!text.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
				{
					continue;
				}
				using Stream stream = asm.GetManifestResourceStream(text);
				if (stream == null)
				{
					return null;
				}
				using StreamReader streamReader = new StreamReader(stream);
				return streamReader.ReadToEnd();
			}
			return null;
		}

		private static Texture2D CreatePegboardTexture(Color baseColor)
		{
			//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_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: 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_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(128, 128, (TextureFormat)4, true)
			{
				wrapMode = (TextureWrapMode)0,
				filterMode = (FilterMode)0
			};
			Color val2 = default(Color);
			((Color)(ref val2))..ctor(0.03f, 0.035f, 0.04f, 1f);
			Color val3 = default(Color);
			((Color)(ref val3))..ctor(0.2f, 0.23f, 0.26f, 1f);
			Color val4 = default(Color);
			((Color)(ref val4))..ctor(0.08f, 0.09f, 0.1f, 1f);
			Color[] array = (Color[])(object)new Color[16384];
			for (int i = 0; i < 128; i++)
			{
				for (int j = 0; j < 128; j++)
				{
					float num = (float)j / 128f;
					float num2 = (float)i / 128f;
					float num3 = Mathf.PerlinNoise(num * 6f + 1.3f, num2 * 6f + 4.7f);
					Color val5 = Color.Lerp(baseColor, val4, Mathf.Clamp01((num3 - 0.45f) * 0.45f));
					int num4 = j % 16;
					int num5 = i % 16;
					float num6 = (float)num4 - 7.5f;
					float num7 = (float)num5 - 7.5f;
					float num8 = num6 * num6 + num7 * num7;
					if (num8 <= 5f)
					{
						val5 = val2;
					}
					else if (num8 <= 9f && num7 < 0f)
					{
						val5 = Color.Lerp(val5, val3, 0.35f);
					}
					val5.a = 1f;
					array[i * 128 + j] = val5;
				}
			}
			val.SetPixels(array);
			val.Apply();
			return val;
		}

		private static Texture2D CreateRustyTexture(Color baseColor, float rustAmount, float grimeAmount, int seed)
		{
			//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_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_0162: 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_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(128, 128, (TextureFormat)4, true)
			{
				wrapMode = (TextureWrapMode)0,
				filterMode = (FilterMode)0
			};
			Color val2 = default(Color);
			((Color)(ref val2))..ctor(0.26f, 0.12f, 0.06f, 1f);
			Color val3 = default(Color);
			((Color)(ref val3))..ctor(0.45f, 0.21f, 0.09f, 1f);
			Color val4 = default(Color);
			((Color)(ref val4))..ctor(0.07f, 0.08f, 0.07f, 1f);
			float num = (float)seed * 37.1f % 100f;
			float num2 = (float)seed * 53.7f % 100f;
			Color[] array = (Color[])(object)new Color[16384];
			for (int i = 0; i < 128; i++)
			{
				for (int j = 0; j < 128; j++)
				{
					float num3 = (float)j / 128f;
					float num4 = (float)i / 128f;
					float num5 = Mathf.PerlinNoise(num3 * 4.5f + num, num4 * 4.5f + num2);
					float num6 = Mathf.PerlinNoise(num3 * 11f + num * 1.7f, num4 * 11f + num2 * 1.3f);
					float num7 = Mathf.PerlinNoise(num3 * 24f + num * 2.3f, num4 * 24f + num2 * 2.1f);
					float num8 = num5 * 0.55f + num6 * 0.3f + num7 * 0.15f;
					float num9 = Mathf.PerlinNoise(num3 * 14f + num, num4 * 2.5f + num2);
					Color val5 = baseColor;
					float num10 = Mathf.Clamp01((num9 - 0.35f) * 1.6f) * grimeAmount;
					val5 = Color.Lerp(val5, val4, num10);
					if (rustAmount > 0.01f)
					{
						float num11 = Mathf.Clamp01((num8 - (0.58f - rustAmount * 0.28f)) * 4.2f) * rustAmount;
						Color val6 = Color.Lerp(val2, val3, num6);
						val5 = Color.Lerp(val5, val6, num11);
					}
					float num12 = (num7 - 0.5f) * 0.1f;
					val5.r = Mathf.Clamp01(val5.r + num12);
					val5.g = Mathf.Clamp01(val5.g + num12);
					val5.b = Mathf.Clamp01(val5.b + num12);
					val5.a = 1f;
					array[i * 128 + j] = val5;
				}
			}
			val.SetPixels(array);
			val.Apply();
			return val;
		}

		private static Dictionary<string, Material> ParseMtl(string mtlText)
		{
			//IL_003a: 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_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_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			//IL_0141: 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_0165: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, Material> dictionary = new Dictionary<string, Material>(StringComparer.OrdinalIgnoreCase);
			Shader val = Shader.Find("Standard") ?? Shader.Find("Sprites/Default");
			Material cur = null;
			string curName = "";
			Color curKd = Color.gray;
			int matIdx = 0;
			string[] array = mtlText.Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0 || text[0] == '#')
				{
					continue;
				}
				string[] array2 = text.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
				if (array2.Length < 2)
				{
					continue;
				}
				string text2 = array2[0].ToLowerInvariant();
				if (!(text2 == "newmtl"))
				{
					if (text2 == "kd" && (Object)(object)cur != (Object)null && array2.Length >= 4 && TryColor(array2, out var c))
					{
						curKd = c;
						if (cur.HasProperty("_Color"))
						{
							cur.SetColor("_Color", c);
						}
					}
				}
				else
				{
					FinalizeCurrent();
					curName = array2[1];
					curKd = Color.gray;
					cur = new Material(val)
					{
						name = curName
					};
					dictionary[curName] = cur;
				}
			}
			FinalizeCurrent();
			return dictionary;
			void FinalizeCurrent()
			{
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_009d: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)cur == (Object)null))
				{
					Texture2D val2;
					if (curName.Contains("Gunmetal"))
					{
						val2 = CreatePegboardTexture(curKd);
					}
					else
					{
						float rustAmount = 0.14f;
						float grimeAmount = 0.25f;
						if (curName.Contains("Rubber"))
						{
							rustAmount = 0.04f;
							grimeAmount = 0.25f;
						}
						else if (curName.Contains("HazardYellow"))
						{
							rustAmount = 0.12f;
							grimeAmount = 0.2f;
						}
						else if (curName.Contains("Steel"))
						{
							rustAmount = 0.15f;
							grimeAmount = 0.22f;
						}
						val2 = CreateRustyTexture(curKd, rustAmount, grimeAmount, ++matIdx);
					}
					if (cur.HasProperty("_MainTex"))
					{
						cur.SetTexture("_MainTex", (Texture)(object)val2);
					}
					if (cur.HasProperty("_Color"))
					{
						cur.SetColor("_Color", Color.white);
					}
					if (cur.HasProperty("_Glossiness"))
					{
						cur.SetFloat("_Glossiness", 0.24f);
					}
					if (cur.HasProperty("_Metallic"))
					{
						cur.SetFloat("_Metallic", 0.32f);
					}
				}
			}
		}

		private static bool TryColor(string[] p, out Color c)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			c = Color.white;
			if (float.TryParse(p[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var result) && float.TryParse(p[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var result2) && float.TryParse(p[3], NumberStyles.Float, CultureInfo.InvariantCulture, out var result3))
			{
				c = new Color(result, result2, result3, 1f);
				return true;
			}
			return false;
		}

		private static GameObject ParseObj(string name, string objText, Dictionary<string, Material> matMap)
		{
			//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_037c: Expected O, but got Unknown
			//IL_0427: Unknown result type (might be due to invalid IL or missing references)
			//IL_042c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0439: Unknown result type (might be due to invalid IL or missing references)
			//IL_0447: Expected O, but got Unknown
			//IL_0404: 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_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>();
			List<Vector2> list2 = new List<Vector2>();
			List<Vector3> list3 = new List<Vector3>();
			List<Vector3> list4 = new List<Vector3>();
			List<Vector2> list5 = new List<Vector2>();
			List<Vector3> list6 = new List<Vector3>();
			Dictionary<string, List<int>> dictionary = new Dictionary<string, List<int>>(StringComparer.OrdinalIgnoreCase);
			List<string> list7 = new List<string>();
			string text = "default";
			string[] array = objText.Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length == 0 || text2[0] == '#')
				{
					continue;
				}
				string[] array2 = text2.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
				if (array2.Length < 2)
				{
					continue;
				}
				if (array2[0] == "v" && array2.Length >= 4)
				{
					float num = float.Parse(array2[1], CultureInfo.InvariantCulture);
					float num2 = float.Parse(array2[2], CultureInfo.InvariantCulture);
					float num3 = float.Parse(array2[3], CultureInfo.InvariantCulture);
					list.Add(new Vector3(0f - num, num2, num3));
				}
				else if (array2[0] == "vt" && array2.Length >= 3)
				{
					float num4 = float.Parse(array2[1], CultureInfo.InvariantCulture);
					float num5 = float.Parse(array2[2], CultureInfo.InvariantCulture);
					list2.Add(new Vector2(num4, num5));
				}
				else if (array2[0] == "vn" && array2.Length >= 4)
				{
					float num6 = float.Parse(array2[1], CultureInfo.InvariantCulture);
					float num7 = float.Parse(array2[2], CultureInfo.InvariantCulture);
					float num8 = float.Parse(array2[3], CultureInfo.InvariantCulture);
					list3.Add(new Vector3(0f - num6, num7, num8));
				}
				else if (array2[0] == "usemtl")
				{
					text = array2[1];
					if (!dictionary.ContainsKey(text))
					{
						dictionary[text] = new List<int>();
						list7.Add(text);
					}
				}
				else
				{
					if (!(array2[0] == "f") || array2.Length < 4)
					{
						continue;
					}
					if (!dictionary.ContainsKey(text))
					{
						dictionary[text] = new List<int>();
						list7.Add(text);
					}
					List<int> list8 = dictionary[text];
					int count = list4.Count;
					int num9 = array2.Length - 1;
					for (int j = 1; j <= num9; j++)
					{
						string[] array3 = array2[j].Split('/');
						int num10 = int.Parse(array3[0], CultureInfo.InvariantCulture) - 1;
						list4.Add((num10 >= 0 && num10 < list.Count) ? list[num10] : Vector3.zero);
						if (array3.Length >= 2 && int.TryParse(array3[1], out var result) && result - 1 >= 0 && result - 1 < list2.Count)
						{
							list5.Add(list2[result - 1]);
						}
						else
						{
							list5.Add(Vector2.zero);
						}
						if (array3.Length >= 3 && int.TryParse(array3[2], out var result2) && result2 - 1 >= 0 && result2 - 1 < list3.Count)
						{
							list6.Add(list3[result2 - 1]);
						}
						else
						{
							list6.Add(Vector3.up);
						}
					}
					for (int k = 1; k < num9 - 1; k++)
					{
						list8.Add(count);
						list8.Add(count + k + 1);
						list8.Add(count + k);
					}
				}
			}
			Mesh val = new Mesh
			{
				name = name
			};
			val.SetVertices(list4);
			val.SetUVs(0, list5);
			val.SetNormals(list6);
			val.subMeshCount = list7.Count;
			Material[] array4 = (Material[])(object)new Material[list7.Count];
			Shader val2 = Shader.Find("Standard") ?? Shader.Find("Sprites/Default");
			for (int l = 0; l < list7.Count; l++)
			{
				val.SetTriangles(dictionary[list7[l]], l);
				array4[l] = (Material)(matMap.TryGetValue(list7[l], out Material value) ? ((object)value) : ((object)new Material(val2)));
			}
			val.RecalculateBounds();
			GameObject val3 = new GameObject(name);
			val3.AddComponent<MeshFilter>().sharedMesh = val;
			((Renderer)val3.AddComponent<MeshRenderer>()).sharedMaterials = array4;
			return val3;
		}
	}
	[BepInPlugin("com.moongetsu.truckarmory", "TruckArmory", "1.0.1")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.moongetsu.truckarmory";

		public const string PluginName = "TruckArmory";

		public const string PluginVersion = "1.0.1";

		internal static ManualLogSource Log;

		internal static Plugin Instance;

		internal static ConfigEntry<bool> EnableMod;

		internal static ConfigEntry<bool> ShowRackModel;

		internal static ConfigEntry<bool> AutoOrganizeOnStart;

		internal static ConfigEntry<bool> EnableReturnToRack;

		internal static ConfigEntry<bool> StackDuplicates;

		internal static ConfigEntry<bool> HideBatteryWhileRacked;

		internal static ConfigEntry<float> ReturnSnapDistance;

		internal static ConfigEntry<float> DefaultRackScale;

		internal static ConfigEntry<bool> EnableLayoutHotkeys;

		internal static ConfigEntry<KeyCode> SpawnRackKey;

		internal static ConfigEntry<KeyCode> MoveNearestKey;

		internal static ConfigEntry<KeyCode> RotateNearestKey;

		internal static ConfigEntry<KeyCode> RemoveNearestKey;

		internal static ConfigEntry<KeyCode> ReorganizeNowKey;

		private Harmony? _harmony;

		private void Awake()
		{
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Expected O, but got Unknown
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Expected O, but got Unknown
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			EnableMod = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EnableMod", true, "Master switch for TruckArmory.");
			ShowRackModel = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShowRackModel", true, "Show the 3D wall-mounted pegboard models inside the truck.");
			AutoOrganizeOnStart = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AutoOrganizeOnStart", true, "Automatically hang purchased weapons and equipment onto the wall racks when a level starts.");
			EnableReturnToRack = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EnableReturnToRack", true, "Snap items back onto empty/matching rack hooks when released near a pegboard.");
			StackDuplicates = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "StackDuplicates", true, "Stack identical items neatly on the same hook/shelf slot (up to 6 on hooks, 10 on shelf).");
			HideBatteryWhileRacked = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "HideBatteryWhileRacked", true, "Hide floating battery/energy bars on items while they are hanging on the armory racks (reappears immediately when grabbed).");
			ReturnSnapDistance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ReturnSnapDistance", 0.42f, new ConfigDescription("Distance (meters) from an empty/matching rack slot at which a released item snaps onto it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.15f, 1f), Array.Empty<object>()));
			DefaultRackScale = ((BaseUnityPlugin)this).Config.Bind<float>("General", "DefaultRackScale", 1f, new ConfigDescription("Default scale for newly spawned racks.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 1.6f), Array.Empty<object>()));
			EnableLayoutHotkeys = ((BaseUnityPlugin)this).Config.Bind<bool>("Hotkeys", "EnableLayoutHotkeys", false, "Enable rack layout builder hotkeys (F8 spawn, F7 move nearest, F9 rotate nearest, F10 remove nearest, F6 reorganize, F11 test arsenal).");
			SpawnRackKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Hotkeys", "SpawnRackKey", (KeyCode)289, "Aim at a wall in the truck and press to SPAWN a new rack there (auto-saves layout).");
			MoveNearestKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Hotkeys", "MoveNearestKey", (KeyCode)288, "Aim at a wall and press to MOVE the nearest rack there (auto-saves layout).");
			RotateNearestKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Hotkeys", "RotateNearestKey", (KeyCode)290, "Rotate nearest rack +15 deg (Shift+F9 = -15 deg, Ctrl+F9 = snap to 90 deg).");
			RemoveNearestKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Hotkeys", "RemoveNearestKey", (KeyCode)291, "Remove the nearest rack within 3.5m (auto-saves layout).");
			ReorganizeNowKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Hotkeys", "ReorganizeNowKey", (KeyCode)287, "Re-hang all loose truck items across all placed racks immediately.");
			EnableMod.SettingChanged += delegate
			{
				if (!EnableMod.Value)
				{
					ArmoryManager.Cleanup();
				}
				else
				{
					ArmoryManager.OnLevelReady();
				}
			};
			_harmony = new Harmony("com.moongetsu.truckarmory");
			_harmony.PatchAll();
			GameObject val = new GameObject("TruckArmory_Manager");
			Object.DontDestroyOnLoad((Object)val);
			val.AddComponent<ArmoryManager>();
			Log.LogInfo((object)"TruckArmory v1.0.1 loaded!");
		}

		private void OnDestroy()
		{
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	[HarmonyPatch]
	internal static class LifecyclePatches
	{
		[HarmonyPatch(typeof(SemiFunc), "OnLevelGenDone")]
		[HarmonyPostfix]
		private static void OnLevelGenDonePostfix()
		{
			ArmoryManager.OnLevelReady();
		}

		[HarmonyPatch(typeof(RunManager), "LeaveToMainMenu")]
		[HarmonyPostfix]
		private static void OnLeaveToMainMenuPostfix()
		{
			ArmoryManager.Cleanup();
		}

		[HarmonyPatch(typeof(GameDirector), "OutroStart")]
		[HarmonyPostfix]
		private static void OnOutroStartPostfix()
		{
			ArmoryManager.ReleaseAllForOutro();
		}
	}
	[Serializable]
	public class RackPlacementData
	{
		public float x;

		public float y;

		public float z;

		public float rotY;

		public float scale = 1f;
	}
	[Serializable]
	public class RackLayoutFile
	{
		public List<RackPlacementData> Racks = new List<RackPlacementData>();
	}
	internal enum RackCategory
	{
		None,
		Weapon,
		Tech,
		Shelf
	}
	internal class RackSlot
	{
		public RackCategory Category;

		public Transform BayTransform;

		public Vector3 LocalPos;

		public Quaternion LocalRot;

		public string? ItemKey;

		public readonly List<PhysGrabObject> Stack = new List<PhysGrabObject>();

		public int MaxStack
		{
			get
			{
				if (!Plugin.StackDuplicates.Value)
				{
					return 1;
				}
				if (Category != RackCategory.Shelf)
				{
					return 6;
				}
				return 10;
			}
		}

		public bool IsEmpty => Stack.Count == 0;

		public bool CanAccept(string key)
		{
			if (Stack.Count != 0)
			{
				if (Plugin.StackDuplicates.Value && ItemKey == key)
				{
					return Stack.Count < MaxStack;
				}
				return false;
			}
			return true;
		}

		public Vector3 GetSlotWorldPos(int stackIndex)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: 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)
			Vector3 val = ((Category == RackCategory.Shelf) ? new Vector3(0f, 0.035f * (float)stackIndex, 0.025f * (float)stackIndex) : new Vector3(0f, 0f, 0.045f * (float)stackIndex));
			return BayTransform.TransformPoint(LocalPos + val);
		}

		public Quaternion GetSlotWorldRot()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//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)
			return BayTransform.rotation * LocalRot;
		}
	}
	internal class RackBay
	{
		public GameObject Go;

		public RackPlacementData Data;

		public readonly List<RackSlot> Slots = new List<RackSlot>();
	}
	internal class ArmoryManager : MonoBehaviour
	{
		private static ArmoryManager? _instance;

		private Transform? _anchorTransform;

		private readonly List<RackBay> _bays = new List<RackBay>();

		private readonly Dictionary<PhysGrabObject, float> _recentlyReleased = new Dictionary<PhysGrabObject, float>();

		private readonly List<GameObject> _devSpawnedItems = new List<GameObject>();

		private readonly HashSet<PhysGrabObject> _clientHiddenBatteries = new HashSet<PhysGrabObject>();

		private float _snapScanTimer;

		private float _clientBatteryTimer;

		private static string LayoutFilePath => Path.Combine(Paths.ConfigPath, "truck_armory_layout.json");

		private void Awake()
		{
			_instance = this;
		}

		private void OnDestroy()
		{
			CleanupInternal();
			if ((Object)(object)_instance == (Object)(object)this)
			{
				_instance = null;
			}
		}

		public static bool IsAllowedScene()
		{
			try
			{
				return !SemiFunc.RunIsArena();
			}
			catch
			{
				return true;
			}
		}

		public static void OnLevelReady()
		{
			_instance?.SpawnLayoutAndOrganize();
		}

		public static void Cleanup()
		{
			_instance?.CleanupInternal();
		}

		public static void ReleaseAllForOutro()
		{
			_instance?.ReleaseAllItemsInternal();
		}

		private void ReleaseAllItemsInternal()
		{
			foreach (RackSlot item in AllSlots())
			{
				foreach (PhysGrabObject item2 in item.Stack)
				{
					if ((Object)(object)item2 != (Object)null)
					{
						if (SemiFunc.IsMasterClientOrSingleplayer())
						{
							item2.OverrideKinematic(0f);
						}
						SetBatteryVisualVisible(item2, visible: true);
					}
				}
				item.Stack.Clear();
				item.ItemKey = null;
			}
		}

		private void CleanupInternal()
		{
			((MonoBehaviour)this).StopAllCoroutines();
			foreach (RackSlot item in AllSlots())
			{
				foreach (PhysGrabObject item2 in item.Stack)
				{
					if ((Object)(object)item2 != (Object)null)
					{
						if (SemiFunc.IsMasterClientOrSingleplayer())
						{
							item2.OverrideKinematic(0f);
						}
						SetBatteryVisualVisible(item2, visible: true);
					}
				}
			}
			foreach (PhysGrabObject clientHiddenBattery in _clientHiddenBatteries)
			{
				if ((Object)(object)clientHiddenBattery != (Object)null)
				{
					SetBatteryVisualVisible(clientHiddenBattery, visible: true);
				}
			}
			_clientHiddenBatteries.Clear();
			foreach (RackBay bay in _bays)
			{
				if ((Object)(object)bay.Go != (Object)null)
				{
					Object.Destroy((Object)(object)bay.Go);
				}
			}
			foreach (GameObject devSpawnedItem in _devSpawnedItems)
			{
				if ((Object)(object)devSpawnedItem != (Object)null)
				{
					Object.Destroy((Object)(object)devSpawnedItem);
				}
			}
			_devSpawnedItems.Clear();
			_bays.Clear();
			_recentlyReleased.Clear();
			_anchorTransform = null;
		}

		private RackLayoutFile LoadLayout()
		{
			try
			{
				if (File.Exists(LayoutFilePath))
				{
					string text = File.ReadAllText(LayoutFilePath);
					RackLayoutFile rackLayoutFile = JsonUtility.FromJson<RackLayoutFile>(text);
					if (rackLayoutFile != null && rackLayoutFile.Racks != null && text.Contains("\"Racks\""))
					{
						return rackLayoutFile;
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Failed to load layout file: " + ex.Message));
			}
			RackLayoutFile rackLayoutFile2 = new RackLayoutFile();
			float[] array = new float[2] { 4.2f, 6.48f };
			float[] array2 = new float[2] { -1.12f, 0.08f };
			float[] array3 = array;
			foreach (float x in array3)
			{
				float[] array4 = array2;
				foreach (float y in array4)
				{
					rackLayoutFile2.Racks.Add(new RackPlacementData
					{
						x = x,
						y = y,
						z = 2.1f,
						rotY = 180f,
						scale = 1f
					});
					rackLayoutFile2.Racks.Add(new RackPlacementData
					{
						x = x,
						y = y,
						z = -2.1f,
						rotY = 0f,
						scale = 1f
					});
				}
			}
			return rackLayoutFile2;
		}

		private void SaveLayout()
		{
			try
			{
				RackLayoutFile rackLayoutFile = new RackLayoutFile();
				foreach (RackBay bay in _bays)
				{
					rackLayoutFile.Racks.Add(bay.Data);
				}
				File.WriteAllText(LayoutFilePath, JsonUtility.ToJson((object)rackLayoutFile, true));
				Plugin.Log.LogInfo((object)$"[Layout] Saved {rackLayoutFile.Racks.Count} rack(s) to {LayoutFilePath}");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Failed to save layout file: " + ex.Message));
			}
		}

		private void SpawnLayoutAndOrganize()
		{
			CleanupInternal();
			if (!Plugin.EnableMod.Value || !IsAllowedScene())
			{
				return;
			}
			Transform val = (((Object)(object)TruckSafetySpawnPoint.instance != (Object)null) ? ((Component)TruckSafetySpawnPoint.instance).transform : (((Object)(object)TruckHealer.instance != (Object)null) ? ((Component)TruckHealer.instance).transform : null));
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			_anchorTransform = val;
			foreach (RackPlacementData rack in LoadLayout().Racks)
			{
				SpawnBay(rack);
			}
			Plugin.Log.LogInfo((object)$"Spawned {_bays.Count} TruckArmory rack(s) anchored to '{((Object)val).name}'.");
			if (Plugin.AutoOrganizeOnStart.Value && SemiFunc.IsMasterClientOrSingleplayer() && !SemiFunc.RunIsShop())
			{
				((MonoBehaviour)this).StartCoroutine(DelayedOrganizeCoroutine());
			}
		}

		private RackBay SpawnBay(RackPlacementData data)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			string text = $"TruckArmoryBay_{_bays.Count + 1}";
			GameObject val = (GameObject)(Plugin.ShowRackModel.Value ? (((object)ObjModelLoader.LoadEmbeddedRack(text)) ?? ((object)new GameObject(text))) : ((object)new GameObject(text)));
			val.transform.SetParent(_anchorTransform, false);
			ApplyBayTransform(val.transform, data);
			RackBay rackBay = new RackBay
			{
				Go = val,
				Data = data
			};
			BuildSlotsForBay(rackBay);
			_bays.Add(rackBay);
			return rackBay;
		}

		private static void ApplyBayTransform(Transform t, RackPlacementData d)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			t.localPosition = new Vector3(d.x, d.y, d.z);
			t.localRotation = Quaternion.Euler(0f, d.rotY, 0f);
			t.localScale = Vector3.one * Mathf.Clamp((d.scale <= 0.01f) ? 1f : d.scale, 0.4f, 2f);
		}

		private static void BuildSlotsForBay(RackBay bay)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: 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_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: 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)
			Transform transform = bay.Go.transform;
			float[] array = new float[3] { 1.04f, 0.84f, 0.64f };
			foreach (float num in array)
			{
				bay.Slots.Add(new RackSlot
				{
					Category = RackCategory.Weapon,
					BayTransform = transform,
					LocalPos = new Vector3(0.54f, num, 0.14f),
					LocalRot = Quaternion.Euler(0f, 90f, 0f)
				});
			}
			float[] array2 = new float[3] { -0.24f, -0.56f, -0.88f };
			array = new float[2] { 0.96f, 0.64f };
			foreach (float num2 in array)
			{
				float[] array3 = array2;
				foreach (float num3 in array3)
				{
					bay.Slots.Add(new RackSlot
					{
						Category = RackCategory.Tech,
						BayTransform = transform,
						LocalPos = new Vector3(num3, num2, 0.14f),
						LocalRot = Quaternion.identity
					});
				}
			}
			for (int k = 0; k < 7; k++)
			{
				float num4 = Mathf.Lerp(0.88f, -0.88f, (float)k / 6f);
				bay.Slots.Add(new RackSlot
				{
					Category = RackCategory.Shelf,
					BayTransform = transform,
					LocalPos = new Vector3(num4, 0.42f, 0.16f),
					LocalRot = Quaternion.identity
				});
			}
		}

		private IEnumerator DelayedOrganizeCoroutine()
		{
			yield return (object)new WaitForSeconds(1.2f);
			OrganizeTruckItems();
		}

		private static bool IsRackableVolume(Item item)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected I4, but got Unknown
			int num = (int)item.itemVolume;
			if (num != 0 && num != 1 && num != 4)
			{
				return num == 7;
			}
			return true;
		}

		private static RackCategory ClassifyItem(ItemAttributes attrs)
		{
			if ((Object)(object)attrs == (Object)null || (Object)(object)attrs.item == (Object)null)
			{
				return RackCategory.None;
			}
			return ClassifyItemDef(attrs.item);
		}

		private static RackCategory ClassifyItemDef(Item item)
		{
			//IL_0014: 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)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected I4, but got Unknown
			if ((Object)(object)item == (Object)null || !IsRackableVolume(item))
			{
				return RackCategory.None;
			}
			itemType itemType = item.itemType;
			switch ((int)itemType)
			{
			case 7:
			case 9:
				return RackCategory.Weapon;
			case 0:
			case 1:
			case 10:
			case 13:
				return RackCategory.Tech;
			case 5:
			case 6:
			case 8:
			case 11:
				return RackCategory.Shelf;
			default:
				if (((object)Unsafe.As<itemType, itemType>(ref item.itemType)/*cast due to .constrained prefix*/).ToString().ToLowerInvariant().Contains("launcher"))
				{
					return RackCategory.Weapon;
				}
				return RackCategory.None;
			}
		}

		private static string GetItemKey(ItemAttributes attrs)
		{
			if ((Object)(object)attrs.item != (Object)null && !string.IsNullOrEmpty(attrs.item.itemName))
			{
				return attrs.item.itemName;
			}
			if (!((Object)(object)attrs.item != (Object)null))
			{
				return ((Object)((Component)attrs).gameObject).name;
			}
			return ((Object)attrs.item).name;
		}

		private IEnumerable<RackSlot> AllSlots()
		{
			foreach (RackBay bay in _bays)
			{
				foreach (RackSlot slot in bay.Slots)
				{
					yield return slot;
				}
			}
		}

		private void OrganizeTruckItems()
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_anchorTransform == (Object)null || _bays.Count == 0 || !SemiFunc.IsMasterClientOrSingleplayer() || SemiFunc.RunIsShop())
			{
				return;
			}
			int num = 0;
			ItemAttributes[] array = Object.FindObjectsOfType<ItemAttributes>();
			foreach (ItemAttributes val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				RackCategory rackCategory = ClassifyItem(val);
				if (rackCategory == RackCategory.None)
				{
					continue;
				}
				PhysGrabObject component = ((Component)val).GetComponent<PhysGrabObject>();
				if (!((Object)(object)component == (Object)null) && !component.grabbed && !IsAlreadyRacked(component) && !(Vector3.Distance(((Component)component).transform.position, _anchorTransform.position) > 9.5f))
				{
					string itemKey = GetItemKey(val);
					RackSlot rackSlot = FindSlotForItem(rackCategory, itemKey);
					if (rackSlot != null)
					{
						RackItemIntoSlot(component, itemKey, rackSlot, playSound: false);
						num++;
					}
				}
			}
			if (num > 0)
			{
				Plugin.Log.LogInfo((object)$"Organized {num} truck items across {_bays.Count} rack(s).");
			}
		}

		private bool IsAlreadyRacked(PhysGrabObject pgo)
		{
			foreach (RackSlot item in AllSlots())
			{
				if (item.Stack.Contains(pgo))
				{
					return true;
				}
			}
			return false;
		}

		private RackSlot? FindSlotForItem(RackCategory preferred, string key)
		{
			foreach (RackSlot item in AllSlots())
			{
				if (item.IsEmpty && item.Category == preferred)
				{
					return item;
				}
			}
			foreach (RackSlot item2 in AllSlots())
			{
				if (item2.IsEmpty)
				{
					return item2;
				}
			}
			if (Plugin.StackDuplicates.Value)
			{
				foreach (RackSlot item3 in AllSlots())
				{
					if (!item3.IsEmpty && item3.CanAccept(key))
					{
						return item3;
					}
				}
			}
			return null;
		}

		private static void SetBatteryVisualVisible(PhysGrabObject pgo, bool visible)
		{
			BatteryVisualLogic componentInChildren = ((Component)pgo).GetComponentInChildren<BatteryVisualLogic>(true);
			if ((Object)(object)componentInChildren != (Object)null && ((Component)componentInChildren).gameObject.activeSelf != visible)
			{
				((Component)componentInChildren).gameObject.SetActive(visible);
			}
		}

		private static Quaternion GetItemWorldRot(RackSlot slot, PhysGrabObject pgo)
		{
			//IL_0052: 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_002a: Invalid comparison between Unknown and I4
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			ItemAttributes component = ((Component)pgo).GetComponent<ItemAttributes>();
			if ((Object)(object)component != (Object)null && (Object)(object)component.item != (Object)null && (int)component.item.itemType == 7)
			{
				return slot.BayTransform.rotation * Quaternion.Euler(0f, 0f, 90f);
			}
			return slot.GetSlotWorldRot();
		}

		private void RackItemIntoSlot(PhysGrabObject pgo, string key, RackSlot slot, bool playSound)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			if (slot.IsEmpty)
			{
				slot.ItemKey = key;
			}
			int count = slot.Stack.Count;
			slot.Stack.Add(pgo);
			Vector3 slotWorldPos = slot.GetSlotWorldPos(count);
			pgo.Teleport(slotWorldPos, GetItemWorldRot(slot, pgo));
			pgo.OverrideKinematic(0.25f);
			SetBatteryVisualVisible(pgo, !Plugin.HideBatteryWhileRacked.Value);
			if (!playSound)
			{
				return;
			}
			MenuManager instance = MenuManager.instance;
			if (instance != null)
			{
				Sound soundTick = instance.soundTick;
				if (soundTick != null)
				{
					soundTick.Play(slotWorldPos, 1f, 1f, 1f, 1f);
				}
			}
		}

		private void Update()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_anchorTransform == (Object)null || !Plugin.EnableMod.Value)
			{
				return;
			}
			Camera val = GameDirector.instance?.MainCamera ?? Camera.main;
			if (Plugin.EnableLayoutHotkeys.Value && (Object)(object)val != (Object)null)
			{
				if ((int)Plugin.SpawnRackKey.Value != 0 && Input.GetKeyDown(Plugin.SpawnRackKey.Value))
				{
					SpawnRackAtCrosshair(val);
				}
				else if ((int)Plugin.MoveNearestKey.Value != 0 && Input.GetKeyDown(Plugin.MoveNearestKey.Value))
				{
					MoveNearestRackToCrosshair(val);
				}
				else if ((int)Plugin.RotateNearestKey.Value != 0 && Input.GetKeyDown(Plugin.RotateNearestKey.Value))
				{
					RotateNearestRack(val);
				}
				else if ((int)Plugin.RemoveNearestKey.Value != 0 && Input.GetKeyDown(Plugin.RemoveNearestKey.Value))
				{
					RemoveNearestRack(val);
				}
				else if ((int)Plugin.ReorganizeNowKey.Value != 0 && Input.GetKeyDown(Plugin.ReorganizeNowKey.Value))
				{
					OrganizeTruckItems();
				}
				else if (Input.GetKeyDown((KeyCode)292))
				{
					SpawnTestArsenal();
				}
			}
			if (!SemiFunc.IsMasterClientOrSingleplayer())
			{
				_clientBatteryTimer += Time.deltaTime;
				if (_clientBatteryTimer >= 0.25f)
				{
					_clientBatteryTimer = 0f;
					SyncClientBatteryVisuals(val);
				}
				return;
			}
			if (_recentlyReleased.Count > 0)
			{
				foreach (PhysGrabObject item in new List<PhysGrabObject>(_recentlyReleased.Keys))
				{
					if ((Object)(object)item == (Object)null)
					{
						_recentlyReleased.Remove(item);
						continue;
					}
					_recentlyReleased[item] -= Time.deltaTime;
					if (_recentlyReleased[item] <= 0f)
					{
						_recentlyReleased.Remove(item);
					}
				}
			}
			foreach (RackSlot item2 in AllSlots())
			{
				for (int num = item2.Stack.Count - 1; num >= 0; num--)
				{
					PhysGrabObject val2 = item2.Stack[num];
					if ((Object)(object)val2 == (Object)null || !((Component)val2).gameObject.activeInHierarchy)
					{
						item2.Stack.RemoveAt(num);
					}
					else if (val2.grabbed)
					{
						item2.Stack.RemoveAt(num);
						val2.OverrideKinematic(0f);
						SetBatteryVisualVisible(val2, visible: true);
						_recentlyReleased[val2] = 1.5f;
					}
					else
					{
						val2.OverrideKinematic(0.25f);
						SetBatteryVisualVisible(val2, !Plugin.HideBatteryWhileRacked.Value);
					}
				}
				if (item2.IsEmpty)
				{
					item2.ItemKey = null;
				}
			}
			if (Plugin.EnableReturnToRack.Value && !SemiFunc.RunIsShop() && IsAnyPlayerNearTruck())
			{
				_snapScanTimer += Time.deltaTime;
				if (_snapScanTimer >= 0.25f)
				{
					_snapScanTimer = 0f;
					TrySnapNearbyItems();
				}
			}
		}

		private bool IsAnyPlayerNearTruck()
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_anchorTransform == (Object)null)
			{
				return false;
			}
			List<PlayerAvatar> list = GameDirector.instance?.PlayerList;
			if (list == null || list.Count == 0)
			{
				return true;
			}
			foreach (PlayerAvatar item in list)
			{
				if ((Object)(object)item != (Object)null && Vector3.Distance(((Component)item).transform.position, _anchorTransform.position) <= 12f)
				{
					return true;
				}
			}
			return false;
		}

		private void SyncClientBatteryVisuals(Camera? mainCam)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: 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)
			if ((Object)(object)_anchorTransform == (Object)null || !Plugin.HideBatteryWhileRacked.Value)
			{
				foreach (PhysGrabObject clientHiddenBattery in _clientHiddenBatteries)
				{
					if ((Object)(object)clientHiddenBattery != (Object)null)
					{
						SetBatteryVisualVisible(clientHiddenBattery, visible: true);
					}
				}
				_clientHiddenBatteries.Clear();
			}
			else
			{
				if ((Object)(object)mainCam != (Object)null && Vector3.Distance(((Component)mainCam).transform.position, _anchorTransform.position) > 12f)
				{
					return;
				}
				HashSet<PhysGrabObject> hashSet = new HashSet<PhysGrabObject>();
				ItemAttributes[] array = Object.FindObjectsOfType<ItemAttributes>();
				foreach (ItemAttributes val in array)
				{
					if ((Object)(object)val == (Object)null || ClassifyItem(val) == RackCategory.None)
					{
						continue;
					}
					PhysGrabObject component = ((Component)val).GetComponent<PhysGrabObject>();
					if ((Object)(object)component == (Object)null || component.grabbed || !((Component)component).gameObject.activeInHierarchy)
					{
						continue;
					}
					foreach (RackSlot item in AllSlots())
					{
						if (Vector3.Distance(((Component)component).transform.position, item.GetSlotWorldPos(0)) <= 0.38f)
						{
							SetBatteryVisualVisible(component, visible: false);
							hashSet.Add(component);
							_clientHiddenBatteries.Add(component);
							break;
						}
					}
				}
				List<PhysGrabObject> list = new List<PhysGrabObject>();
				foreach (PhysGrabObject clientHiddenBattery2 in _clientHiddenBatteries)
				{
					if ((Object)(object)clientHiddenBattery2 == (Object)null || !hashSet.Contains(clientHiddenBattery2))
					{
						list.Add(clientHiddenBattery2);
					}
				}
				foreach (PhysGrabObject item2 in list)
				{
					if ((Object)(object)item2 != (Object)null)
					{
						SetBatteryVisualVisible(item2, visible: true);
					}
					_clientHiddenBatteries.Remove(item2);
				}
			}
		}

		private void TrySnapNearbyItems()
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			float value = Plugin.ReturnSnapDistance.Value;
			ItemAttributes[] array = Object.FindObjectsOfType<ItemAttributes>();
			foreach (ItemAttributes val in array)
			{
				if ((Object)(object)val == (Object)null || ClassifyItem(val) == RackCategory.None)
				{
					continue;
				}
				PhysGrabObject component = ((Component)val).GetComponent<PhysGrabObject>();
				if ((Object)(object)component == (Object)null || component.grabbed || IsAlreadyRacked(component) || _recentlyReleased.ContainsKey(component))
				{
					continue;
				}
				string itemKey = GetItemKey(val);
				RackSlot rackSlot = null;
				float num = value;
				foreach (RackSlot item in AllSlots())
				{
					if (item.CanAccept(itemKey))
					{
						float num2 = Vector3.Distance(((Component)component).transform.position, item.GetSlotWorldPos(item.Stack.Count));
						if (num2 < num)
						{
							num = num2;
							rackSlot = item;
						}
					}
				}
				if (rackSlot != null)
				{
					RackItemIntoSlot(component, itemKey, rackSlot, playSound: true);
				}
			}
		}

		private bool RaycastTruckSurface(Camera mainCam, out Vector3 localPos, out float localYaw)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: 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_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			localPos = Vector3.zero;
			localYaw = 0f;
			if ((Object)(object)_anchorTransform == (Object)null)
			{
				return false;
			}
			RaycastHit[] array = Physics.RaycastAll(((Component)mainCam).transform.position, ((Component)mainCam).transform.forward, 8f, -1, (QueryTriggerInteraction)1);
			Array.Sort(array, (RaycastHit a, RaycastHit b) => ((RaycastHit)(ref a)).distance.CompareTo(((RaycastHit)(ref b)).distance));
			RaycastHit[] array2 = array;
			for (int num = 0; num < array2.Length; num++)
			{
				RaycastHit val = array2[num];
				if ((Object)(object)((RaycastHit)(ref val)).collider == (Object)null || ((Object)(object)PlayerAvatar.instance != (Object)null && ((Component)((RaycastHit)(ref val)).collider).transform.IsChildOf(((Component)PlayerAvatar.instance).transform)))
				{
					continue;
				}
				bool flag = false;
				foreach (RackBay bay in _bays)
				{
					if ((Object)(object)bay.Go != (Object)null && ((Component)((RaycastHit)(ref val)).collider).transform.IsChildOf(bay.Go.transform))
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					localPos = _anchorTransform.InverseTransformPoint(((RaycastHit)(ref val)).point);
					Vector3 val2 = ((Component)mainCam).transform.position - ((RaycastHit)(ref val)).point;
					val2.y = 0f;
					float num2;
					if (!(((Vector3)(ref val2)).sqrMagnitude > 0.001f))
					{
						num2 = 0f;
					}
					else
					{
						Quaternion val3 = Quaternion.LookRotation(((Vector3)(ref val2)).normalized, Vector3.up);
						num2 = ((Quaternion)(ref val3)).eulerAngles.y;
					}
					float num3 = num2;
					localYaw = Mathf.DeltaAngle(_anchorTransform.eulerAngles.y, num3);
					return true;
				}
			}
			return false;
		}

		private RackBay? FindNearestBay(Vector3 worldPos, float maxDist = 4.5f)
		{
			//IL_0028: 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)
			RackBay result = null;
			float num = maxDist;
			foreach (RackBay bay in _bays)
			{
				if (!((Object)(object)bay.Go == (Object)null))
				{
					float num2 = Vector3.Distance(worldPos, bay.Go.transform.position);
					if (num2 < num)
					{
						num = num2;
						result = bay;
					}
				}
			}
			return result;
		}

		private void SyncBayItems(RackBay bay)
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			if (!SemiFunc.IsMasterClientOrSingleplayer())
			{
				return;
			}
			foreach (RackSlot slot in bay.Slots)
			{
				for (int i = 0; i < slot.Stack.Count; i++)
				{
					if ((Object)(object)slot.Stack[i] != (Object)null && !slot.Stack[i].grabbed)
					{
						slot.Stack[i].Teleport(slot.GetSlotWorldPos(i), GetItemWorldRot(slot, slot.Stack[i]));
					}
				}
			}
		}

		private void SpawnRackAtCrosshair(Camera mainCam)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if (!RaycastTruckSurface(mainCam, out var localPos, out var localYaw))
			{
				return;
			}
			RackPlacementData rackPlacementData = new RackPlacementData
			{
				x = (float)Math.Round(localPos.x, 4),
				y = (float)Math.Round(localPos.y, 4),
				z = (float)Math.Round(localPos.z, 4),
				rotY = (float)Math.Round(localYaw, 1),
				scale = Plugin.DefaultRackScale.Value
			};
			RackBay rackBay = SpawnBay(rackPlacementData);
			SaveLayout();
			MenuManager instance = MenuManager.instance;
			if (instance != null)
			{
				Sound soundConfirm = instance.soundConfirm;
				if (soundConfirm != null)
				{
					soundConfirm.Play(rackBay.Go.transform.position, 1f, 1f, 1f, 1f);
				}
			}
			Plugin.Log.LogInfo((object)$"[F8 SPAWN] Rack #{_bays.Count} at ({rackPlacementData.x}, {rackPlacementData.y}, {rackPlacementData.z}) rotY={rackPlacementData.rotY}");
		}

		private void MoveNearestRackToCrosshair(Camera mainCam)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			RackBay rackBay = FindNearestBay(((Component)mainCam).transform.position, 6f);
			if (rackBay == null || !RaycastTruckSurface(mainCam, out var localPos, out var localYaw))
			{
				return;
			}
			rackBay.Data.x = (float)Math.Round(localPos.x, 4);
			rackBay.Data.y = (float)Math.Round(localPos.y, 4);
			rackBay.Data.z = (float)Math.Round(localPos.z, 4);
			rackBay.Data.rotY = (float)Math.Round(localYaw, 1);
			ApplyBayTransform(rackBay.Go.transform, rackBay.Data);
			SyncBayItems(rackBay);
			SaveLayout();
			MenuManager instance = MenuManager.instance;
			if (instance != null)
			{
				Sound soundTick = instance.soundTick;
				if (soundTick != null)
				{
					soundTick.Play(rackBay.Go.transform.position, 1f, 1f, 1f, 1f);
				}
			}
			Plugin.Log.LogInfo((object)$"[F7 MOVE] Moved rack to ({rackBay.Data.x}, {rackBay.Data.y}, {rackBay.Data.z}) rotY={rackBay.Data.rotY}");
		}

		private void RotateNearestRack(Camera mainCam)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			RackBay rackBay = FindNearestBay(((Component)mainCam).transform.position, 6f);
			if (rackBay == null)
			{
				return;
			}
			if (Input.GetKey((KeyCode)306) || Input.GetKey((KeyCode)305))
			{
				rackBay.Data.rotY = Mathf.Round(rackBay.Data.rotY / 90f) * 90f;
			}
			else if (Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303))
			{
				rackBay.Data.rotY = (float)Math.Round(rackBay.Data.rotY - 15f, 1);
			}
			else
			{
				rackBay.Data.rotY = (float)Math.Round(rackBay.Data.rotY + 15f, 1);
			}
			ApplyBayTransform(rackBay.Go.transform, rackBay.Data);
			SyncBayItems(rackBay);
			SaveLayout();
			MenuManager instance = MenuManager.instance;
			if (instance != null)
			{
				Sound soundTick = instance.soundTick;
				if (soundTick != null)
				{
					soundTick.Play(rackBay.Go.transform.position, 1f, 1f, 1f, 1f);
				}
			}
			Plugin.Log.LogInfo((object)$"[F9 ROTATE] rotY={rackBay.Data.rotY}");
		}

		private void SpawnTestArsenal()
		{
			//IL_0136: 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_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: 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)
			if ((Object)(object)_anchorTransform == (Object)null || !SemiFunc.IsMasterClientOrSingleplayer())
			{
				return;
			}
			_devSpawnedItems.RemoveAll((GameObject g) => (Object)(object)g == (Object)null);
			if (_devSpawnedItems.Count > 0)
			{
				foreach (GameObject devSpawnedItem in _devSpawnedItems)
				{
					Object.Destroy((Object)(object)devSpawnedItem);
				}
				_devSpawnedItems.Clear();
				Plugin.Log.LogInfo((object)"[DEV F11] Cleared all test arsenal items.");
			}
			else
			{
				if (StatsManager.instance?.itemDictionary == null)
				{
					return;
				}
				int num = 0;
				foreach (Item value in StatsManager.instance.itemDictionary.Values)
				{
					if ((Object)(object)value == (Object)null || value.prefab == null)
					{
						continue;
					}
					RackCategory rackCategory = ClassifyItemDef(value);
					if (rackCategory == RackCategory.None)
					{
						continue;
					}
					string key = ((!string.IsNullOrEmpty(value.itemName)) ? value.itemName : ((Object)value).name);
					RackSlot rackSlot = FindSlotForItem(rackCategory, key);
					if (rackSlot == null)
					{
						continue;
					}
					Vector3 slotWorldPos = rackSlot.GetSlotWorldPos(rackSlot.Stack.Count);
					Quaternion slotWorldRot = rackSlot.GetSlotWorldRot();
					GameObject val = Resources.Load<GameObject>("Items/" + ((Object)value).name);
					if (!((Object)(object)val == (Object)null))
					{
						GameObject val2 = Object.Instantiate<GameObject>(val, slotWorldPos, slotWorldRot);
						_devSpawnedItems.Add(val2);
						PhysGrabObject component = val2.GetComponent<PhysGrabObject>();
						if ((Object)(object)component != (Object)null)
						{
							RackItemIntoSlot(component, key, rackSlot, playSound: false);
							num++;
						}
					}
				}
				Plugin.Log.LogInfo((object)$"[DEV F11] Spawned {num} small/medium test arsenal items onto the racks!");
			}
		}

		private void RemoveNearestRack(Camera mainCam)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			RackBay rackBay = FindNearestBay(((Component)mainCam).transform.position);
			if (rackBay == null)
			{
				return;
			}
			if (SemiFunc.IsMasterClientOrSingleplayer())
			{
				foreach (RackSlot slot in rackBay.Slots)
				{
					foreach (PhysGrabObject item in slot.Stack)
					{
						if ((Object)(object)item != (Object)null)
						{
							item.OverrideKinematic(0f);
							SetBatteryVisualVisible(item, visible: true);
						}
					}
				}
			}
			Vector3 position = rackBay.Go.transform.position;
			Object.Destroy((Object)(object)rackBay.Go);
			_bays.Remove(rackBay);
			SaveLayout();
			MenuManager instance = MenuManager.instance;
			if (instance != null)
			{
				Sound soundDeny = instance.soundDeny;
				if (soundDeny != null)
				{
					soundDeny.Play(position, 1f, 1f, 1f, 1f);
				}
			}
			Plugin.Log.LogInfo((object)$"[F10 REMOVE] Removed rack (remaining: {_bays.Count}).");
		}
	}
}