Decompiled source of QuickDeploy v1.0.0

QuickDeploy.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
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 UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Pinkpz")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Pinkpz")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("QuickDeploy")]
[assembly: AssemblyTitle("QuickDeploy")]
[assembly: AssemblyVersion("1.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 QuickDeploy
{
	internal struct DeployResult
	{
		public bool NoPlanet;

		public int ItemsMoved;

		public int ContainersUsed;

		public int ContainersInRange;
	}
	internal static class DeployLogic
	{
		public static DeployResult Run()
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: 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_00ef: Unknown result type (might be due to invalid IL or missing references)
			DeployResult result = default(DeployResult);
			Player mainPlayer = GameMain.mainPlayer;
			PlanetData localPlanet = GameMain.localPlanet;
			if (mainPlayer == null || localPlanet == null || localPlanet.factory == null || mainPlayer.package == null)
			{
				result.NoPlanet = true;
				return result;
			}
			PlanetFactory factory = localPlanet.factory;
			StorageComponent package = mainPlayer.package;
			List<StorageComponent> list = CollectTargets(factory, mainPlayer);
			result.ContainersInRange = list.Count;
			if (list.Count == 0)
			{
				return result;
			}
			HashSet<string> excludedTypes = QuickDeployPlugin.ParseNames(QuickDeployPlugin.ExcludedItemTypes.Value);
			HashSet<int> excludedItems = QuickDeployPlugin.ParseIds(QuickDeployPlugin.ExcludedItemIds.Value);
			HashSet<int> hashSet = new HashSet<int>();
			int num5 = default(int);
			for (int i = 0; i < package.size; i++)
			{
				GRID val = package.grids[i];
				if (val.itemId <= 0 || val.count <= 0 || val.filter != 0 || IsExcluded(val.itemId, excludedTypes, excludedItems))
				{
					continue;
				}
				int itemId = val.itemId;
				int num = val.count;
				int inc = val.inc;
				int num2 = 0;
				foreach (StorageComponent item in list)
				{
					if (num <= 0)
					{
						break;
					}
					if (TryDeposit(item, itemId, num, inc, out var added, out var remainInc) && added > 0)
					{
						num2 += added;
						num -= added;
						inc = remainInc;
						hashSet.Add(item.id);
					}
				}
				if (num2 > 0)
				{
					int num3 = itemId;
					int num4 = num2;
					package.TakeItemFromGrid(i, ref num3, ref num4, ref num5);
					result.ItemsMoved += num2;
				}
			}
			result.ContainersUsed = hashSet.Count;
			return result;
		}

		private static bool IsExcluded(int itemId, HashSet<string> excludedTypes, HashSet<int> excludedItems)
		{
			if (excludedItems.Contains(itemId))
			{
				return true;
			}
			ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(itemId);
			if (val == null)
			{
				return true;
			}
			if (val.CanBuild || val.IsEntity)
			{
				return true;
			}
			if (excludedTypes.Contains(((object)Unsafe.As<EItemType, EItemType>(ref val.Type)/*cast due to .constrained prefix*/).ToString()))
			{
				return true;
			}
			return false;
		}

		private static List<StorageComponent> CollectTargets(PlanetFactory factory, Player player)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: 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_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			List<StorageComponent> list = new List<StorageComponent>();
			Dictionary<int, float> distances = new Dictionary<int, float>();
			FactoryStorage factoryStorage = factory.factoryStorage;
			if (factoryStorage == null || factoryStorage.storagePool == null)
			{
				return list;
			}
			float num = QuickDeployPlugin.Range.Value;
			if (num <= 0f && player.mecha != null)
			{
				num = player.mecha.buildArea;
			}
			float num2 = num * num;
			HashSet<int> hashSet = QuickDeployPlugin.ParseIds(QuickDeployPlugin.ExcludedBuildingIds.Value);
			Vector3 position = player.position;
			for (int i = 1; i < factoryStorage.storageCursor; i++)
			{
				StorageComponent val = factoryStorage.storagePool[i];
				if (val == null || val.id != i || val.entityId <= 0 || val.entityId >= factory.entityPool.Length)
				{
					continue;
				}
				EntityData val2 = factory.entityPool[val.entityId];
				if (val2.id == val.entityId && !hashSet.Contains(val2.protoId))
				{
					Vector3 val3 = val2.pos - position;
					float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
					if (!(sqrMagnitude > num2))
					{
						list.Add(val);
						distances[val.id] = sqrMagnitude;
					}
				}
			}
			list.Sort((StorageComponent a, StorageComponent b) => distances[a.id].CompareTo(distances[b.id]));
			return list;
		}

		private static bool TryDeposit(StorageComponent storage, int itemId, int count, int inc, out int added, out int remainInc)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: 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_0055: 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)
			added = 0;
			remainInc = inc;
			int num = storage.size - storage.bans;
			if (num > storage.grids.Length)
			{
				num = storage.grids.Length;
			}
			if (num <= 0)
			{
				return false;
			}
			bool flag = false;
			for (int i = 0; i < num; i++)
			{
				GRID val = storage.grids[i];
				if ((val.itemId == itemId && val.count > 0) || val.filter == itemId)
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				return false;
			}
			try
			{
				added = storage.AddItem(itemId, count, 0, num, inc, ref remainInc);
				return true;
			}
			catch (Exception ex)
			{
				QuickDeployPlugin.Log.LogWarning((object)("Deposit failed for storage " + storage.id + ": " + ex.Message));
				added = 0;
				remainInc = inc;
				return false;
			}
		}
	}
	[BepInPlugin("pinkpz.dsp.quickdeploy", "QuickDeploy", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class QuickDeployPlugin : BaseUnityPlugin
	{
		public const string GUID = "pinkpz.dsp.quickdeploy";

		public const string NAME = "QuickDeploy";

		public const string VERSION = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<float> Range;

		internal static ConfigEntry<string> ExcludedItemTypes;

		internal static ConfigEntry<string> ExcludedItemIds;

		internal static ConfigEntry<string> ExcludedBuildingIds;

		internal static ConfigEntry<float> ButtonOffsetX;

		internal static ConfigEntry<float> ButtonOffsetY;

		internal static ConfigEntry<float> ButtonWidth;

		internal static ConfigEntry<float> ButtonHeight;

		private void Awake()
		{
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Range = ((BaseUnityPlugin)this).Config.Bind<float>("Deploy", "Range", 30f, "Max distance (meters) from the mecha to a container for it to be used. 0 = use the mecha build area.");
			ExcludedItemTypes = ((BaseUnityPlugin)this).Config.Bind<string>("Deploy", "ExcludedItemTypes", "Production,Logistics,Decoration,Turret,Defense", "Item types that are never deployed (buildings, turrets, ammo/weapons...). Comma separated EItemType names.");
			ExcludedItemIds = ((BaseUnityPlugin)this).Config.Bind<string>("Deploy", "ExcludedItemIds", "", "Extra item ids that are never deployed. Comma separated, e.g. 1801,1802");
			ExcludedBuildingIds = ((BaseUnityPlugin)this).Config.Bind<string>("Deploy", "ExcludedContainerBuildingIds", "11999", "Container building (item) ids that are never used as a target. 11999 = Trash Can from ProjectGenesis_kfix, it destroys items.");
			ButtonOffsetX = ((BaseUnityPlugin)this).Config.Bind<float>("Button", "OffsetX", 150f, "Button X offset from the Logistics checkbox (pixels).");
			ButtonOffsetY = ((BaseUnityPlugin)this).Config.Bind<float>("Button", "OffsetY", 0f, "Button Y offset from the Logistics checkbox (pixels).");
			ButtonWidth = ((BaseUnityPlugin)this).Config.Bind<float>("Button", "Width", 100f, "Button width (pixels).");
			ButtonHeight = ((BaseUnityPlugin)this).Config.Bind<float>("Button", "Height", 22f, "Button height (pixels).");
			new Harmony("pinkpz.dsp.quickdeploy").PatchAll(typeof(QuickDeployPlugin).Assembly);
			Log.LogInfo((object)"QuickDeploy 1.0.0 loaded");
		}

		internal static HashSet<int> ParseIds(string text)
		{
			HashSet<int> hashSet = new HashSet<int>();
			if (string.IsNullOrEmpty(text))
			{
				return hashSet;
			}
			string[] array = text.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				if (int.TryParse(array[i].Trim(), out var result))
				{
					hashSet.Add(result);
				}
			}
			return hashSet;
		}

		internal static HashSet<string> ParseNames(string text)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			if (string.IsNullOrEmpty(text))
			{
				return hashSet;
			}
			string[] array = text.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length > 0)
				{
					hashSet.Add(text2);
				}
			}
			return hashSet;
		}
	}
	[HarmonyPatch(typeof(UIInventoryWindow))]
	internal static class UIInventoryWindowPatch
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static UnityAction <0>__OnClick;
		}

		private const string ButtonName = "quick-deploy-button";

		[HarmonyPostfix]
		[HarmonyPatch("_OnOpen")]
		public static void OnOpen_Postfix(UIInventoryWindow __instance)
		{
			try
			{
				EnsureButton(__instance);
			}
			catch (Exception ex)
			{
				QuickDeployPlugin.Log.LogWarning((object)("Could not create the Quick Deploy button: " + ex));
			}
		}

		private static void EnsureButton(UIInventoryWindow window)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: 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_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Expected O, but got Unknown
			UIToggle val = (((Object)(object)window.deliveryPanel != (Object)null) ? window.deliveryPanel.deliveryToggle : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			RectTransform rectTransform = val.rectTransform;
			Transform parent = ((Transform)rectTransform).parent;
			RectTransform val2 = (RectTransform)(object)((parent is RectTransform) ? parent : null);
			if (!((Object)(object)val2 == (Object)null) && !((Object)(object)((Transform)val2).Find("quick-deploy-button") != (Object)null))
			{
				GameObject val3 = new GameObject("quick-deploy-button", new Type[3]
				{
					typeof(RectTransform),
					typeof(Image),
					typeof(Button)
				});
				RectTransform component = val3.GetComponent<RectTransform>();
				((Transform)component).SetParent((Transform)(object)val2, false);
				component.anchorMin = rectTransform.anchorMin;
				component.anchorMax = rectTransform.anchorMax;
				component.pivot = rectTransform.pivot;
				component.sizeDelta = new Vector2(QuickDeployPlugin.ButtonWidth.Value, QuickDeployPlugin.ButtonHeight.Value);
				component.anchoredPosition = rectTransform.anchoredPosition + new Vector2(QuickDeployPlugin.ButtonOffsetX.Value, QuickDeployPlugin.ButtonOffsetY.Value);
				Image component2 = val3.GetComponent<Image>();
				((Graphic)component2).color = new Color(0.16f, 0.32f, 0.45f, 0.75f);
				Button component3 = val3.GetComponent<Button>();
				((Selectable)component3).targetGraphic = (Graphic)(object)component2;
				ColorBlock colors = ((Selectable)component3).colors;
				((ColorBlock)(ref colors)).highlightedColor = new Color(1.25f, 1.25f, 1.25f, 1f);
				((ColorBlock)(ref colors)).pressedColor = new Color(0.8f, 0.8f, 0.8f, 1f);
				((Selectable)component3).colors = colors;
				ButtonClickedEvent onClick = component3.onClick;
				object obj = <>O.<0>__OnClick;
				if (obj == null)
				{
					UnityAction val4 = OnClick;
					<>O.<0>__OnClick = val4;
					obj = (object)val4;
				}
				((UnityEvent)onClick).AddListener((UnityAction)obj);
				GameObject val5 = new GameObject("Text", new Type[2]
				{
					typeof(RectTransform),
					typeof(Text)
				});
				RectTransform component4 = val5.GetComponent<RectTransform>();
				((Transform)component4).SetParent((Transform)(object)component, false);
				component4.anchorMin = Vector2.zero;
				component4.anchorMax = Vector2.one;
				component4.offsetMin = Vector2.zero;
				component4.offsetMax = Vector2.zero;
				Text component5 = val5.GetComponent<Text>();
				component5.text = "Quick Deploy";
				component5.alignment = (TextAnchor)4;
				((Graphic)component5).color = Color.white;
				component5.fontSize = 14;
				((Graphic)component5).raycastTarget = false;
				if ((Object)(object)window.titleText != (Object)null)
				{
					component5.font = window.titleText.font;
				}
			}
		}

		private static void OnClick()
		{
			try
			{
				DeployResult deployResult = DeployLogic.Run();
				string text = (deployResult.NoPlanet ? "Quick Deploy: stand on a planet first" : ((deployResult.ContainersInRange == 0) ? "Quick Deploy: no container in range" : ((deployResult.ItemsMoved != 0) ? ("Quick Deploy: moved " + deployResult.ItemsMoved + " items into " + deployResult.ContainersUsed + " containers") : "Quick Deploy: nothing to deploy")));
				UIRealtimeTip.Popup(text, false, 0);
			}
			catch (Exception ex)
			{
				QuickDeployPlugin.Log.LogError((object)ex);
				UIRealtimeTip.Popup("Quick Deploy failed, see the BepInEx log", false, 0);
			}
		}
	}
}