Decompiled source of DarkFogWorkshop v1.1.3

DarkFogWorkshop.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("TTenYX")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Logistics stations turn science matrices into Dark Fog materials | 物流塔用科学矩阵产出黑雾材料")]
[assembly: AssemblyFileVersion("1.1.3.0")]
[assembly: AssemblyInformationalVersion("1.1.3")]
[assembly: AssemblyProduct("DarkFogWorkshop")]
[assembly: AssemblyTitle("DarkFogWorkshop")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.3.0")]
[module: UnverifiableCode]
[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;
		}
	}
}
internal static class PluginInfo
{
	public const string PLUGIN_GUID = "TTenYX.DSP.DarkFogWorkshop";

	public const string PLUGIN_NAME = "DarkFogWorkshop";

	public const string PLUGIN_VERSION = "1.1.3";
}
namespace DarkFogWorkshop
{
	internal static class DarkFogItemPickerPatch
	{
		private static readonly int[] DarkFogItemIds = new int[6] { 5201, 5202, 5203, 5204, 5205, 5206 };

		private static readonly int[] VanillaSlots = new int[6] { 104, 106, 108, 107, 11, 105 };

		private const int GridCols = 14;

		private const int GridRows = 8;

		private const int GridSlots = 112;

		private static bool _diagLogged;

