Decompiled source of ClearInventory v1.0.0

plugins/ClearInventory.dll

Decompiled 12 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
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.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("ClearInventory")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ClearInventory")]
[assembly: AssemblyTitle("ClearInventory")]
[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 ClearInventory
{
	[BepInPlugin("com.github.jiesiluo.clearinventory", "Clear Inventory", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public class Result
		{
			public int Items;

			public int Kinds;

			public int OverMax;

			public int Stations;

			public int Left;

			public string Error;
		}

		private struct Slot
		{
			public StationComponent Station;

			public int Index;
		}

		public const string Guid = "com.github.jiesiluo.clearinventory";

		public const string Version = "1.0.0";

		internal static ConfigEntry<float> Range;

		internal static ConfigEntry<bool> Overflow;

		internal static ConfigEntry<bool> SkipFilteredSlots;

		internal static ConfigEntry<float> ButtonOffsetX;

		internal static ConfigEntry<float> ButtonOffsetY;

		internal static ManualLogSource Log;

		private void Awake()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Range = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Range", 0f, "How far from the mecha a station may be, in metres. 0 = every station on the planet.");
			Overflow = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Overflow", true, "When every station with a slot for an item is at its max, put the rest into the nearest of them anyway (over its max).");
			SkipFilteredSlots = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SkipFilteredSlots", false, "Leave inventory slots that have a filter set.");
			ButtonOffsetX = ((BaseUnityPlugin)this).Config.Bind<float>("Button", "OffsetX", 0f, "Moves the button right (pixels) from where the mod puts it.");
			ButtonOffsetY = ((BaseUnityPlugin)this).Config.Bind<float>("Button", "OffsetY", 0f, "Moves the button up (pixels) from where the mod puts it.");
			new Harmony("com.github.jiesiluo.clearinventory").PatchAll(typeof(InventoryButton));
		}

		public static List<StationComponent> StationsInRange(PlanetFactory factory, Vector3 from, float range)
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			List<KeyValuePair<float, StationComponent>> list = new List<KeyValuePair<float, StationComponent>>();
			StationComponent[] stationPool = factory.transport.stationPool;
			int stationCursor = factory.transport.stationCursor;
			for (int i = 1; i < stationCursor && i < stationPool.Length; i++)
			{
				StationComponent val = stationPool[i];
				if (val != null && val.id == i && !val.isCollector && !val.isVeinCollector && val.storage != null && val.entityId > 0 && val.entityId < factory.entityPool.Length)
				{
					Vector3 val2 = factory.entityPool[val.entityId].pos - from;
					float magnitude = ((Vector3)(ref val2)).magnitude;
					if (!(range > 0f) || !(magnitude > range))
					{
						list.Add(new KeyValuePair<float, StationComponent>(magnitude, val));
					}
				}
			}
			list.Sort((KeyValuePair<float, StationComponent> a, KeyValuePair<float, StationComponent> b) => a.Key.CompareTo(b.Key));
			List<StationComponent> list2 = new List<StationComponent>(list.Count);
			foreach (KeyValuePair<float, StationComponent> item in list)
			{
				list2.Add(item.Value);
			}
			return list2;
		}

		public static Result Deposit(Player player, float range, bool overflow, bool skipFiltered)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			Result result = new Result();
			PlanetData localPlanet = GameMain.localPlanet;
			PlanetFactory val = localPlanet?.factory;
			if (player == null || val == null || !localPlanet.factoryLoaded || player.sailing)
			{
				result.Error = Tr("不在星球上", "Not on a planet");
				return result;
			}
			List<StationComponent> list = StationsInRange(val, player.position, range);
			if (list.Count == 0)
			{
				result.Error = Tr("这颗星球上没有物流塔", "No logistics station on this planet") + ((range > 0f) ? Tr($"({range:0} 米内)", $" (within {range:0} m)") : "");
				return result;
			}
			Dictionary<int, List<Slot>> dictionary = new Dictionary<int, List<Slot>>();
			foreach (StationComponent item in list)
			{
				for (int i = 0; i < item.storage.Length; i++)
				{
					int itemId = item.storage[i].itemId;
					if (itemId > 0)
					{
						if (!dictionary.TryGetValue(itemId, out var value))
						{
							value = (dictionary[itemId] = new List<Slot>());
						}
						value.Add(new Slot
						{
							Station = item,
							Index = i
						});
					}
				}
			}
			StorageComponent package = player.package;
			HashSet<int> hashSet = new HashSet<int>();
			HashSet<int> hashSet2 = new HashSet<int>();
			for (int j = 0; j < package.size; j++)
			{
				int itemId2 = package.grids[j].itemId;
				int num = package.grids[j].count;
				if (itemId2 <= 0 || num <= 0 || (skipFiltered && package.grids[j].filter != 0) || !dictionary.TryGetValue(itemId2, out var value2))
				{
					continue;
				}
				foreach (Slot item2 in value2)
				{
					if (num <= 0)
					{
						break;
					}
					int num2;
					lock (item2.Station.storage)
					{
						num2 = item2.Station.storage[item2.Index].max - item2.Station.storage[item2.Index].count;
					}
					if (num2 > 0)
					{
						int num3 = Move(package, j, itemId2, Math.Min(num2, num), item2);
						if (num3 <= 0)
						{
							break;
						}
						num -= num3;
						result.Items += num3;
						hashSet.Add(itemId2);
						hashSet2.Add(item2.Station.id);
					}
				}
				if (num <= 0)
				{
					continue;
				}
				if (!overflow)
				{
					result.Left += num;
					continue;
				}
				int num4 = Move(package, j, itemId2, num, value2[0]);
				result.Items += num4;
				result.OverMax += num4;
				if (num4 > 0)
				{
					hashSet.Add(itemId2);
					hashSet2.Add(value2[0].Station.id);
				}
			}
			result.Kinds = hashSet.Count;
			result.Stations = hashSet2.Count;
			return result;
		}

		private static int Move(StorageComponent package, int grid, int itemId, int count, Slot t)
		{
			int num = itemId;
			int num2 = count;
			int num3 = default(int);
			package.TakeItemFromGrid(grid, ref num, ref num2, ref num3);
			if (num != itemId || num2 <= 0)
			{
				return 0;
			}
			StationStore[] storage = t.Station.storage;
			lock (storage)
			{
				if (storage[t.Index].itemId == itemId)
				{
					storage[t.Index].count += num2;
					storage[t.Index].inc += num3;
					return num2;
				}
			}
			int num4 = default(int);
			package.AddItemStacked(itemId, num2, num3, ref num4);
			return 0;
		}

		internal static string Tr(string zh, string en)
		{
			if (!Localization.isZHCN)
			{
				return en;
			}
			return zh;
		}

		public static string Describe(Result r)
		{
			if (r.Error != null)
			{
				return r.Error;
			}
			if (r.Items == 0)
			{
				if (r.Left <= 0)
				{
					return Tr("背包里没有物流塔能收的东西", "Nothing in the inventory has a station slot");
				}
				return Tr($"物流塔都满了,还剩 {r.Left} 个没放", $"Every station is full, {r.Left} left");
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(Tr($"存入 {r.Items} 个({r.Kinds} 种)到 {r.Stations} 座物流塔", $"Put {r.Items} items ({r.Kinds} kinds) into {r.Stations} stations"));
			if (r.OverMax > 0)
			{
				stringBuilder.Append(Tr($",其中 {r.OverMax} 个超出上限", $", {r.OverMax} over the max"));
			}
			if (r.Left > 0)
			{
				stringBuilder.Append(Tr($",还剩 {r.Left} 个(塔满了)", $", {r.Left} left (stations full)"));
			}
			return stringBuilder.ToString();
		}

		public static Result Press()
		{
			Result result;
			try
			{
				result = Deposit(GameMain.mainPlayer, Range.Value, Overflow.Value, SkipFilteredSlots.Value);
			}
			catch (Exception ex)
			{
				Log.LogError((object)ex);
				result = new Result
				{
					Error = ex.GetType().Name
				};
			}
			UIRealtimeTip.Popup(Describe(result), false, 0);
			return result;
		}
	}
	public static class InventoryButton
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__3_0;

			internal void <Ensure>b__3_0()
			{
				Plugin.Press();
			}
		}

		public static GameObject Made;

		public static string Found = "not looked yet";

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIInventoryWindow), "_OnOpen")]
		private static void AfterOpen(UIInventoryWindow __instance)
		{
			try
			{
				Ensure(__instance);
			}
			catch (Exception ex)
			{
				Found = "error: " + ex.Message;
				Plugin.Log.LogError((object)ex);
			}
		}

		public static void Ensure(UIInventoryWindow window)
		{
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			//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_00f3: Expected O, but got Unknown
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Expected O, but got Unknown
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Made == (Object)null)
			{
				Button val = null;
				Button[] componentsInChildren = ((Component)window).GetComponentsInChildren<Button>(true);
				foreach (Button val2 in componentsInChildren)
				{
					if (((Object)val2).name == "confirm-btn" && (Object)(object)((Component)val2).GetComponentInChildren<Text>(true) != (Object)null)
					{
						val = val2;
						break;
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					Found = "text button to copy not found";
					Plugin.Log.LogWarning((object)"Clear Inventory: no button to copy, no button added");
					return;
				}
				Found = "copied " + Path(((Component)val).transform, ((Component)window).transform);
				GameObject val3 = Object.Instantiate<GameObject>(((Component)val).gameObject, (Transform)(object)window.windowTrans, false);
				((Object)val3).name = "clear-inventory-button";
				Button component = val3.GetComponent<Button>();
				component.onClick = new ButtonClickedEvent();
				ButtonClickedEvent onClick = component.onClick;
				object obj = <>c.<>9__3_0;
				if (obj == null)
				{
					UnityAction val4 = delegate
					{
						Plugin.Press();
					};
					<>c.<>9__3_0 = val4;
					obj = (object)val4;
				}
				((UnityEvent)onClick).AddListener((UnityAction)obj);
				UIButton component2 = val3.GetComponent<UIButton>();
				if ((Object)(object)component2 != (Object)null)
				{
					component2.tips.tipTitle = Plugin.Tr("清理背包", "Clear inventory");
					component2.tips.tipText = Plugin.Tr("把背包里的东西放进本星球的物流塔(行星塔、星际塔,只放塔里已有这种物品格子的)。近的先放到上限,全都满了,剩下的超出上限放进最近的那座。", "Moves inventory items into this planet's logistics stations that have a slot for them. Nearest first up to each max; when all are full, the rest goes over the max of the nearest one.");
					component2.tips.corner = 3;
					component2.tips.offset = new Vector2(0f, 6f);
				}
				Localizer[] componentsInChildren2 = val3.GetComponentsInChildren<Localizer>(true);
				for (int i = 0; i < componentsInChildren2.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
				}
				Text componentInChildren = val3.GetComponentInChildren<Text>(true);
				componentInChildren.text = Plugin.Tr("清理背包", "Clear");
				RectTransform val5 = (RectTransform)val3.transform;
				Vector2 val6 = default(Vector2);
				((Vector2)(ref val6))..ctor(0f, 1f);
				val5.anchorMax = val6;
				val5.anchorMin = val6;
				val5.pivot = new Vector2(0f, 0.5f);
				val5.sizeDelta = new Vector2(Mathf.Max(70f, componentInChildren.preferredWidth + 20f), val5.sizeDelta.y);
				Made = val3;
			}
			Place(window);
		}

		private static void Place(UIInventoryWindow window)
		{
			//IL_000a: 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_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: 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)
			//IL_0060: Expected O, but got Unknown
			//IL_0090: 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_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: 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_00d2: 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_00df: 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_00e8: 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_00f6: 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)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: 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_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: 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_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: 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_015d: 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_0171: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = (RectTransform)Made.transform;
			Made.SetActive(true);
			UIToggle val2 = (((Object)(object)window.deliveryPanel != (Object)null) ? window.deliveryPanel.deliveryToggle : null);
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor(120f, -48f);
			if ((Object)(object)val2 != (Object)null)
			{
				RectTransform val4 = (RectTransform)((Component)val2).transform;
				Text componentInChildren = ((Component)val2).GetComponentInChildren<Text>(true);
				RectTransform val5 = (((Object)(object)componentInChildren != (Object)null) ? ((Graphic)componentInChildren).rectTransform : val4);
				Vector3[] array = (Vector3[])(object)new Vector3[4];
				val5.GetWorldCorners(array);
				Vector3 val6 = (array[0] + array[1]) * 0.5f;
				Rect rect;
				float num;
				if (!((Object)(object)componentInChildren != (Object)null))
				{
					rect = val5.rect;
					num = ((Rect)(ref rect)).width;
				}
				else
				{
					num = componentInChildren.preferredWidth;
				}
				float num2 = num;
				Vector3 val7 = array[2] - array[1];
				Vector3 val8 = val6 + ((Vector3)(ref val7)).normalized * num2 * ((Transform)val5).lossyScale.x;
				Vector3 val9 = ((Transform)window.windowTrans).InverseTransformPoint(val8);
				rect = window.windowTrans.rect;
				Vector2 size = ((Rect)(ref rect)).size;
				Vector2 pivot = window.windowTrans.pivot;
				((Vector2)(ref val3))..ctor(val9.x + pivot.x * size.x + 16f, val9.y - (1f - pivot.y) * size.y);
			}
			val.anchoredPosition = val3 + new Vector2(Plugin.ButtonOffsetX.Value, Plugin.ButtonOffsetY.Value);
		}

		public static string Path(Transform t, Transform root)
		{
			string text = ((Object)t).name;
			while ((Object)(object)t.parent != (Object)null && (Object)(object)t != (Object)(object)root)
			{
				t = t.parent;
				text = ((Object)t).name + "/" + text;
			}
			return text;
		}
	}
}