Decompiled source of Tool Rack v1.0.0

BepInEx/plugins/CrackToolRack/CrackToolRack.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mirror;
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: AssemblyVersion("0.0.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 CrackToolRack
{
	[BepInPlugin("Grokent.CrackToolRack", "Tool Rack", "1.0.0")]
	public sealed class ToolRackPlugin : BaseUnityPlugin
	{
		public const string Guid = "Grokent.CrackToolRack";

		public const string Version = "1.0.0";

		public static readonly PieceType RackType = (PieceType)11;

		internal static ToolRackPlugin Instance;

		internal static ManualLogSource Log;

		private static readonly Dictionary<int, NetworkIdentity> Racks = new Dictionary<int, NetworkIdentity>();

		private static readonly List<CartCargoBed> RackBeds = new List<CartCargoBed>();

		private static ScaffoldPieceDefinition _definition;

		private static GameObject _visualTemplate;

		private static ScaffoldManager _templateOwner;

		private static Sprite _icon;

		private static ConfigEntry<float> _heightOffset;

		private static ConfigEntry<float> _yawOffset;

		private static ConfigEntry<float> _forwardOffset;

		private static ConfigEntry<float> _slotSpacingScale;

		private static ConfigEntry<bool> _verbose;

		private static uint? _rackAssetId;

		private const string RackNameKey = "ScaffoldingPiece_ToolRack";

		private const string RackPrefabPath = "Incremental/PF_ToolRack";

		private const string BeamPieceName = "CrossBeamH";

		private void Awake()
		{
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			_heightOffset = ((BaseUnityPlugin)this).Config.Bind<float>("Rack", "HeightOffset", 0.02f, "Height of the clamp row above the crossbeam centre. 0.020 puts the clamp row at the beam mid-line.");
			_yawOffset = ((BaseUnityPlugin)this).Config.Bind<float>("Rack", "YawOffset", 90f, "Rotation of the rack around the beam. 90 lays the four clamps along the beam.");
			_forwardOffset = ((BaseUnityPlugin)this).Config.Bind<float>("Rack", "ForwardOffset", 0.13f, "How far the clamp row sits in front of the beam centre line. 0.130 leaves the clamp backs inside the beam and the fronts protruding.");
			_slotSpacingScale = ((BaseUnityPlugin)this).Config.Bind<float>("Rack", "SlotSpacingScale", 0.7f, "Scales the four holder positions toward the centre. 1.0 is the cart spacing.");
			_verbose = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLogging", false, "Log every rack spawn/remove.");
			new Harmony("Grokent.CrackToolRack").PatchAll();
			SaveManager.GroundItemsRestored += OnGroundItemsRestored;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Tool Rack loaded.");
		}

		private void OnDestroy()
		{
			SaveManager.GroundItemsRestored -= OnGroundItemsRestored;
		}

		private static void Verbose(string message)
		{
			if (_verbose != null && _verbose.Value)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogInfo((object)message);
				}
			}
		}

		internal static void OnCartCargoBedAwake(CartCargoBed bed)
		{
			//IL_0084: 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)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			if (!GameMode.IsStory || (Object)(object)bed == (Object)null || !_rackAssetId.HasValue)
			{
				return;
			}
			NetworkIdentity component = ((Component)bed).GetComponent<NetworkIdentity>();
			if ((Object)(object)component == (Object)null || component.assetId != _rackAssetId.Value)
			{
				return;
			}
			Transform[] array = AccessTools.FieldRefAccess<CartCargoBed, Transform[]>("slots").Invoke(bed);
			if (array == null)
			{
				return;
			}
			float num = ((_slotSpacingScale != null) ? _slotSpacingScale.Value : 0.7f);
			foreach (Transform val in array)
			{
				if (!((Object)(object)val == (Object)null))
				{
					Vector3 localPosition = val.localPosition;
					localPosition.x *= num;
					val.localPosition = localPosition;
				}
			}
			Verbose("[ToolRack] compressed holder spacing by " + num);
		}

		internal static void OnScaffoldManagerAwake(ScaffoldManager manager)
		{
			if (GameMode.IsStory)
			{
				EnsureRackPrefabRegistered();
				BuildDefinition(manager);
			}
		}

		private static NetworkIdentity LoadRackPrefab()
		{
			NetworkIdentity obj = Resources.Load<NetworkIdentity>("Incremental/PF_ToolRack");
			if ((Object)(object)obj == (Object)null)
			{
				ManualLogSource log = Log;
				if (log == null)
				{
					return obj;
				}
				log.LogError((object)"[ToolRack] no prefab at Resources/Incremental/PF_ToolRack");
			}
			return obj;
		}

		private static void EnsureRackPrefabRegistered()
		{
			NetworkIdentity val = LoadRackPrefab();
			if (!((Object)(object)val == (Object)null))
			{
				_rackAssetId = val.assetId;
				if (!NetworkClient.prefabs.ContainsKey(val.assetId))
				{
					NetworkClient.RegisterPrefab(((Component)val).gameObject);
					Verbose("[ToolRack] registered Incremental/PF_ToolRack");
				}
			}
		}

		private static void BuildDefinition(ScaffoldManager manager)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<PieceType, ScaffoldPieceDefinition> dictionary = AccessTools.FieldRefAccess<ScaffoldManager, Dictionary<PieceType, ScaffoldPieceDefinition>>("_defLookup").Invoke(manager);
			if (dictionary == null)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogError((object)"[ToolRack] ScaffoldManager has no definition lookup");
				}
			}
			else
			{
				if (dictionary.ContainsKey(RackType))
				{
					return;
				}
				if (!dictionary.TryGetValue((PieceType)3, out var value) || (Object)(object)value == (Object)null || (Object)(object)value.visualPrefab == (Object)null)
				{
					ManualLogSource log2 = Log;
					if (log2 != null)
					{
						log2.LogError((object)"[ToolRack] could not find the CrossBeamH definition");
					}
					return;
				}
				if ((Object)(object)_visualTemplate != (Object)null)
				{
					Object.Destroy((Object)(object)_visualTemplate);
					_visualTemplate = null;
				}
				_visualTemplate = Object.Instantiate<GameObject>(value.visualPrefab);
				((Object)_visualTemplate).name = "PF_Scaffolding_ToolRack";
				_visualTemplate.transform.position = new Vector3(0f, -5000f, 0f);
				_visualTemplate.transform.rotation = Quaternion.identity;
				Object.DontDestroyOnLoad((Object)(object)_visualTemplate);
				_templateOwner = manager;
				ScaffoldPieceDefinition val = ScriptableObject.CreateInstance<ScaffoldPieceDefinition>();
				val.type = RackType;
				val.nameId = "ScaffoldingPiece_ToolRack";
				val.minBoltsToPlace = value.minBoltsToPlace;
				val.minBoltsToFail = value.minBoltsToFail;
				val.stabilityProduction = value.stabilityProduction;
				val.groundProductionBoost = value.groundProductionBoost;
				val.stabilityCost = value.stabilityCost;
				val.halfCellXZ = value.halfCellXZ;
				val.visualPrefab = _visualTemplate;
				val.icon = EnsureIcon();
				AccessTools.FieldRefAccess<ScaffoldPieceDefinition, ConnectionSlotDef[]>("_cachedSlots").Invoke(val) = null;
				AccessTools.FieldRefAccess<ScaffoldPieceDefinition, Vector3[]>("_cachedPlacementRefs").Invoke(val) = null;
				AccessTools.Method(typeof(ScaffoldPieceDefinition), "BuildSlots", (Type[])null, (Type[])null).Invoke(val, null);
				dictionary[RackType] = val;
				_definition = val;
				FieldRef<ScaffoldManager, ScaffoldPieceDefinition[]> obj = AccessTools.FieldRefAccess<ScaffoldManager, ScaffoldPieceDefinition[]>("pieceDefinitions");
				ScaffoldPieceDefinition[] array = obj.Invoke(manager);
				List<ScaffoldPieceDefinition> list = ((array == null) ? new List<ScaffoldPieceDefinition>() : new List<ScaffoldPieceDefinition>(array));
				if (!list.Contains(val))
				{
					list.Add(val);
				}
				obj.Invoke(manager) = list.ToArray();
				ManualLogSource log3 = Log;
				if (log3 != null)
				{
					log3.LogInfo((object)("[ToolRack] registered piece type 11 (Tool Rack), slots=" + val.connectionSlots.Length + " bolts=" + val.BoltedSlotCount));
				}
			}
		}

		private static Sprite EnsureIcon()
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_009e: 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)
			if ((Object)(object)_icon != (Object)null)
			{
				return _icon;
			}
			try
			{
				using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("CrackToolRack.icon.png");
				if (stream == null)
				{
					ManualLogSource log = Log;
					if (log != null)
					{
						log.LogWarning((object)"[ToolRack] embedded icon missing");
					}
					return null;
				}
				byte[] array;
				using (MemoryStream memoryStream = new MemoryStream())
				{
					stream.CopyTo(memoryStream);
					array = memoryStream.ToArray();
				}
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				ImageConversion.LoadImage(val, array);
				((Object)val).name = "TEX_ToolRack_Icon";
				_icon = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
				((Object)_icon).name = "ToolRackIcon";
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = Log;
				if (log2 != null)
				{
					log2.LogError((object)("[ToolRack] icon load failed: " + ex));
				}
			}
			return _icon;
		}

		internal static void AddPieceToToolbox(Toolbox toolbox)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Invalid comparison between I4 and Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected I4, but got Unknown
			if (!GameMode.IsStory)
			{
				return;
			}
			FieldRef<Toolbox, PieceType[]> val = AccessTools.FieldRefAccess<Toolbox, PieceType[]>("availablePieces");
			PieceType[] array = val.Invoke(toolbox) ?? Array.Empty<PieceType>();
			for (int i = 0; i < array.Length; i++)
			{
				if ((int)array[i] == (int)RackType)
				{
					return;
				}
			}
			PieceType[] array2 = (PieceType[])(object)new PieceType[array.Length + 1];
			Array.Copy(array, array2, array.Length);
			array2[array.Length] = (PieceType)(int)RackType;
			val.Invoke(toolbox) = array2;
			Verbose("[ToolRack] added piece to toolbox " + ((Object)toolbox).name);
		}

		internal static void OnSpawnVisual(ScaffoldManager manager, int pieceId)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkServer.active)
			{
				return;
			}
			ScaffoldGrid grid = manager.Grid;
			if (grid != null)
			{
				ScaffoldPieceData? piece = grid.GetPiece(pieceId);
				if (piece.HasValue && piece.Value.type == RackType)
				{
					SpawnRack(grid, pieceId, piece.Value);
				}
			}
		}

		private unsafe static void SpawnRack(ScaffoldGrid grid, int pieceId, ScaffoldPieceData piece)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: 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_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: 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)
			if (Racks.ContainsKey(pieceId))
			{
				return;
			}
			NetworkIdentity val = LoadRackPrefab();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			ScaffoldPieceDefinition definition = grid.GetDefinition(RackType);
			Vector3 val2 = grid.CellToWorld(piece.gridCell, definition.halfCellXZ);
			Quaternion rotationQuaternion = ((ScaffoldPieceData)(ref piece)).RotationQuaternion;
			Quaternion val3 = rotationQuaternion * Quaternion.Euler(0f, _yawOffset.Value, 0f);
			Vector3 val4 = val2 + rotationQuaternion * new Vector3(-1.5f, 0f, 0f);
			Vector3 val5 = val3 * new Vector3(0f, 0f, 0.1f);
			Vector3 val6 = val4 + Vector3.up * _heightOffset.Value - val5 + rotationQuaternion * new Vector3(_forwardOffset.Value, 0f, 0f);
			NetworkIdentity val7 = Object.Instantiate<NetworkIdentity>(val, val6, val3);
			((Object)val7).name = "ToolRack_" + pieceId;
			NetworkServer.Spawn(((Component)val7).gameObject, (NetworkConnectionToClient)null);
			Racks[pieceId] = val7;
			CartCargoBed component = ((Component)val7).GetComponent<CartCargoBed>();
			if ((Object)(object)component != (Object)null)
			{
				RackBeds.Add(component);
				TuneBedTrigger(val7);
			}
			else
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogError((object)"[ToolRack] spawned rack has no CartCargoBed");
				}
			}
			Verbose("[ToolRack] spawned rack for piece " + pieceId + " at " + ((object)(*(Vector3*)(&val6))/*cast due to .constrained prefix*/).ToString());
		}

		private static void TuneBedTrigger(NetworkIdentity rack)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			Transform[] componentsInChildren = ((Component)rack).GetComponentsInChildren<Transform>(true);
			foreach (Transform val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null) && !(((Object)val).name != "Bed"))
				{
					BoxCollider component = ((Component)val).GetComponent<BoxCollider>();
					if (!((Object)(object)component == (Object)null))
					{
						component.center = new Vector3(0f, 0.3f, 0f);
						component.size = new Vector3(2.9f, 1.2f, 1.2f);
						Verbose("[ToolRack] centred bed trigger");
						break;
					}
				}
			}
		}

		internal static void OnApplyRemove(int pieceId)
		{
			if (Racks.TryGetValue(pieceId, out var value))
			{
				Racks.Remove(pieceId);
				DestroyRack(value);
				Verbose("[ToolRack] removed rack for piece " + pieceId);
			}
		}

		private static void DestroyRack(NetworkIdentity rack)
		{
			if (!((Object)(object)rack == (Object)null))
			{
				CartCargoBed component = ((Component)rack).GetComponent<CartCargoBed>();
				if ((Object)(object)component != (Object)null)
				{
					RackBeds.Remove(component);
				}
				if (NetworkServer.active)
				{
					NetworkServer.Destroy(((Component)rack).gameObject);
				}
				else
				{
					Object.Destroy((Object)(object)((Component)rack).gameObject);
				}
			}
		}

		internal static void DestroyAllRacks()
		{
			if (Racks.Count == 0)
			{
				RackBeds.Clear();
				return;
			}
			List<NetworkIdentity> list = new List<NetworkIdentity>(Racks.Values);
			Racks.Clear();
			RackBeds.Clear();
			for (int i = 0; i < list.Count; i++)
			{
				DestroyRack(list[i]);
			}
		}

		internal static void OnScaffoldManagerDestroyed(ScaffoldManager manager)
		{
			DestroyAllRacks();
			if ((Object)(object)_templateOwner == (Object)(object)manager && (Object)(object)_visualTemplate != (Object)null)
			{
				Object.Destroy((Object)(object)_visualTemplate);
				_visualTemplate = null;
				_templateOwner = null;
			}
		}

		internal static void OnSnapshotPrefix()
		{
			DestroyAllRacks();
		}

		internal static void OnSnapshotPostfix()
		{
			RestowAllBeds(5f);
		}

		private static void OnGroundItemsRestored()
		{
			RestowAllBeds(3f);
		}

		private static void RestowAllBeds(float seconds)
		{
			if (!NetworkServer.active)
			{
				return;
			}
			for (int num = RackBeds.Count - 1; num >= 0; num--)
			{
				CartCargoBed val = RackBeds[num];
				if ((Object)(object)val == (Object)null)
				{
					RackBeds.RemoveAt(num);
				}
				else
				{
					val.ServerTakeAnythingFor(seconds);
				}
			}
		}
	}
	[HarmonyPatch(typeof(ScaffoldManager), "Awake")]
	internal static class ScaffoldManagerAwakePatch
	{
		[HarmonyPostfix]
		private static void Postfix(ScaffoldManager __instance)
		{
			ToolRackPlugin.OnScaffoldManagerAwake(__instance);
		}
	}
	[HarmonyPatch(typeof(CartCargoBed), "Awake")]
	internal static class CartCargoBedAwakePatch
	{
		[HarmonyPostfix]
		private static void Postfix(CartCargoBed __instance)
		{
			ToolRackPlugin.OnCartCargoBedAwake(__instance);
		}
	}
	[HarmonyPatch(typeof(Toolbox), "Awake")]
	internal static class ToolboxAwakePatch
	{
		[HarmonyPostfix]
		private static void Postfix(Toolbox __instance)
		{
			ToolRackPlugin.AddPieceToToolbox(__instance);
		}
	}
	[HarmonyPatch(typeof(ScaffoldManager), "SpawnVisual")]
	internal static class ScaffoldManagerSpawnVisualPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ScaffoldManager __instance, int pieceId)
		{
			ToolRackPlugin.OnSpawnVisual(__instance, pieceId);
		}
	}
	[HarmonyPatch(typeof(ScaffoldManager), "ApplyRemove")]
	internal static class ScaffoldManagerApplyRemovePatch
	{
		[HarmonyPostfix]
		private static void Postfix(int pieceId)
		{
			ToolRackPlugin.OnApplyRemove(pieceId);
		}
	}
	[HarmonyPatch(typeof(ScaffoldManager), "LoadFromSnapshot")]
	internal static class ScaffoldManagerLoadSnapshotPatch
	{
		[HarmonyPrefix]
		private static void Prefix()
		{
			ToolRackPlugin.OnSnapshotPrefix();
		}

		[HarmonyPostfix]
		private static void Postfix()
		{
			ToolRackPlugin.OnSnapshotPostfix();
		}
	}
	[HarmonyPatch(typeof(ScaffoldManager), "OnDestroy")]
	internal static class ScaffoldManagerDestroyPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ScaffoldManager __instance)
		{
			ToolRackPlugin.OnScaffoldManagerDestroyed(__instance);
		}
	}
	[HarmonyPatch(typeof(LocalizationManager), "GetText", new Type[]
	{
		typeof(string),
		typeof(Random),
		typeof(string)
	})]
	internal static class LocalizationToolRackPatch
	{
		[HarmonyPrefix]
		private static bool Prefix(string key, ref string __result)
		{
			if (key == "ScaffoldingPiece_ToolRack")
			{
				__result = "Tool Rack";
				return false;
			}
			return true;
		}
	}
}