		internal static void Install(Harmony harmony)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(UIItemPicker), "RefreshIcons", (Type[])null, (Type[])null);
				MethodInfo methodInfo2 = AccessTools.Method(typeof(DarkFogItemPickerPatch), "RefreshIcons_Postfix", (Type[])null, (Type[])null);
				if (methodInfo == null || methodInfo2 == null)
				{
					ManualLogSource log = DarkFogWorkshop.Log;
					if (log != null)
					{
						log.LogWarning((object)"[选物品] 未找到 UIItemPicker.RefreshIcons,黑雾材料不会出现在选择物品界面。");
					}
				}
				else
				{
					harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = DarkFogWorkshop.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("[选物品] 补丁注册失败(不影响其它功能):" + ex.Message));
				}
			}
		}

		internal static void RefreshIcons_Postfix(UIItemPicker __instance)
		{
			try
			{
				AppendDarkFogItems(__instance);
			}
			catch (Exception ex)
			{
				ManualLogSource log = DarkFogWorkshop.Log;
				if (log != null)
				{
					log.LogWarning((object)("[选物品] 补充黑雾材料失败:" + ex.Message));
				}
			}
		}

		private static void AppendDarkFogItems(UIItemPicker picker)
		{
			if ((Object)(object)picker == (Object)null || GameMain.history == null || GameMain.iconSet == null || picker.onReturn == null || !(picker.onReturn.Target is UIStationStorage))
			{
				return;
			}
			object obj = AccessTools.Field(typeof(UIItemPicker), "currentType")?.GetValue(picker);
			if (obj is int num && num != 1)
			{
				return;
			}
			ItemProto[] array = (ItemProto[])AccessTools.Field(typeof(UIItemPicker), "protoArray")?.GetValue(picker);
			uint[] array2 = (uint[])AccessTools.Field(typeof(UIItemPicker), "indexArray")?.GetValue(picker);
			if (array == null || array2 == null)
			{
				return;
			}
			int num2 = Math.Min(Math.Min(array.Length, array2.Length), 112);
			List<string> list = new List<string>();
			for (int i = 0; i < DarkFogItemIds.Length; i++)
			{
				int num3 = DarkFogItemIds[i];
				bool flag = false;
				for (int j = 0; j < num2; j++)
				{
					if (array[j] != null && ((Proto)array[j]).ID == num3)
					{
						flag = true;
						break;
					}
				}
				if (flag)
				{
					continue;
				}
				ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(num3);
				if (val != null)
				{
					int k;
					for (k = VanillaSlots[i]; k < num2 && array[k] != null; k++)
					{
					}
					if (k < num2)
					{
						array[k] = val;
						array2[k] = GameMain.iconSet.itemIconIndex[num3];
						list.Add($"{num3}@{k}");
					}
				}
			}
			if (!_diagLogged)
			{
				_diagLogged = true;
				ManualLogSource log = DarkFogWorkshop.Log;
				if (log != null)
				{
					log.LogInfo((object)(string.Format("[选物品] currentType={0} 本次摆放=[{1}] ", obj, string.Join(", ", list)) + "(原版格位 1807-1811→末行列6-10,1112→首行列11)"));
				}
			}
		}
	}
	[BepInPlugin("TTenYX.DSP.DarkFogWorkshop", "DarkFogWorkshop", "1.1.3")]
	public class DarkFogWorkshop : BaseUnityPlugin
	{
		public const string PLUGIN_GUID = "TTenYX.DSP.DarkFogWorkshop";

		public const string PLUGIN_NAME = "DarkFogWorkshop";

		public const string HELP_TITLE = "黑雾工坊 DarkFogWorkshop";

		public const string PLUGIN_VERSION = "1.1.3";

		private static readonly Harmony harmony = new Harmony("TTenYX.DSP.DarkFogWorkshop");

		internal static ManualLogSource Log;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			UIStationWindowPatch.CaptureMainThread();
			ModConfig.Bind(((BaseUnityPlugin)this).Config);
			harmony.PatchAll(typeof(DarkFogWorkshopPatch));
			harmony.PatchAll(typeof(UIStationWindowPatch));
			SafePatchAll(typeof(OrbitalRingCompat.OnStationIdChangeGuard), "OrbitalRing.OnStationIdChangeGuard");
			SafePatchAll(typeof(OrbitalRingCompat.OnUpdateGuard), "OrbitalRing.OnUpdateGuard");
			SafePatchAll(typeof(OrbitalRingCompat.OnOpenGuard), "OrbitalRing.OnOpenGuard");
			DarkFogItemPickerPatch.Install(harmony);
			Log.LogInfo((object)"DarkFogWorkshop v1.1.3 已加载(作者 TTenYX)");
			Log.LogInfo((object)($"U={ModConfig.MatrixPointPerMinute.Value}/分钟  X={ModConfig.ExchangeFactor.Value}  " + "Y=" + (ModConfig.UseGameTechSpeed.Value ? "存档矩阵转化算力速度" : (ModConfig.TechSpeedPercent.Value + "%")) + "  " + $"每分钟算力={DarkFogWorkshopPatch.CreditPerMinute():0.##}"));
		}

		private void SafePatchAll(Type patchClass, string label)
		{
			try
			{
				harmony.PatchAll(patchClass);
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("注册补丁 " + label + " 失败(不影响其它功能):" + ex.Message));
			}
		}

		private void OnDestroy()
		{
			harmony.UnpatchSelf();
		}

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

		internal static string ItemName(int itemId)
		{
			if (itemId <= 0)
			{
				return "-";
			}
			ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(itemId);
			if (val == null)
			{
				return itemId.ToString();
			}
			return ((Proto)val).name;
		}
	}
	internal static class ModConfig
	{
		internal static ConfigEntry<double> ExchangeFactor;

		internal static ConfigEntry<int> MatrixPointPerMinute;

		internal static ConfigEntry<int> TechSpeedPercent;

		internal static ConfigEntry<bool> UseGameTechSpeed;

		internal static ConfigEntry<double> SpeedMultiplier;

		internal static ConfigEntry<bool> AccumulatePartialPoints;

		internal static ConfigEntry<int> MetadataMatrixPerMinute;

		internal static ConfigEntry<bool> VerboseLog;

		internal static ConfigEntry<int> ElectromagneticMatrixPoints;

		internal static ConfigEntry<int> EnergyMatrixPoints;

		internal static ConfigEntry<int> StructureMatrixPoints;

		internal static ConfigEntry<int> InformationMatrixPoints;

		internal static ConfigEntry<int> GravityMatrixPoints;

		internal static ConfigEntry<int> UniverseMatrixPoints;

		internal static ConfigEntry<int> EnergyFragmentPoints;

		internal static ConfigEntry<int> DarkFogMatrixPoints;

		internal static ConfigEntry<int> SiliconNeuronPoints;

		internal static ConfigEntry<int> NegentropySingularityPoints;

		internal static ConfigEntry<int> MatterReassemblerPoints;

		internal static ConfigEntry<int> CoreElementPoints;

		internal static ConfigEntry<int> OutputSlotLimit;

		internal static ConfigEntry<bool> DiagnosticLog;

		internal static void Bind(ConfigFile config)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Expected O, but got Unknown
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Expected O, but got Unknown
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Expected O, but got Unknown
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Expected O, but got Unknown
			//IL_0313: Unknown result type (might be due to invalid IL or missing references)
			//IL_031d: Expected O, but got Unknown
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Expected O, but got Unknown
			ExchangeFactor = config.Bind<double>("1. 通用", "ExchangeFactor", 1.0, new ConfigDescription("兑换系数 X:矩阵点数 = X × 黑雾材料算力。可小数(如 0.5、2.5),必须大于 0。\nX=1 时 1 个宇宙矩阵(3000) 可换 1 个核心素(3000) 或 60 个能量碎片(50)。", (AcceptableValueBase)(object)new AcceptableValueRange<double>(0.0001, 1000000.0), Array.Empty<object>()));
			MatrixPointPerMinute = config.Bind<int>("1. 通用", "MatrixPointPerMinute", 7200, new ConfigDescription("矩阵转化算力速度 U:物流塔**每分钟**可进行兑换的算力(Y=100% 时)。默认 7200。\n最终**每分钟算力 = U × Y**(Y 为「矩阵转化算力速度」百分比,如 1500% 即 15 倍)。\n例:U=7200、Y=1500% ⇒ 7200 × 15 = 108000 点/分钟。", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100000000), Array.Empty<object>()));
			TechSpeedPercent = config.Bind<int>("1. 通用", "TechSpeedPercent", 100, new ConfigDescription("矩阵转化算力速度 Y 的默认值(百分比)。100 表示 100%,即 1 倍。\n举例:研究速度 14 级(游戏内显示 1500%)就填 1500。\nUseGameTechSpeed = true 时本项被忽略。", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100000000), Array.Empty<object>()));
			UseGameTechSpeed = config.Bind<bool>("1. 通用", "UseGameTechSpeed", true, new ConfigDescription("true:Y 自动取存档的研究速度数值(GameMain.history.techSpeed 是**倍率**,\n  14 级为 15,等价于游戏面板显示的 1500%)。\nfalse:Y 恒定使用上面的 TechSpeedPercent。\n若发现实际速率与预期不符,把它设为 false 并手填数值。", (AcceptableValueBase)null, Array.Empty<object>()));
			SpeedMultiplier = config.Bind<double>("1. 通用", "SpeedMultiplier", 1.0, new ConfigDescription("调试倍率,默认 1(不放大)。最终每分钟算力 = U × Y × 本项。", (AcceptableValueBase)(object)new AcceptableValueRange<double>(0.0, 1000000.0), Array.Empty<object>()));
			AccumulatePartialPoints = config.Bind<bool>("1. 通用", "AccumulatePartialPoints", true, new ConfigDescription("单帧算力买不起 1 个矩阵 / 1 个材料时,是否把这笔算力攒着、凑够 1 个再扣。\ntrue(推荐):结余仍然不结转,只会攒「没凑满 1 个」的零头。\n  矩阵侧等效吞吐 = 材料种数 × 每分钟算力;每种材料的产出 = 每分钟算力 / 单价 个/分钟。\nfalse:严格按单帧算力结算。此时若「每分钟算力 / 3600」小于单价,就会永远兑换不出来——\n  例如每分钟算力 3600 点(=1 点/帧)时,物质重组器 100 点、核心素 300 点都买不起,\n  结果是「只有能量碎片(50 点)能产出」,其它材料永远为 0。", (AcceptableValueBase)null, Array.Empty<object>()));
			MetadataMatrixPerMinute = config.Bind<int>("1. 通用", "MetadataMatrixPerMinute", 600, new ConfigDescription("勾选物流塔上的「元数据兑换科学矩阵」后,按此速率兑换对应矩阵(个/分钟)。默认 600。", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1000000), Array.Empty<object>()));
			VerboseLog = config.Bind<bool>("1. 通用", "VerboseLog", false, new ConfigDescription("详细诊断日志:每次真正发生兑换时,逐槽位打印 物品/数量/上限/单价/配额/本帧产出。\n**默认关闭**(会把日志刷满)。排查「某些材料不产出」时临时改成 true。", (AcceptableValueBase)null, Array.Empty<object>()));
			ElectromagneticMatrixPoints = BindPoints(config, "2. 科学矩阵算力", "ElectromagneticMatrix", 50, "电磁矩阵 (1201)");
			EnergyMatrixPoints = BindPoints(config, "2. 科学矩阵算力", "EnergyMatrix", 100, "能量矩阵 (1202)");
			StructureMatrixPoints = BindPoints(config, "2. 科学矩阵算力", "StructureMatrix", 250, "结构矩阵 (1203)");
			InformationMatrixPoints = BindPoints(config, "2. 科学矩阵算力", "InformationMatrix", 750, "信息矩阵 (1204)");
			GravityMatrixPoints = BindPoints(config, "2. 科学矩阵算力", "GravityMatrix", 1500, "引力矩阵 (1205)");
			UniverseMatrixPoints = BindPoints(config, "2. 科学矩阵算力", "UniverseMatrix", 3000, "宇宙矩阵 (1206)");
			EnergyFragmentPoints = BindPoints(config, "3. 黑雾材料算力", "EnergyFragment", 50, "能量碎片 (5206)");
			DarkFogMatrixPoints = BindPoints(config, "3. 黑雾材料算力", "DarkFogMatrix", 150, "黑雾矩阵 (5201)");
			SiliconNeuronPoints = BindPoints(config, "3. 黑雾材料算力", "SiliconNeuron", 100, "硅基神经元 (5202)");
			NegentropySingularityPoints = BindPoints(config, "3. 黑雾材料算力", "NegentropySingularity", 100, "负熵奇点 (5204)");
			MatterReassemblerPoints = BindPoints(config, "3. 黑雾材料算力", "MatterReassembler", 100, "物质重组器 (5203)");
			CoreElementPoints = BindPoints(config, "3. 黑雾材料算力", "CoreElement", 300, "核心素 (5205)");
			OutputSlotLimit = config.Bind<int>("1. 通用", "OutputSlotLimit", 6, new ConfigDescription("参与兑换的材料槽位上限(第几格)。默认 6:原版塔的全部槽位都能兑换。\n本项只限制产出侧;第 1 格(矩阵)始终参与。装运输塔扩容后想用更多格就填更大。\n每种材料各占一份算力,格数越多矩阵消耗越快。", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 20), Array.Empty<object>()));
			DiagnosticLog = config.Bind<bool>("4. 界面", "DiagnosticLog", false, new ConfigDescription("把每座塔每 2 秒的兑换判定过程写入 BepInEx 日志,用于排查「不兑换」的问题。\n排查完可以改成 false 关掉。", (AcceptableValueBase)null, Array.Empty<object>()));
		}

		private static ConfigEntry<int> BindPoints(ConfigFile config, string section, string key, int value, string label)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			return config.Bind<int>(section, key, value, new ConfigDescription(label + " 的算力(兑换权重)。必须为正整数。", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100000000), Array.Empty<object>()));
		}
	}
	[HarmonyPatch]
	public static class DarkFogWorkshopPatch
	{
		internal class State
		{
			internal bool active;

			internal int consumedMatrices;

			internal int producedTotal;

			internal double unusedPoints;

			internal double partialPoints;

			internal int matrixPartialItem;

			internal readonly double[] materialPartial = new double[20];

			internal readonly int[] materialPartialItem = new int[20];

			internal int activeKinds;

			internal bool metadataExchangeEnabled;

			internal double metadataPartial;

			internal long lastDiagTick;
		}

		internal const int MatrixSlot = 0;

		internal const int OutputSlotFirst = 1;

		internal const int OutputSlotLast = 3;

		private const int OutputSlotCapacity = 20;

		internal const int DarkFogMatrixId = 5201;

		internal const int SiliconNeuronId = 5202;

		internal const int MatterReassemblerId = 5203;

		internal const int NegentropySingularityId = 5204;

		internal const int CoreElementId = 5205;

		internal const int EnergyFragmentId = 5206;

		private const double MinPointsPerMaterial = 1.0;

		private const double PartialCapUnits = 64.0;

		private static readonly ConditionalWeakTable<StationComponent, State> states = new ConditionalWeakTable<StationComponent, State>();

		private static readonly HashSet<StationComponent> metadataStations = new HashSet<StationComponent>();

		internal const double TicksPerSecond = 60.0;

		internal const double TicksPerMinute = 3600.0;

		private const int IncLevelMax = 10;

		private const int NameFieldUnits = 24;

		private const int IconUnits = 4;

		private const int NameValueGapSpaces = 4;

		private const int BaseFontSize = 14;

		private const float LineHeightScale = 1.5f;

		private const string ProduceColor = "#61D8FF";

		private const string ConsumeColor = "#ff965e";

		private static readonly Dictionary<int, string> iconTagCache = new Dictionary<int, string>();

		private static int OutputSlotLastIndex(StationStore[] storage)
		{
			int num = ((ModConfig.OutputSlotLimit != null) ? ModConfig.OutputSlotLimit.Value : 4) - 1;
			if (num > 20)
			{
				num = 20;
			}
			if (num >= storage.Length)
			{
				num = storage.Length - 1;
			}
			return num;
		}

		internal static void SetMetadataExchangeEnabled(StationComponent station, bool enabled)
		{
			if (station != null)
			{
				State state = GetState(station);
				state.metadataExchangeEnabled = enabled;
				state.metadataPartial = 0.0;
				if (enabled)
				{
					metadataStations.Add(station);
				}
				else
				{
					metadataStations.Remove(station);
				}
			}
		}

		internal static bool IsMetadataExchangeEnabled(StationComponent station)
		{
			if (station != null && states.TryGetValue(station, out var value))
			{
				return value.metadataExchangeEnabled;
			}
			return false;
		}

		internal static bool IsMetadataExchangeEligible(StationComponent station)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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_0024: 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)
			if (station == null || station.storage == null || station.storage.Length == 0)
			{
				return false;
			}
			StationStore val = station.storage[0];
			if ((int)val.localLogic == 0)
			{
				return IsScienceMatrix(val.itemId);
			}
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameMain), "Update")]
		public static void GameMain_Update_Postfix()
		{
			if (metadataStations.Count == 0 || GameMain.data == null || DSPGame.propertySystem == null)
			{
				return;
			}
			List<StationComponent> list = null;
			foreach (StationComponent metadataStation in metadataStations)
			{
				if (metadataStation == null || !states.TryGetValue(metadataStation, out var value) || !value.metadataExchangeEnabled || !IsMetadataExchangeEligible(metadataStation) || !TryExchangeMetadataMatrix(metadataStation))
				{
					if (list == null)
					{
						list = new List<StationComponent>();
					}
					list.Add(metadataStation);
				}
			}
			if (list == null)
			{
				return;
			}
			for (int i = 0; i < list.Count; i++)
			{
				StationComponent val = list[i];
				metadataStations.Remove(val);
				if (val != null && states.TryGetValue(val, out var value2))
				{
					value2.metadataExchangeEnabled = false;
					value2.metadataPartial = 0.0;
				}
			}
		}

		private static bool TryExchangeMetadataMatrix(StationComponent station)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: 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)
			State state = GetState(station);
			StationStore[] storage = station.storage;
			if (storage == null || storage.Length == 0)
			{
				return false;
			}
			StationStore val = storage[0];
			int num = val.max - val.count;
			if (num <= 0)
			{
				state.metadataPartial = 0.0;
				return true;
			}
			long clusterSeedKey = GameMain.data.GetClusterSeedKey();
			long itemAvaliableProperty = DSPGame.propertySystem.GetItemAvaliableProperty(clusterSeedKey, val.itemId);
			if (itemAvaliableProperty <= 0)
			{
				state.metadataPartial = 0.0;
				return true;
			}
			double num2 = (double)Math.Max(1, ModConfig.MetadataMatrixPerMinute.Value) / 3600.0;
			state.metadataPartial += num2;
			int num3 = (int)Math.Min(Math.Floor(state.metadataPartial), Math.Min(num, itemAvaliableProperty));
			if (num3 <= 0)
			{
				return true;
			}
			DSPGame.propertySystem.AddItemConsumption(clusterSeedKey, val.itemId, num3);
			GameMain.data.history.AddPropertyItemConsumption(val.itemId, num3, true);
			val.count += num3;
			storage[0] = val;
			state.metadataPartial -= num3;
			return true;
		}

		internal static State GetState(StationComponent station)
		{
			return states.GetOrCreateValue(station);
		}

		internal static void ResetState(StationComponent station)
		{
			if (station != null && states.TryGetValue(station, out var value))
			{
				value.active = false;
				value.consumedMatrices = 0;
				value.producedTotal = 0;
				value.unusedPoints = 0.0;
				value.partialPoints = 0.0;
				value.matrixPartialItem = 0;
				value.metadataExchangeEnabled = false;
				value.metadataPartial = 0.0;
				metadataStations.Remove(station);
				value.activeKinds = 0;
				for (int i = 0; i < value.materialPartial.Length; i++)
				{
					value.materialPartial[i] = 0.0;
					value.materialPartialItem[i] = 0;
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlanetTransport), "GameTick")]
		public static void PlanetTransport_GameTick_Postfix(PlanetTransport __instance)
		{
			PlanetFactory factory = __instance.factory;
			StationComponent[] stationPool = __instance.stationPool;
			if (factory == null || stationPool == null)
			{
				return;
			}
			FactoryProductionStat[] array = ((GameMain.statistics != null) ? GameMain.statistics.production : null)?.factoryStatPool;
			if (array == null || factory.index < 0 || factory.index >= array.Length)
			{
				return;
			}
			FactoryProductionStat val = array[factory.index];
			if (val == null)
			{
				return;
			}
			for (int i = 1; i < __instance.stationCursor; i++)
			{
				StationComponent val2 = stationPool[i];
				if (val2 != null && val2.id == i && !val2.isCollector && !val2.isVeinCollector)
				{
					try
					{
						Tick(val2, val.productRegister, val.consumeRegister);
					}
					catch (Exception arg)
					{
						DarkFogWorkshop.Log.LogError((object)$"黑雾工坊处理运输塔 {i} 时出错:{arg}");
					}
				}
			}
		}

		private static void Tick(StationComponent station, int[] productRegister, int[] consumeRegister)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Invalid comparison between Unknown and I4
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Invalid comparison between Unknown and I4
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			StationStore[] storage = station.storage;
			State orCreateValue = states.GetOrCreateValue(station);
			orCreateValue.active = false;
			orCreateValue.consumedMatrices = 0;
			orCreateValue.producedTotal = 0;
			orCreateValue.unusedPoints = 0.0;
			orCreateValue.activeKinds = 0;
			if (storage == null || storage.Length <= 1)
			{
				SettleDbg(station, orCreateValue, "槽位不足", "");
				return;
			}
			bool flag = orCreateValue.metadataExchangeEnabled && (int)storage[0].localLogic == 0;
			if ((int)storage[0].localLogic != 2 && !flag)
			{
				SettleDbg(station, orCreateValue, "未勾本地需求", $"第1格物品={storage[0].itemId} localLogic={storage[0].localLogic}");
				return;
			}
			int itemId = storage[0].itemId;
			double num = MatrixPointsOf(itemId);
			if (num <= 0.0)
			{
				SettleDbg(station, orCreateValue, "第1格不是科学矩阵", $"itemId={itemId}");
				return;
			}
			if (orCreateValue.matrixPartialItem != itemId)
			{
				SettleDbg(station, orCreateValue, "矩阵类型变化,清空算力累积", $"旧={orCreateValue.matrixPartialItem} 新={itemId} " + $"旧零头={orCreateValue.partialPoints:0.##}");
				orCreateValue.matrixPartialItem = itemId;
				orCreateValue.partialPoints = 0.0;
				for (int i = 0; i < orCreateValue.materialPartial.Length; i++)
				{
					orCreateValue.materialPartial[i] = 0.0;
					orCreateValue.materialPartialItem[i] = 0;
				}
			}
			int num2 = OutputSlotLastIndex(storage);
			double num3 = BudgetPerTick();
			orCreateValue.unusedPoints = 0.0;
			if (num3 <= 0.0)
			{
				SettleDbg(station, orCreateValue, "本帧算力为0", $"矩阵单价={num}");
				return;
			}
			double[] array = new double[20];
			int[] array2 = new int[20];
			double[] array3 = new double[20];
			double[] array4 = new double[20];
			double num4 = IncOutputMultiplier(station);
			if (num4 < 1.0)
			{
				num4 = 1.0;
			}
			int num5 = 0;
			int num6 = 0;
			for (int j = 1; j <= num2; j++)
			{
				int num7 = j - 1;
				int itemId2 = storage[j].itemId;
				double num8 = MaterialPointsOf(itemId2);
				array2[num7] = itemId2;
				array3[num7] = num8;
				if (num8 <= 0.0)
				{
					orCreateValue.materialPartial[num7] = 0.0;
					orCreateValue.materialPartialItem[num7] = 0;
					continue;
				}
				array[num7] = num3;
				num5++;
				bool flag2 = (double)(storage[j].max - storage[j].count) > 0.0;
				if (flag2)
				{
					num6++;
				}
				if (ModConfig.AccumulatePartialPoints.Value)
				{
					if (orCreateValue.materialPartialItem[num7] != itemId2)
					{
						orCreateValue.materialPartial[num7] = 0.0;
						orCreateValue.materialPartialItem[num7] = itemId2;
					}
					orCreateValue.materialPartial[num7] += num3;
				}
				else
				{
					orCreateValue.materialPartial[num7] = num3;
				}
				double num9 = num8 * (flag2 ? 64.0 : 1.0);
				if (orCreateValue.materialPartial[num7] > num9)
				{
					orCreateValue.materialPartial[num7] = num9;
				}
				array4[num7] = orCreateValue.materialPartial[num7];
			}
			if (num5 == 0)
			{
				SettleDbg(station, orCreateValue, "第2/3/4格没有黑雾材料", $"第1格={itemId} 数量={storage[0].count}");
				return;
			}
			orCreateValue.activeKinds = num5;
			if (num6 == 0)
			{
				orCreateValue.consumedMatrices = 0;
				orCreateValue.producedTotal = 0;
				SettleDbg(station, orCreateValue, "材料槽位全满,跳过消耗", $"材料种数={num5} 第1格={itemId} 存量={storage[0].count}");
				return;
			}
			double num10 = (double)num5 * num3;
			orCreateValue.activeKinds = num5;
			int num11 = 0;
			int[] array5 = null;
			double num12 = 0.0;
			lock (storage)
			{
				int count = storage[0].count;
				double num13 = num10;
				if (num13 > (double)count * num)
				{
					num13 = (double)count * num;
					double num14 = ((num10 > 0.0) ? (num13 / num10) : 0.0);
					for (int k = 0; k < array.Length; k++)
					{
						array[k] *= num14;
					}
				}
				if (num13 > 0.0)
				{
					int num15 = (int)Math.Floor(num13 / num);
					if (num15 >= 1)
					{
						orCreateValue.partialPoints = 0.0;
						num11 = Math.Min(num15, count);
					}
					else if (ModConfig.AccumulatePartialPoints.Value && count > 0)
					{
						orCreateValue.partialPoints += num13;
						if (orCreateValue.partialPoints >= num)
						{
							orCreateValue.partialPoints -= num;
							if (orCreateValue.partialPoints < 0.0)
							{
								orCreateValue.partialPoints = 0.0;
							}
							num11 = 1;
						}
					}
					else
					{
						orCreateValue.partialPoints = 0.0;
					}
				}
				int num16 = 0;
				double num17 = 0.0;
				if (num11 > 0)
				{
					ConsumeMatrixWithInc(ref storage[0], num11);
					for (int l = 1; l <= num2; l++)
					{
						int num18 = l - 1;
						double num19 = array3[num18];
						if (num19 <= 0.0)
						{
							continue;
						}
						ref StationStore reference = ref storage[l];
						double num20 = reference.max - reference.count;
						if (!(num20 <= 0.0))
						{
							double num21 = num19 / num4;
							double num22 = Math.Floor(orCreateValue.materialPartial[num18] / num21);
							if (num22 > num20)
							{
								num22 = num20;
							}
							if (!(num22 <= 0.0))
							{
								int num23 = (int)num22;
								reference.count += num23;
								double num24 = (double)num23 * num21;
								orCreateValue.materialPartial[num18] = Math.Max(0.0, orCreateValue.materialPartial[num18] - num24);
								num16 += num23;
								array5 = AddCount(array5, reference.itemId, num23);
								num17 += num24;
							}
						}
					}
				}
				orCreateValue.unusedPoints = Math.Max(0.0, (double)num11 * num - num17);
				orCreateValue.consumedMatrices = num11;
				orCreateValue.producedTotal = num16;
				num12 = num17;
				if (num11 > 0)
				{
					RegisterConsume(consumeRegister, itemId, num11);
				}
				if (num16 > 0 && array5 != null && productRegister != null)
				{
					for (int m = 0; m < array5.Length; m += 2)
					{
						RegisterProduce(productRegister, array5[m], array5[m + 1]);
					}
				}
				orCreateValue.active = true;
			}
			SettleDbg(station, orCreateValue, "已结算", $"第1格={itemId} 槽内存量={storage[0].count} 单价={num:0.##} " + $"需算力={num10:0.##} 用掉算力={num12:0.##} 材料种数={orCreateValue.activeKinds} " + $"本帧消耗={num11} 本帧产出={orCreateValue.producedTotal}");
			if (ModConfig.VerboseLog.Value && (num11 > 0 || orCreateValue.producedTotal > 0))
			{
				LogSlotDetail(station, storage, num2, array4, array3, num11, orCreateValue);
			}
		}

		private static void LogSlotDetail(StationComponent station, StationStore[] storage, int lastOutput, double[] materialPoints, double[] unitCost, int consumed, State state)
		{
			if (ModConfig.VerboseLog.Value)
			{
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append($"[槽位明细] 塔{station.id} 本帧消耗矩阵={consumed} 产出={state.producedTotal} " + $"storage.Length={storage.Length} lastOutput下标={lastOutput}");
				for (int i = 1; i <= lastOutput; i++)
				{
					int num = i - 1;
					ref StationStore reference = ref storage[i];
					double num2 = unitCost[num];
					stringBuilder.Append($"\n    第{i + 1}格 itemId={reference.itemId} 数量={reference.count}/{reference.max} " + $"单价={num2:0.##} 累积点数={materialPoints[num]:0.##} " + $"可换={((num2 > 0.0) ? Math.Floor(materialPoints[num] / num2) : 0.0)}");
				}
				DarkFogWorkshop.Log.LogInfo((object)stringBuilder.ToString());
			}
		}

		private static void SettleDbg(StationComponent station, State state, string stage, string extra)
		{
			if (ModConfig.DiagnosticLog.Value && GameMain.gameTick - state.lastDiagTick >= 120)
			{
				state.lastDiagTick = GameMain.gameTick;
				DarkFogWorkshop.Log.LogInfo((object)($"[诊断] 塔{station.id} 阶段={stage} {extra} 每分钟算力={CreditPerMinute():0.##} " + $"消耗矩阵={state.consumedMatrices} 产出={state.producedTotal} 材料种数={state.activeKinds}"));
			}
		}

		private static int[] AddCount(int[] pairs, int itemId, int count)
		{
			if (pairs == null)
			{
				return new int[2] { itemId, count };
			}
			for (int i = 0; i < pairs.Length; i += 2)
			{
				if (pairs[i] == itemId)
				{
					pairs[i + 1] += count;
					return pairs;
				}
			}
			int[] array = new int[pairs.Length + 2];
			Array.Copy(pairs, array, pairs.Length);
			array[pairs.Length] = itemId;
			array[pairs.Length + 1] = count;
			return array;
		}

		private static void RegisterConsume(int[] consumeRegister, int itemId, int count)
		{
			if (consumeRegister == null || itemId <= 0 || itemId >= consumeRegister.Length)
			{
				return;
			}
			lock (consumeRegister)
			{
				consumeRegister[itemId] += count;
			}
		}

		private static void RegisterProduce(int[] productRegister, int itemId, int count)
		{
			if (productRegister == null || itemId <= 0 || itemId >= productRegister.Length)
			{
				return;
			}
			lock (productRegister)
			{
				productRegister[itemId] += count;
			}
		}

		internal static double CreditPerMinute()
		{
			double num = (double)ModConfig.MatrixPointPerMinute.Value * TechSpeedScale() * ModConfig.SpeedMultiplier.Value;
			if (!(num > 0.0))
			{
				return 0.0;
			}
			return num;
		}

		internal static double BudgetPerTick()
		{
			return CreditPerMinute() / 3600.0;
		}

		internal static double TechSpeedScale()
		{
			if (ModConfig.UseGameTechSpeed.Value)
			{
				try
				{
					int num = ((GameMain.history != null) ? GameMain.history.techSpeed : 0);
					if (num > 0)
					{
						return num;
					}
				}
				catch (Exception)
				{
				}
			}
			return (double)Math.Max(1, ModConfig.TechSpeedPercent.Value) / 100.0;
		}

		internal static int IncLevelOf(in StationStore matrixSlot)
		{
			int count = matrixSlot.count;
			if (count <= 0 || matrixSlot.inc <= 0)
			{
				return 0;
			}
			int num = matrixSlot.inc / count;
			if (num < 0)
			{
				return 0;
			}
			if (num <= 10)
			{
				return num;
			}
			return 10;
		}

		internal static void ConsumeMatrixWithInc(ref StationStore matrixSlot, int consume)
		{
			if (consume > 0)
			{
				int count = matrixSlot.count;
				int inc = matrixSlot.inc;
				if (count <= 0 || inc <= 0)
				{
					matrixSlot.count = Math.Max(0, count - consume);
					matrixSlot.inc = 0;
					return;
				}
				int num = inc / count;
				int num2 = inc - num * count;
				int num3 = Math.Max(0, count - consume);
				num2 -= num3;
				int num4 = ((num2 > 0) ? (num * consume + num2) : (num * consume));
				matrixSlot.count = num3;
				matrixSlot.inc = Math.Max(0, inc - num4);
			}
		}

		internal static double IncBonusRatio(int level)
		{
			if (level <= 0)
			{
				return 0.0;
			}
			try
			{
				if (level >= Cargo.incTableMilli.Length)
				{
					level = Cargo.incTableMilli.Length - 1;
				}
				double num = Cargo.incTableMilli[level];
				return (num > 0.0) ? num : 0.0;
			}
			catch (Exception)
			{
				return 0.0;
			}
		}

		internal static double IncOutputMultiplier(StationComponent station)
		{
			StationStore[] array = station?.storage;
			if (array == null || array.Length == 0)
			{
				return 1.0;
			}
			return 1.0 + IncBonusRatio(IncLevelOf(in array[0]));
		}

		internal static double MatrixPointsOf(int itemId)
		{
			return itemId switch
			{
				6001 => ModConfig.ElectromagneticMatrixPoints.Value, 
				6002 => ModConfig.EnergyMatrixPoints.Value, 
				6003 => ModConfig.StructureMatrixPoints.Value, 
				6004 => ModConfig.InformationMatrixPoints.Value, 
				6005 => ModConfig.GravityMatrixPoints.Value, 
				6006 => ModConfig.UniverseMatrixPoints.Value, 
				_ => 0.0, 
			};
		}

		internal static double MaterialPointsOf(int itemId)
		{
			int value;
			switch (itemId)
			{
			case 5201:
				value = ModConfig.DarkFogMatrixPoints.Value;
				break;
			case 5202:
				value = ModConfig.SiliconNeuronPoints.Value;
				break;
			case 5203:
				value = ModConfig.MatterReassemblerPoints.Value;
				break;
			case 5204:
				value = ModConfig.NegentropySingularityPoints.Value;
				break;
			case 5205:
				value = ModConfig.CoreElementPoints.Value;
				break;
			case 5206:
				value = ModConfig.EnergyFragmentPoints.Value;
				break;
			default:
				return 0.0;
			}
			if (value <= 0)
			{
				return 0.0;
			}
			return Math.Max(1.0, (double)value * ModConfig.ExchangeFactor.Value);
		}

		internal static bool IsDarkFogMaterial(int itemId)
		{
			return MaterialPointsOf(itemId) > 0.0;
		}

		internal static bool IsScienceMatrix(int itemId)
		{
			return MatrixPointsOf(itemId) > 0.0;
		}

		internal static bool IsMatrixDemanded(StationComponent station)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			StationStore[] array = station?.storage;
			if (array != null && array.Length != 0)
			{
				return (int)array[0].localLogic == 2;
			}
			return false;
		}

		internal static bool IsWorkshopShape(StationComponent station)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Invalid comparison between Unknown and I4
			StationStore[] array = station?.storage;
			if (array == null || array.Length <= 1)
			{
				return false;
			}
			if ((int)array[0].localLogic != 2)
			{
				return false;
			}
			if (!IsScienceMatrix(array[0].itemId))
			{
				return false;
			}
			int num = Math.Min(3, array.Length - 1);
			for (int i = 1; i <= num; i++)
			{
				if (IsDarkFogMaterial(array[i].itemId))
				{
					return true;
				}
			}
			return false;
		}

		internal static int CountMaterials(StationComponent station)
		{
			StationStore[] array = station?.storage;
			if (array == null)
			{
				return 0;
			}
			int num = OutputSlotLastIndex(array);
			int num2 = 0;
			for (int i = 1; i <= num; i++)
			{
				if (IsDarkFogMaterial(array[i].itemId))
				{
					num2++;
				}
			}
			return num2;
		}

		internal static string DescribeDetail(StationComponent station)
		{
			StationStore[] array = station?.storage;
			StringBuilder stringBuilder = new StringBuilder();
			double num = CreditPerMinute();
			int num2 = CountMaterials(station);
			double num3 = ((array != null && array.Length != 0) ? MatrixPointsOf(array[0].itemId) : 0.0);
			double num4 = IncOutputMultiplier(station);
			int num5 = ((array != null && array.Length != 0) ? IncLevelOf(in array[0]) : 0);
			double num6 = TechSpeedScale() * 100.0;
			if (array != null && array.Length != 0)
			{
				int itemId = array[0].itemId;
				stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr("当前矩阵转化算力速度 Y ", "current matrix conversion speed Y ") + $"{num6:0.#}%" + "  ( " + DarkFogWorkshop.Tr("升级「研究速度」可提升", "upgrade Research Speed") + " )"));
				stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr("单种材料每分钟算力 ", "per-material per-minute credit ") + $"= U {ModConfig.MatrixPointPerMinute.Value} × Y {num6:0.#}%" + $" = {num:0.##}"));
				stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr("黑雾工坊初始算力 U 可在配置文件中修改", "U is the base credit, configurable in the config file")));
				stringBuilder.AppendLine();
				stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr("第 1 槽位", "Slot 1") + " ( " + Consume(DarkFogWorkshop.Tr("消耗", "input")) + " ) : " + ItemLabel(itemId)));
				if (num3 > 0.0 && num2 > 0)
				{
					double num7 = num / num3;
					stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr("消耗速度 ", "consume ") + $"{num7:0.##}" + DarkFogWorkshop.Tr("/分钟", "/min") + " ( " + DarkFogWorkshop.Tr("单种", "single") + " )  " + DarkFogWorkshop.Tr("合计 ", "total ") + $"{num7 * (double)num2:0.##}" + DarkFogWorkshop.Tr("/分钟", "/min") + " ( " + num2 + DarkFogWorkshop.Tr("种合计", " kinds") + " )"));
				}
				else
				{
					stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr("消耗速度 0/分钟 ( 材料未在兑换 )", "consume 0/min ( idle )")));
				}
				if (num4 > 1.0)
				{
					stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr("科学矩阵已喷涂增产剂:", "Matrix proliferated: ") + Produce(DarkFogWorkshop.Tr("额外产出", "extra output")) + $" +{(num4 - 1.0) * 100.0:0.#}%" + DarkFogWorkshop.Tr($" ( 等级 {num5} )", $" ( lv {num5} )") + DarkFogWorkshop.Tr($" → 转化 ×{num4:0.###} 黑雾材料", $" -> x{num4:0.###} dark fog material")));
				}
				else
				{
					stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr("科学矩阵若喷涂增产剂可获得", "Spraying the slot-1 matrix grants ") + Produce(DarkFogWorkshop.Tr("额外产出", "extra output")) + DarkFogWorkshop.Tr("黑雾材料", " dark fog material")));
				}
			}
			if (array != null)
			{
				int num8 = OutputSlotLastIndex(array);
				bool flag = false;
				for (int i = 1; i <= num8; i++)
				{
					double num9 = MaterialPointsOf(array[i].itemId);
					if (!(num9 <= 0.0))
					{
						flag = true;
						stringBuilder.AppendLine();
						stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr($"第 {i + 1} 槽位", $"Slot {i + 1}") + " ( " + Produce(DarkFogWorkshop.Tr("产出", "output")) + " ) : " + ItemLabel(array[i].itemId)));
						stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr("转化速度 ", "convert ") + $"{num * num4 / num9:0.##}" + DarkFogWorkshop.Tr("/分钟", "/min")));
					}
				}
				if (!flag)
				{
					stringBuilder.AppendLine();
					stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr("( 第 2 格起还没有放黑雾材料 )", "( no dark fog material in slot 2+ )")));
				}
			}
			stringBuilder.AppendLine();
			stringBuilder.AppendLine(Line(TableHeader2()));
			stringBuilder.AppendLine(Line(TableRow2(6001, MatrixPointsOf(6001))));
			stringBuilder.AppendLine(Line(TableRow2(6002, MatrixPointsOf(6002))));
			stringBuilder.AppendLine(Line(TableRow2(6003, MatrixPointsOf(6003))));
			stringBuilder.AppendLine(Line(TableRow2(6004, MatrixPointsOf(6004))));
			stringBuilder.AppendLine(Line(TableRow2(6005, MatrixPointsOf(6005))));
			stringBuilder.AppendLine(Line(TableRow2(6006, MatrixPointsOf(6006))));
			stringBuilder.AppendLine(Line(TableBlankRow()));
			stringBuilder.AppendLine(Line(TableSectionHeader(DarkFogWorkshop.Tr("黑雾材料", "Dark fog"), DarkFogWorkshop.Tr("算力", "Pts"))));
			stringBuilder.AppendLine(Line(TableRow2(5206, MaterialPointsOf(5206))));
			stringBuilder.AppendLine(Line(TableRow2(5201, MaterialPointsOf(5201))));
			stringBuilder.AppendLine(Line(TableRow2(5202, MaterialPointsOf(5202))));
			stringBuilder.AppendLine(Line(TableRow2(5204, MaterialPointsOf(5204))));
			stringBuilder.AppendLine(Line(TableRow2(5203, MaterialPointsOf(5203))));
			stringBuilder.AppendLine(Line(TableRow2(5205, MaterialPointsOf(5205))));
			stringBuilder.AppendLine();
			stringBuilder.AppendLine(Line(DarkFogWorkshop.Tr("Tips: 各物品算力可在配置文件中修改", "Tips: point values are configurable in the config file")));
			return stringBuilder.ToString().TrimEnd();
		}

		private static string TableHeader2()
		{
			return Cell2(DarkFogWorkshop.Tr("科学矩阵", "Matrix"), DarkFogWorkshop.Tr("算力", "Pts"), hasIcon: false);
		}

		private static string TableRow2(int itemId, double value)
		{
			return Cell2(ItemLabel(itemId), ValueText(value), hasIcon: true);
		}

		private static string TableSectionHeader(string name, string value)
		{
			return Cell2(name, value, hasIcon: false);
		}

		private static string TableBlankRow()
		{
			return "\t";
		}

		private static string Cell2(string name, string valueText, bool hasIcon)
		{
			string text = StripIconTags(name);
			int num = DisplayUnits(text);
			if (hasIcon && name.Length > text.Length)
			{
				num += 4;
			}
			int count = Math.Max(4, 24 - num);
			return name + new string(' ', count) + "\t" + valueText;
		}

		private static int DisplayUnits(string text)
		{
			int num = 0;
			for (int i = 0; i < text.Length; i++)
			{
				num += ((text[i] <= '\u2000') ? 1 : 2);
			}
			return num;
		}

		private static string Line(string content)
		{
			int num = (int)Math.Round(21.0);
			return $"<size={num}>\u2009</size>{content}";
		}

		private static string Produce(string text)
		{
			return "<color=#61D8FF>" + text + "</color>";
		}

		private static string Consume(string text)
		{
			return "<color=#ff965e>" + text + "</color>";
		}

		internal static string ItemLabel(int itemId)
		{
			string text = TryGetIconTag(itemId);
			string text2 = DarkFogWorkshop.ItemName(itemId);
			if (text == null)
			{
				return text2;
			}
			return text + text2;
		}

		private static string TryGetIconTag(int itemId)
		{
			if (iconTagCache.TryGetValue(itemId, out var value))
			{
				return value;
			}
			string text = null;
			try
			{
				ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(itemId);
				if (val != null)
				{
					FieldInfo field = ((object)val).GetType().GetField("iconTagString", BindingFlags.Instance | BindingFlags.Public);
					if (field != null)
					{
						string text2 = field.GetValue(val) as string;
						if (!string.IsNullOrEmpty(text2))
						{
							text = text2;
						}
					}
				}
			}
			catch (Exception ex)
			{
				DarkFogWorkshop.Log.LogInfo((object)$"[提示] 取物品 {itemId} 图标标签失败(将用纯名字):{ex.GetType().Name}");
			}
			iconTagCache[itemId] = text;
			return text;
		}

		private static string ValueText(double value)
		{
			if (!(value > 0.0))
			{
				return "—";
			}
			return ((long)value).ToString();
		}

		internal static string DescribeTableMetrics()
		{
			return string.Empty;
		}

		internal static string StripIconTags(string text)
		{
			if (string.IsNullOrEmpty(text) || text.IndexOf('\\') < 0)
			{
				return text ?? string.Empty;
			}
			StringBuilder stringBuilder = new StringBuilder(text.Length);
			for (int i = 0; i < text.Length; i++)
			{
				if (text[i] == '\\')
				{
					int num = text.IndexOf(';', i + 1);
					if (num > i)
					{
						i = num;
						continue;
					}
				}
				stringBuilder.Append(text[i]);
			}
			return stringBuilder.ToString();
		}

		private static int DisplayWidth(string text)
		{
			int num = 0;
			for (int i = 0; i < text.Length; i++)
			{
				num += ((text[i] <= '\u2000') ? 1 : 2);
			}
			return num;
		}
	}
	internal static class OrbitalRingCompat
	{
		[HarmonyPatch(typeof(UIStationWindow), "OnStationIdChange")]
		internal static class OnStationIdChangeGuard
		{
			internal static Exception Finalizer(Exception __exception, UIStationWindow __instance)
			{
				return OrbitalRingCompat.Finalizer(__exception, __instance);
			}
		}

		[HarmonyPatch(typeof(UIStationWindow), "_OnUpdate")]
		internal static class OnUpdateGuard
		{
			internal static Exception Finalizer(Exception __exception, UIStationWindow __instance)
			{
				return OrbitalRingCompat.Finalizer(__exception, __instance);
			}
		}

		[HarmonyPatch(typeof(UIStationWindow), "_OnOpen")]
		internal static class OnOpenGuard
		{
			internal static Exception Finalizer(Exception __exception, UIStationWindow __instance)
			{
				return OrbitalRingCompat.Finalizer(__exception, __instance);
			}
		}

		private static Exception Finalizer(Exception __exception, UIStationWindow __instance)
		{
			if (__exception == null)
			{
				return null;
			}
			if (!(__exception is IndexOutOfRangeException) && !(__exception is ArgumentOutOfRangeException))
			{
				return __exception;
			}
			string stackTrace = __exception.StackTrace;
			if (string.IsNullOrEmpty(stackTrace) || stackTrace.IndexOf("ProjectOrbitalRing", StringComparison.OrdinalIgnoreCase) < 0)
			{
				return __exception;
			}
			if ((Object)(object)__instance != (Object)null)
			{
				__instance.event_lock = false;
			}
			if (DarkFogWorkshop.Log != null)
			{
				DarkFogWorkshop.Log.LogWarning((object)"[兼容] 已拦截 OrbitalRing 共享仓储 UI 的数组越界(其 UI 固定 5 槽),窗口继续运行。");
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(UISimpleGeneralTip))]
	public static class UISimpleGeneralTipPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("SetTip")]
		public static void SetTip_Postfix(UISimpleGeneralTip __instance)
		{
			UIStationWindowPatch.ApplyTipLineSpacing(__instance);
		}
	}
	[HarmonyPatch(typeof(UIStationWindow))]
	public static class UIStationWindowPatch
	{
		private sealed class WorkshopUiHost : MonoBehaviour
		{
			public UIStationWindow window;
		}

		private const float HelpRight = 48f;

		private const float HelpTop = 57f;

		private const float HelpSize = 24f;

		private const long TipRefreshTicks = 30L;

		private const int TipWidth = 465;

		private const float MetadataGapX = 35f;

		private const float MetadataNudgeY = 0f;

		private static UIStationWindow _window;

		private static UIButton _helpButton;

		private static GameObject _metadataBar;

		private static UIButton _metadataButton;

		private static Image _metadataCheck;

		private static Text _metadataLabel;

		private static StationComponent _metadataStation;

		private static WorkshopUiHost _host;

		private static StationComponent _lastTipStation;

		private static long _lastTipTick;

		private static int _mainThreadId;

		private const float TipLineSpacing = 1.5f;

		private static readonly float[] TipTableColWidths = new float[2] { 140f, 80f };

		private static readonly float[] TipTableRowHeights = new float[14]
		{
			24f, 24f, 24f, 24f, 24f, 24f, 24f, 24f, 24f, 24f,
			24f, 24f, 24f, 24f
		};

		private static readonly HorzAlignment[] TipTableColAlignments = (HorzAlignment[])(object)new HorzAlignment[2]
		{
			default(HorzAlignment),
			(HorzAlignment)2
		};

		internal static void CaptureMainThread()
		{
			_mainThreadId = Thread.CurrentThread.ManagedThreadId;
		}

		internal static bool IsMainThread()
		{
			if (_mainThreadId != 0)
			{
				return Thread.CurrentThread.ManagedThreadId == _mainThreadId;
			}
			return true;
		}

		internal static void ApplyTipLineSpacing(UISimpleGeneralTip tip)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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_00c1: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)tip == (Object)null || (Object)(object)tip.subTextComp == (Object)null)
			{
				return;
			}
			try
			{
				Text subTextComp = tip.subTextComp;
				subTextComp.tableColWidths = TipTableColWidths;
				subTextComp.tableRowHeights = TipTableRowHeights;
				subTextComp.tableColAlignments = TipTableColAlignments;
				subTextComp.tableRowAlignments = (VertAlignment[])(object)new VertAlignment[1] { (VertAlignment)3 };
				subTextComp.tableCellPadding = new Vector4(0f, 0f, 0f, 0f);
				subTextComp.tableLineColor = new Color(0f, 0f, 0f, 0f);
				subTextComp.tableLineTint = false;
				subTextComp.latinCharSpacing = 0f;
				subTextComp.latinCharStretch = new Vector2(1f, 1f);
				subTextComp.wideCharStretch = new Vector2(1f, 1f);
				subTextComp.lineBreakSmartAdjust = false;
			}
			catch (Exception ex)
			{
				DarkFogWorkshop.Log.LogWarning((object)("[提示] 设置提示框属性失败:" + ex.Message));
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("_OnCreate")]
		public static void OnCreate_Postfix(UIStationWindow __instance)
		{
			_window = __instance;
			EnsureWidget(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("_OnOpen")]
		public static void OnOpen_Postfix(UIStationWindow __instance)
		{
			_window = __instance;
			EnsureWidget(__instance);
			Refresh(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("_OnClose")]
		public static void OnClose_Postfix(UIStationWindow __instance)
		{
			Hide();
		}

		[HarmonyPostfix]
		[HarmonyPatch("OnStationIdChange")]
		public static void OnStationIdChange_Postfix(UIStationWindow __instance)
		{
			_window = __instance;
			EnsureWidget(__instance);
			Refresh(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("_OnUpdate")]
		public static void OnUpdate_Postfix(UIStationWindow __instance)
		{
			EnsureWidget(__instance);
			Refresh(__instance);
		}

		private static StationComponent GetStation(UIStationWindow window)
		{
			if ((Object)(object)window == (Object)null)
			{
				return null;
			}
			PlanetTransport val = window.transport ?? ((window.factory != null) ? window.factory.transport : null);
			int stationId = window.stationId;
			if (val == null || stationId <= 0 || stationId >= val.stationCursor)
			{
				return null;
			}
			StationComponent val2 = val.stationPool[stationId];
			if (val2 == null || val2.id != stationId)
			{
				return null;
			}
			return val2;
		}

		private static void EnsureWidget(UIStationWindow window)
		{
			if ((Object)(object)window == (Object)null || (Object)(object)window.windowTrans == (Object)null)
			{
				return;
			}
			if ((Object)(object)_helpButton == (Object)null)
			{
				CreateWidget(window);
			}
			EnsureMetadataBar(window);
			if (!((Object)(object)_helpButton == (Object)null))
			{
				if ((Object)(object)((Component)_helpButton).transform.parent != (Object)(object)window.windowTrans)
				{
					((Component)_helpButton).transform.SetParent((Transform)(object)window.windowTrans, false);
					((Component)_helpButton).transform.SetAsLastSibling();
					LayoutHelpButton();
				}
				if ((Object)(object)_host == (Object)null)
				{
					_host = ((Component)_helpButton).gameObject.AddComponent<WorkshopUiHost>();
				}
				_host.window = window;
			}
		}

		private static void EnsureMetadataBar(UIStationWindow window)
		{
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)window == (Object)null || (Object)(object)window.windowTrans == (Object)null || (Object)(object)window.warperNecessaryGroup == (Object)null)
			{
				return;
			}
			if ((Object)(object)_metadataBar != (Object)null)
			{
				if ((Object)(object)_metadataBar.transform.parent != (Object)(object)window.windowTrans)
				{
					_metadataBar.transform.SetParent((Transform)(object)window.windowTrans, false);
					LayoutMetadataBar(window);
				}
				return;
			}
			_metadataBar = Object.Instantiate<GameObject>(((Component)window.warperNecessaryGroup).gameObject, (Transform)(object)window.windowTrans);
			((Object)_metadataBar).name = "dark-fog-workshop-metadata-exchange";
			_metadataButton = _metadataBar.GetComponentInChildren<UIButton>(true);
			UIButton[] componentsInChildren = _metadataBar.GetComponentsInChildren<UIButton>(true);
			foreach (UIButton obj in componentsInChildren)
			{
				obj.tipTitleFormatString = string.Empty;
				obj.tipTextFormatString = string.Empty;
				obj.tips.tipTitle = "黑雾工坊 DarkFogWorkshop";
				obj.tips.tipText = DarkFogWorkshop.Tr("勾选后,第 1 槽位将开始自动兑换元数据,将对应的科学矩阵直接放入该槽位。取消勾选即可停止兑换。补充说明:元数据兑换速度可在配置文件中修改。", "When checked, slot 1 automatically exchanges metadata for its selected science matrix and deposits it directly into the slot. Uncheck to stop. Note: the exchange rate can be changed in the config file.");
				obj.tips.itemId = 0;
				obj.tips.type = (ItemTipType)2;
				obj.UpdateTip();
			}
			if ((Object)(object)_metadataButton != (Object)null)
			{
				_metadataButton.onClick -= OnMetadataExchangeClick;
				_metadataButton.onClick += OnMetadataExchangeClick;
			}
			string text = RelativePath((Transform)(object)window.warperNecessaryGroup, ((Object)(object)window.warperNecessaryCheck != (Object)null) ? ((Component)window.warperNecessaryCheck).transform : null);
			Transform val = (string.IsNullOrEmpty(text) ? null : _metadataBar.transform.Find(text));
			_metadataCheck = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<Image>() : _metadataBar.GetComponentInChildren<Image>(true));
			Text[] componentsInChildren2 = _metadataBar.GetComponentsInChildren<Text>(true);
			if (componentsInChildren2 != null && componentsInChildren2.Length != 0)
			{
				_metadataLabel = componentsInChildren2[0];
				Localizer component = ((Component)_metadataLabel).GetComponent<Localizer>();
				if ((Object)(object)component != (Object)null)
				{
					component.stringKey = null;
					component.translation = null;
				}
				_metadataLabel.text = "元数据兑换科学矩阵";
			}
			LayoutMetadataBar(window);
		}

		private static void LayoutMetadataBar(UIStationWindow window)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: 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_0142: 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_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: 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_00cf: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: 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_0115: 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)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: 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_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_0285: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_metadataBar == (Object)null || (Object)(object)window == (Object)null || (Object)(object)window.windowTrans == (Object)null)
			{
				return;
			}
			Transform transform = _metadataBar.transform;
			RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			if (!((Object)(object)val == (Object)null))
			{
				val.anchorMin = new Vector2(0f, 1f);
				val.anchorMax = new Vector2(0f, 1f);
				val.pivot = new Vector2(0f, 1f);
				((Transform)val).localScale = Vector3.one;
				RectTransform windowTrans = window.windowTrans;
				float num = -69f;
				RectTransform val2 = (RectTransform)(((Object)(object)window.nameInput != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
				float num2 = 320f;
				Rect rect;
				if ((Object)(object)val2 != (Object)null)
				{
					rect = val2.rect;
					float num3 = ((Rect)(ref rect)).width * (1f - val2.pivot.x);
					rect = val2.rect;
					Vector3 val3 = ((Transform)val2).TransformPoint(new Vector3(num3, ((Rect)(ref rect)).height * (0.5f - val2.pivot.y), 0f));
					num2 = ((Transform)windowTrans).InverseTransformPoint(val3).x + 35f;
				}
				rect = windowTrans.rect;
				float num4 = (0f - ((Rect)(ref rect)).width) * windowTrans.pivot.x;
				rect = windowTrans.rect;
				float num5 = ((Rect)(ref rect)).height * (1f - windowTrans.pivot.y);
				rect = windowTrans.rect;
				float num6 = ((Rect)(ref rect)).width * (1f - windowTrans.pivot.x) - 20f;
				rect = val.rect;
				float num7 = num6 - ((Rect)(ref rect)).width;
				if (num2 > num7)
				{
					num2 = num7;
				}
				rect = val.rect;
				float num8;
				if (!(((Rect)(ref rect)).height > 1f))
				{
					num8 = 26f;
				}
				else
				{
					rect = val.rect;
					num8 = ((Rect)(ref rect)).height;
				}
				float num9 = num8;
				val.anchoredPosition3D = new Vector3(num2 - num4, num - num9 * 0.5f - num5, 0f);
				RectTransform val4 = (RectTransform)(((Object)(object)_metadataCheck != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
				if ((Object)(object)val4 != (Object)null)
				{
					rect = val4.rect;
					float num10 = ((Rect)(ref rect)).width * (0.5f - val4.pivot.x);
					rect = val4.rect;
					Vector3 val5 = ((Transform)val4).TransformPoint(new Vector3(num10, ((Rect)(ref rect)).height * (0.5f - val4.pivot.y), 0f));
					float y = ((Transform)windowTrans).InverseTransformPoint(val5).y;
					val.anchoredPosition3D += new Vector3(0f, num - y, 0f);
				}
			}
		}

		private static string RelativePath(Transform root, Transform target)
		{
			if ((Object)(object)root == (Object)null || (Object)(object)target == (Object)null || (Object)(object)target == (Object)(object)root)
			{
				return string.Empty;
			}
			StringBuilder stringBuilder = new StringBuilder(((Object)target).name);
			Transform parent = target.parent;
			while ((Object)(object)parent != (Object)null && (Object)(object)parent != (Object)(object)root)
			{
				stringBuilder.Insert(0, ((Object)parent).name + "/");
				parent = parent.parent;
			}
			if (!((Object)(object)parent == (Object)(object)root))
			{
				return string.Empty;
			}
			return stringBuilder.ToString();
		}

		private static void OnMetadataExchangeClick(int obj)
		{
			StationComponent metadataStation = _metadataStation;
			if (metadataStation != null && DarkFogWorkshopPatch.IsMetadataExchangeEligible(metadataStation))
			{
				DarkFogWorkshopPatch.SetMetadataExchangeEnabled(metadataStation, !DarkFogWorkshopPatch.IsMetadataExchangeEnabled(metadataStation));
				if ((Object)(object)_window != (Object)null)
				{
					Refresh(_window);
				}
			}
		}

		private static void RefreshMetadataWidget(UIStationWindow window, StationComponent station, bool windowActive)
		{
			if ((Object)(object)_metadataBar == (Object)null)
			{
				return;
			}
			bool flag = station != null && DarkFogWorkshopPatch.IsMetadataExchangeEligible(station);
			if (!flag && station != null && DarkFogWorkshopPatch.IsMetadataExchangeEnabled(station))
			{
				DarkFogWorkshopPatch.SetMetadataExchangeEnabled(station, enabled: false);
			}
			bool flag2 = windowActive && flag;
			if (_metadataBar.activeSelf != flag2)
			{
				_metadataBar.SetActive(flag2);
			}
			if (flag2)
			{
				LayoutMetadataBar(window);
				if ((Object)(object)_metadataCheck != (Object)null)
				{
					((Behaviour)_metadataCheck).enabled = DarkFogWorkshopPatch.IsMetadataExchangeEnabled(station);
				}
			}
			_metadataStation = (flag ? station : null);
		}

		private static void CreateWidget(UIStationWindow window)
		{
			Font font = (((Object)(object)window.titleText != (Object)null) ? window.titleText.font : Resources.GetBuiltinResource<Font>("Arial.ttf"));
			_helpButton = CreateHelpButton(window, font);
			LayoutHelpButton();
		}

		private static UIButton CreateHelpButton(UIStationWindow window, Font font)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			//IL_00cc: 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_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = FindNativeTipButton();
			if ((Object)(object)val != (Object)null)
			{
				GameObject val2 = Object.Instantiate<GameObject>(val);
				((Object)val2).name = "dark-fog-workshop-help";
				UIButton component = val2.GetComponent<UIButton>();
				if ((Object)(object)component != (Object)null)
				{
					TipSettings tips = component.tips;
					ResetButton(component);
					tips.topLevel = true;
					tips.type = (ItemTipType)2;
					tips.delay = 0.2f;
					component.tips = tips;
					PrepareLabel(val2, font);
					val2.transform.SetParent((Transform)(object)window.windowTrans, false);
					LayoutHelpButton(component);
					val2.SetActive(true);
					return component;
				}
				Object.Destroy((Object)(object)val2);
			}
			GameObject val3 = new GameObject("dark-fog-workshop-help");
			val3.transform.SetParent((Transform)(object)window.windowTrans, false);
			Image obj = val3.AddComponent<Image>();
			((Graphic)obj).color = new Color(0.22f, 0.5f, 0.6f, 0.9f);
			((Graphic)obj).raycastTarget = true;
			UIButton obj2 = val3.AddComponent<UIButton>();
			obj2.button = null;
			obj2.tips = new TipSettings
			{
				topLevel = true,
				type = (ItemTipType)2,
				delay = 0.2f
			};
			PrepareLabel(val3, font);
			return obj2;
		}

		private static GameObject FindNativeTipButton()
		{
			try
			{
				UIGalaxySelect val = (((Object)(object)UIRoot.instance != (Object)null) ? UIRoot.instance.galaxySelect : null);
				if ((Object)(object)val == (Object)null)
				{
					return null;
				}
				if ((Object)(object)val.sandboxToggle != (Object)null)
				{
					Transform parent = ((Component)val.sandboxToggle).gameObject.transform.parent;
					if ((Object)(object)parent != (Object)null)
					{
						Transform val2 = parent.Find("tip-button");
						if ((Object)(object)val2 != (Object)null)
						{
							return ((Component)val2).gameObject;
						}
					}
				}
				if ((Object)(object)val.darkFogDetailBtn != (Object)null)
				{
					return ((Component)val.darkFogDetailBtn).gameObject;
				}
			}
			catch (Exception ex)
			{
				DarkFogWorkshop.Log.LogWarning((object)("找不到原生提示控件模板,改用自绘控件:" + ex.Message));
			}
			return null;
		}

		private static void PrepareLabel(GameObject root, Font font)
		{
			//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_0070: 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_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: 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)
			//IL_00d5: 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)
			Text componentInChildren = root.GetComponentInChildren<Text>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				Localizer component = ((Component)componentInChildren).GetComponent<Localizer>();
				if ((Object)(object)component != (Object)null)
				{
					component.stringKey = null;
					component.translation = null;
				}
				componentInChildren.text = "?";
				componentInChildren.fontStyle = (FontStyle)0;
				((Graphic)componentInChildren).color = Color.white;
				((Graphic)componentInChildren).raycastTarget = false;
			}
			else
			{
				GameObject val = new GameObject("Text");
				val.transform.SetParent(root.transform, false);
				Text obj = val.AddComponent<Text>();
				obj.font = font;
				obj.text = "?";
				obj.fontSize = 15;
				obj.fontStyle = (FontStyle)0;
				obj.alignment = (TextAnchor)4;
				((Graphic)obj).color = Color.white;
				((Graphic)obj).raycastTarget = false;
				RectTransform component2 = val.GetComponent<RectTransform>();
				component2.anchorMin = Vector2.zero;
				component2.anchorMax = Vector2.one;
				component2.offsetMin = Vector2.zero;
				component2.offsetMax = Vector2.zero;
			}
		}

		private static void ResetButton(UIButton button)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			button.Init();
			((Behaviour)button).enabled = true;
			button.highlighted = false;
			button.updating = true;
			button.data = 0;
			button.tips = default(TipSettings);
			if ((Object)(object)button.button != (Object)null)
			{
				((UnityEventBase)button.button.onClick).RemoveAllListeners();
				((Selectable)button.button).interactable = false;
			}
			button.onClick -= OnHelpButtonClicked;
			button.MReset();
		}

		private static void OnHelpButtonClicked(int obj)
		{
		}

		private static RectTransform AnchorTopRight(Component cmp, float right, float top)
		{
			//IL_0022: 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_004c: 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)
			Transform transform = cmp.transform;
			RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			val.anchorMin = new Vector2(1f, 1f);
			val.anchorMax = new Vector2(1f, 1f);
			val.pivot = new Vector2(1f, 1f);
			val.anchoredPosition3D = new Vector3(0f - right, 0f - top, 0f);
			return val;
		}

		private static void LayoutHelpButton()
		{
			LayoutHelpButton(_helpButton);
		}

		private static void LayoutHelpButton(UIButton button)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)button == (Object)null))
			{
				RectTransform val = AnchorTopRight((Component)(object)button, 48f, 57f);
				if ((Object)(object)val != (Object)null)
				{
					val.sizeDelta = new Vector2(24f, 24f);
				}
			}
		}

		private static void Hide()
		{
			if ((Object)(object)_helpButton != (Object)null && ((Component)_helpButton).gameObject.activeSelf)
			{
				((Component)_helpButton).gameObject.SetActive(false);
			}
			if ((Object)(object)_metadataBar != (Object)null && _metadataBar.activeSelf)
			{
				_metadataBar.SetActive(false);
			}
		}

		private static void Refresh(UIStationWindow window)
		{
			if (!((Object)(object)_helpButton == (Object)null))
			{
				StationComponent station = GetStation(window);
				RefreshMetadataWidget(window, station, ((ManualBehaviour)window).active);
				bool flag = ((ManualBehaviour)window).active && station != null && (DarkFogWorkshopPatch.IsWorkshopShape(station) || (DarkFogWorkshopPatch.IsMetadataExchangeEligible(station) && DarkFogWorkshopPatch.IsMetadataExchangeEnabled(station)));
				if (((Component)_helpButton).gameObject.activeSelf != flag)
				{
					((Component)_helpButton).gameObject.SetActive(flag);
				}
				if (flag)
				{
					UpdateHelpTip(station);
				}
			}
		}

		private static void UpdateHelpTip(StationComponent station)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			long gameTick = GameMain.gameTick;
			if (gameTick - _lastTipTick >= 30 || _lastTipStation != station)
			{
				_lastTipTick = gameTick;
				_lastTipStation = station;
				string text = DarkFogWorkshopPatch.DescribeDetail(station);
				if (!(_helpButton.tips.tipTitle == "黑雾工坊 DarkFogWorkshop") || !(_helpButton.tips.tipText == text))
				{
					_helpButton.tips.tipTitle = "黑雾工坊 DarkFogWorkshop";
					_helpButton.tips.tipText = text;
					_helpButton.tips.type = (ItemTipType)2;
					_helpButton.tips.topLevel = true;
					_helpButton.tips.width = 465;
					_helpButton.UpdateTip();
				}
			}
		}
	}
}