Decompiled source of DSPShieldPlanner v0.7.0

plugins/DSP.ShieldPlanner.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CommonAPI;
using CommonAPI.Systems;
using CommonAPI.Systems.ModLocalization;
using DSP.ShieldPlanner.Diagnostics;
using DSP.ShieldPlanner.GameData;
using DSP.ShieldPlanner.Placement;
using DSP.ShieldPlanner.Solver;
using DSP.ShieldPlanner.UI;
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("DSP.ShieldPlanner")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+76a32125039c0a53a32885b22dcdbb6038068fb0")]
[assembly: AssemblyProduct("DSP.ShieldPlanner")]
[assembly: AssemblyTitle("DSP.ShieldPlanner")]
[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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DSP.ShieldPlanner
{
	internal static class GameLifecycleHooks
	{
		private static void SafeRun(string hookName, Action action)
		{
			try
			{
				action();
			}
			catch (Exception arg)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)$"[ShieldPlanner] 生命周期钩子 {hookName} 异常: {arg}");
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameMain), "End")]
		private static void GameMain_End_Postfix()
		{
			SafeRun("GameMain.End", delegate
			{
				Plugin.OnGameSessionEnded("对局结束");
			});
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(GameMain), "OnDestroy")]
		private static void GameMain_OnDestroy_Prefix()
		{
			SafeRun("GameMain.OnDestroy", delegate
			{
				Plugin.OnGameSessionEnded("GameMain 销毁");
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIRoot), "OnGameLoadStart")]
		private static void UIRoot_OnGameLoadStart_Postfix()
		{
			SafeRun("UIRoot.OnGameLoadStart", delegate
			{
				Plugin.OnGameSessionEnded("开始加载存档");
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIRoot), "OnGameLoadFailed")]
		private static void UIRoot_OnGameLoadFailed_Postfix()
		{
			SafeRun("UIRoot.OnGameLoadFailed", delegate
			{
				Plugin.OnGameSessionEnded("存档加载失败");
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameMain), "Begin")]
		private static void GameMain_Begin_Postfix()
		{
			if (!DSPGame.IsMenuDemo && !((Object)(object)GameMain.instance == (Object)null) && !GameMain.instance.isMenuDemo)
			{
				SafeRun("GameMain.Begin", Plugin.OnGameSessionBegan);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameData), "LeavePlanet")]
		private static void GameData_LeavePlanet_Postfix()
		{
			if (!DSPGame.IsMenuDemo && Plugin.IsInPlayableGame())
			{
				SafeRun("GameData.LeavePlanet", Plugin.OnLeavePlanet);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameData), "ArrivePlanet", new Type[] { typeof(PlanetData) })]
		private static void GameData_ArrivePlanet_Postfix(PlanetData planet)
		{
			if (!DSPGame.IsMenuDemo && Plugin.IsInPlayableGame())
			{
				SafeRun("GameData.ArrivePlanet", delegate
				{
					Plugin.OnArrivePlanet(planet);
				});
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BuildTool_BlueprintPaste), "_OnClose")]
		private static void BuildTool_BlueprintPaste_OnClose_Postfix()
		{
			SafeRun("BuildTool_BlueprintPaste._OnClose", Plugin.OnBlueprintPasteClosed);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIGame), "ShutAllFunctionWindow")]
		private static void UIGame_ShutAllFunctionWindow_Postfix()
		{
			SafeRun("UIGame.ShutAllFunctionWindow", ShieldPlannerUI.Close);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIGame), "BeforeEnterFullScreenUI")]
		private static void UIGame_BeforeEnterFullScreenUI_Postfix()
		{
			SafeRun("UIGame.BeforeEnterFullScreenUI", Plugin.OnEnterFullScreenUI);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIGame), "OnEnterToMilkyWay")]
		private static void UIGame_OnEnterToMilkyWay_Postfix()
		{
			SafeRun("UIGame.OnEnterToMilkyWay", Plugin.OnEnterMilkyWay);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIEscMenu), "_OnOpen")]
		private static void UIEscMenu_OnOpen_Postfix()
		{
			SafeRun("UIEscMenu._OnOpen", ShieldPlannerUI.Close);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "Kill")]
		private static void Player_Kill_Postfix(Player __instance)
		{
			if (!DSPGame.IsMenuDemo && GameMain.mainPlayer != null && __instance == GameMain.mainPlayer)
			{
				SafeRun("Player.Kill", Plugin.OnPlayerKilled);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIRoot), "_OnDestroy")]
		private static void UIRoot_OnDestroy_Postfix()
		{
			SafeRun("UIRoot._OnDestroy", ShieldPlannerUI.OnUIRootDestroy);
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[CommonAPISubmoduleDependency(new string[] { "CustomKeyBindSystem", "LocalizationModule" })]
	[BepInPlugin("dsp.shieldplanner", "DSP ShieldPlanner", "0.7.0")]
	public class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log = null;

		public static Plugin Instance = null;

		private Harmony? _harmony;

		private static PressKeyBind? _togglePanelKey;

		private Task<PlanOutcome?>? _task;

		private CancellationTokenSource? _taskCts;

		private PlanetData? _taskPlanet;

		private bool _taskPlace;

		private bool _taskAsBlueprint;

		private List<SVec3>? _taskExisting;

		private PlanSnapshot? _taskSnap;

		private bool _pausedLogged;

		private List<SVec3>? _pendingBlueprint;

		private PlanetData? _pendingPlanet;

		private List<SVec3>? _pendingExisting;

		private float _configSaveAt;

		private double _lastFill = -1.0;

		private int _lastCount = -1;

		private double _taskStartRealtime;

		private LastSolveRecord? _lastSolve;

		public static double LastSolveAlpha = -1.0;

		private void Awake()
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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_0089: 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_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			PluginConfig.Init(((BaseUnityPlugin)this).Config);
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			LocalizationModule.RegisterTranslation("KEYToggleShieldPlannerPanel", "[ShieldPlanner] Toggle ShieldPlanner Panel", "[ShieldPlanner] 打开/关闭护盾规划面板", "[ShieldPlanner] Toggle ShieldPlanner Panel");
			_togglePanelKey = (CustomKeyBindSystem.HasKeyBind("ToggleShieldPlannerPanel") ? CustomKeyBindSystem.GetKeyBind("ToggleShieldPlannerPanel") : CustomKeyBindSystem.RegisterKeyBindWithReturn<PressKeyBind>(new BuiltinKey
			{
				name = "ToggleShieldPlannerPanel",
				key = new CombineKey(289, (byte)3, (ECombineKeyAction)0, false),
				conflictGroup = 2821,
				canOverride = true
			}));
			Log.LogInfo((object)$"[ShieldPlanner] 已通过 CommonAPI 注册面板快捷键:id={_togglePanelKey.defaultBind.id},默认={_togglePanelKey.defaultBind.key}");
			_harmony = new Harmony("dsp.shieldplanner");
			_harmony.PatchAll(typeof(GameLifecycleHooks));
			Log.LogInfo((object)"[DSP ShieldPlanner] 加载成功 v0.7.0(可在「设置 → 按键」自定义面板快捷键)");
		}

		private void OnDestroy()
		{
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			_harmony = null;
			_togglePanelKey = null;
			CancelActiveTask("mod 卸载", showBanner: false);
			ClearPendingBlueprint(hideBanner: false);
			ResetDiagnosticCache();
			ShieldPlannerUI.OnModDestroy();
			Log.LogInfo((object)"[ShieldPlanner] mod 卸载:未完成的结果已丢弃");
		}

		private static bool IsTogglePanelKeyDown()
		{
			if (_togglePanelKey != null)
			{
				return _togglePanelKey.keyValue;
			}
			return false;
		}

		internal static bool IsInPlayableGame()
		{
			if (GameMain.isRunning && !GameMain.isEnded && !GameMain.isLoading && !DSPGame.IsMenuDemo && (!((Object)(object)UIRoot.instance != (Object)null) || !((Object)(object)UIRoot.instance.uiMilkyWay != (Object)null) || !((ManualBehaviour)UIRoot.instance.uiMilkyWay).active) && (Object)(object)GameMain.instance != (Object)null && !GameMain.instance.isMenuDemo && GameMain.data != null)
			{
				return GameMain.mainPlayer != null;
			}
			return false;
		}

		internal static bool IsInBlockingUI()
		{
			UIGame val = UIRoot.instance?.uiGame;
			if ((Object)(object)val == (Object)null)
			{
				return true;
			}
			if ((!((Object)(object)val.escMenu != (Object)null) || !((ManualBehaviour)val.escMenu).active) && (!((Object)(object)val.starmap != (Object)null) || !((ManualBehaviour)val.starmap).active) && (!((Object)(object)val.techTree != (Object)null) || !((ManualBehaviour)val.techTree).active) && (!((Object)(object)val.dysonEditor != (Object)null) || !((ManualBehaviour)val.dysonEditor).active) && (!((Object)(object)val.dashboard != (Object)null) || !((ManualBehaviour)val.dashboard).active) && (!((Object)(object)val.zScreen != (Object)null) || !((ManualBehaviour)val.zScreen).active))
			{
				return VFInput.inFullscreenGUI;
			}
			return true;
		}

		private bool CancelActiveTask(string reason, bool showBanner, string? bannerText = null)
		{
			if (_task == null && _taskCts == null)
			{
				return false;
			}
			CancellationTokenSource taskCts = _taskCts;
			_taskCts = null;
			_task = null;
			_taskPlanet = null;
			_taskExisting = null;
			_taskSnap = null;
			_pausedLogged = false;
			try
			{
				taskCts?.Cancel();
			}
			catch
			{
			}
			ShieldPlannerUI.SetBusy(busy: false);
			ShieldPlannerUI.HideBannerIf(BannerTag.Solving);
			Log.LogInfo((object)("[ShieldPlanner] 已终止后台求解:" + reason));
			if (showBanner && IsInPlayableGame() && !string.IsNullOrEmpty(bannerText))
			{
				ShieldPlannerUI.ShowBanner(bannerText, 4f);
			}
			return true;
		}

		private bool ClearPendingBlueprint(bool hideBanner)
		{
			if (_pendingBlueprint == null)
			{
				return false;
			}
			_pendingBlueprint = null;
			_pendingPlanet = null;
			_pendingExisting = null;
			if (hideBanner)
			{
				ShieldPlannerUI.HideBannerIf(BannerTag.PendingBlueprint);
			}
			ShieldPlannerUI.SetBusy(busy: false);
			return true;
		}

		private void ResetDiagnosticCache()
		{
			_lastFill = -1.0;
			_lastCount = -1;
			_lastSolve = null;
			LastSolveAlpha = -1.0;
		}

		internal static void OnGameSessionEnded(string reason)
		{
			Plugin instance = Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				instance.CancelActiveTask(reason, showBanner: false);
				instance.ClearPendingBlueprint(hideBanner: false);
				instance.ResetDiagnosticCache();
				ShieldPlannerUI.ResetSessionUI();
			}
		}

		internal static void OnGameSessionBegan()
		{
			Plugin instance = Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				instance.CancelActiveTask("进入新对局清理", showBanner: false);
				instance.ClearPendingBlueprint(hideBanner: false);
				instance.ResetDiagnosticCache();
				ShieldPlannerUI.ResetSessionUI();
				ShieldPlannerUI.OnPlanetChanged();
			}
		}

		internal static void OnLeavePlanet()
		{
			Plugin instance = Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				bool flag = instance.CancelActiveTask("离开目标星球", showBanner: false);
				bool flag2 = instance.ClearPendingBlueprint(hideBanner: false);
				instance.ResetDiagnosticCache();
				ShieldPlannerUI.HideBanner();
				ShieldPlannerUI.ResetStatus();
				ShieldPlannerUI.OnPlanetChanged();
				if (flag && IsInPlayableGame())
				{
					ShieldPlannerUI.ShowBanner("已离开目标星球,护盾计算已取消", 4f);
				}
				else if (flag2 && IsInPlayableGame())
				{
					ShieldPlannerUI.ShowBanner("已离开目标星球,待打开的蓝图已取消", 4f);
				}
			}
		}

		internal static void OnArrivePlanet(PlanetData? planet)
		{
			Plugin instance = Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				if (instance._task != null && instance._taskPlanet != planet)
				{
					instance.CancelActiveTask("切换至其他星球", showBanner: false);
				}
				if (instance._pendingBlueprint != null && instance._pendingPlanet != planet)
				{
					instance.ClearPendingBlueprint(hideBanner: true);
				}
				instance.ResetDiagnosticCache();
				ShieldPlannerUI.HideBanner();
				ShieldPlannerUI.ResetStatus();
				ShieldPlannerUI.OnPlanetChanged();
			}
		}

		internal static void OnBlueprintPasteClosed()
		{
			ShieldPlannerUI.HideBannerIf(BannerTag.BlueprintPaste);
		}

		internal static void OnEnterFullScreenUI()
		{
			ShieldPlannerUI.Close();
			ShieldPlannerUI.HideBannerIf(BannerTag.BlueprintPaste);
		}

		internal static void OnEnterMilkyWay()
		{
			ShieldPlannerUI.Close();
			ShieldPlannerUI.HideBanner();
		}

		internal static void OnPlayerKilled()
		{
			Plugin instance = Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				ShieldPlannerUI.Close();
				bool flag = instance.CancelActiveTask("机甲已被摧毁", showBanner: false);
				bool flag2 = instance.ClearPendingBlueprint(hideBanner: false);
				ShieldPlannerUI.HideBanner();
				if (flag || flag2)
				{
					ShieldPlannerUI.ResetStatus();
				}
			}
		}

		private void Update()
		{
			//IL_01f4: 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_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: 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_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			if (Time.time >= _configSaveAt)
			{
				_configSaveAt = Time.time + 2f;
				((BaseUnityPlugin)this).Config.Save();
			}
			if (!IsInPlayableGame())
			{
				CancelActiveTask("已离开对局", showBanner: false);
				ClearPendingBlueprint(hideBanner: true);
				ShieldPlannerUI.Close();
				ShieldPlannerUI.HideBanner();
				return;
			}
			ShieldPlannerUI.Tick();
			KeyboardShortcut value;
			if (_task != null)
			{
				if (GameMain.localPlanet != _taskPlanet || !GameMain.mainPlayer.isAlive)
				{
					if (CancelActiveTask("目标星球变化或机甲已摧毁", showBanner: false))
					{
						ShieldPlannerUI.ResetStatus();
					}
					return;
				}
				if (_task.IsCompleted)
				{
					if (GameMain.isPaused || (_taskAsBlueprint && IsInBlockingUI()))
					{
						if (!_pausedLogged)
						{
							_pausedLogged = true;
							Log.LogInfo((object)"[ShieldPlanner] 游戏暂停或全屏界面打开中,求解结果等待恢复后落地");
						}
					}
					else
					{
						_pausedLogged = false;
						LandResult();
					}
					return;
				}
				if (!VFInput.inputing && !IsInBlockingUI())
				{
					if (IsTogglePanelKeyDown())
					{
						ShieldPlannerUI.Toggle();
						return;
					}
					value = PluginConfig.HotkeyDiagnostic.Value;
					if (((KeyboardShortcut)(ref value)).IsDown())
					{
						Log.LogInfo((object)"[ShieldPlanner] 求解中,诊断热键暂不可用(完成后即可)");
					}
				}
				ShieldPlannerUI.SetBusy(busy: true);
				return;
			}
			if (_pendingBlueprint != null)
			{
				if (_pendingPlanet == null || GameMain.localPlanet != _pendingPlanet || !GameMain.mainPlayer.isAlive)
				{
					ClearPendingBlueprint(hideBanner: true);
					ShieldPlannerUI.ResetStatus();
				}
				else
				{
					if (PlayerInBuildMode())
					{
						ShieldPlannerUI.SetBusy(busy: true);
						return;
					}
					if (GameMain.isPaused || IsInBlockingUI())
					{
						ShieldPlannerUI.SetBusy(busy: true);
						return;
					}
					List<SVec3> pendingBlueprint = _pendingBlueprint;
					PlanetData? pendingPlanet = _pendingPlanet;
					List<SVec3> pendingExisting = _pendingExisting;
					ClearPendingBlueprint(hideBanner: true);
					OpenPasteBlueprint(pendingPlanet, pendingBlueprint, pendingExisting);
				}
			}
			ShieldPlannerUI.SetBusy(busy: false);
			if (VFInput.inputing || IsInBlockingUI() || !GameMain.mainPlayer.isAlive)
			{
				return;
			}
			if (GameMain.localPlanet == null)
			{
				if (ShieldPlannerUI.IsOpen && IsTogglePanelKeyDown())
				{
					ShieldPlannerUI.Toggle();
				}
				return;
			}
			if (IsTogglePanelKeyDown())
			{
				ShieldPlannerUI.Toggle();
				return;
			}
			value = PluginConfig.HotkeyPlan.Value;
			bool num = ((KeyboardShortcut)(ref value)).IsDown();
			value = PluginConfig.HotkeyPlace.Value;
			bool flag = ((KeyboardShortcut)(ref value)).IsDown();
			value = PluginConfig.HotkeyBlueprint.Value;
			bool flag2 = ((KeyboardShortcut)(ref value)).IsDown();
			if (num || flag || flag2)
			{
				TryTrigger(flag, flag2);
				return;
			}
			value = PluginConfig.HotkeyDiagnostic.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				RunDiagnostic();
			}
		}

		internal static void RunDiagnostic()
		{
			if (TryGetDiagnosticTarget(requireDebugRecord: false, out PlanetData planet))
			{
				PlanetATField aTField = ShieldInfo.GetATField();
				Plugin instance = Instance;
				DiagnosticResult diagnosticResult = DiagnosticReportBuilder.RunLightDiagnostic(planet, aTField, ref instance._lastFill, ref instance._lastCount);
				ShieldPlannerUI.SetStatus(diagnosticResult.Summary);
				ShieldPlannerUI.ShowBanner(diagnosticResult.Summary, 7f);
			}
		}

		internal static void RunCopyDiagnosticSummary()
		{
			if (TryGetDiagnosticTarget(requireDebugRecord: true, out PlanetData planet))
			{
				PlanetATField aTField = ShieldInfo.GetATField();
				Plugin instance = Instance;
				DiagnosticResult diagnosticResult = DiagnosticReportBuilder.CopyCompactSummary(planet, aTField, instance._lastSolve, ref instance._lastFill, ref instance._lastCount);
				ShieldPlannerUI.SetStatus(diagnosticResult.Summary);
				ShieldPlannerUI.ShowBanner(diagnosticResult.Summary, 7f);
			}
		}

		internal static void RunExportFullDiagnosticBundle()
		{
			if (TryGetDiagnosticTarget(requireDebugRecord: true, out PlanetData planet))
			{
				PlanetATField aTField = ShieldInfo.GetATField();
				Plugin instance = Instance;
				DiagnosticResult diagnosticResult = DiagnosticReportBuilder.ExportFullBundle(planet, aTField, instance._lastSolve, ref instance._lastFill, ref instance._lastCount);
				ShieldPlannerUI.SetStatus(diagnosticResult.Summary);
				ShieldPlannerUI.ShowBanner(diagnosticResult.Summary);
			}
		}

		private static bool TryGetDiagnosticTarget(bool requireDebugRecord, out PlanetData planet)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Invalid comparison between Unknown and I4
			planet = null;
			if (!IsInPlayableGame())
			{
				Log.LogWarning((object)"[ShieldPlanner] 未处于有效对局中,不可执行诊断");
				return false;
			}
			if (Instance._task != null)
			{
				Log.LogInfo((object)"[ShieldPlanner] 求解中,暂不可诊断(完成后即可)");
				ShieldPlannerUI.ShowBanner("求解中,请等待完成后再诊断", 5f);
				return false;
			}
			if (requireDebugRecord && !PluginConfig.DebugRecord.Value)
			{
				Log.LogWarning((object)"[ShieldPlanner] 请先勾选面板「调试记录」后再导出排障报告");
				ShieldPlannerUI.ShowBanner("请先勾选「调试记录」再导出排障报告", 5f);
				return false;
			}
			PlanetData localPlanet = GameMain.localPlanet;
			if (localPlanet == null || (int)localPlanet.type == 5)
			{
				string text = ((localPlanet == null) ? "需在星球上执行诊断" : "气态行星无护盾系统");
				Log.LogWarning((object)("[ShieldPlanner] 诊断:" + text));
				ShieldPlannerUI.ShowBanner("ShieldPlanner:" + text, 5f);
				ShieldPlannerUI.SetStatus("状态:" + text);
				return false;
			}
			planet = localPlanet;
			return true;
		}

		internal static void TryTrigger(bool place, bool asBlueprint)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Invalid comparison between Unknown and I4
			if (!IsInPlayableGame())
			{
				Log.LogWarning((object)"[ShieldPlanner] 未处于有效对局中,不可触发");
				return;
			}
			if (!GameMain.mainPlayer.isAlive)
			{
				Log.LogWarning((object)"[ShieldPlanner] 机甲已被摧毁,无法规划");
				ShieldPlannerUI.ShowBanner("ShieldPlanner:机甲已被摧毁,无法规划", 5f);
				return;
			}
			Plugin instance = Instance;
			if (instance._task != null)
			{
				Log.LogWarning((object)"[ShieldPlanner] 求解中,已忽略本次触发(完成后可再次操作)");
				ShieldPlannerUI.ShowBanner("求解中,请等待完成后再操作", 5f);
				return;
			}
			PlanetData localPlanet = GameMain.localPlanet;
			if (localPlanet == null)
			{
				Log.LogWarning((object)"[ShieldPlanner] 需在星球上触发(星系视图/太空不可用)");
				ShieldPlannerUI.ShowBanner("ShieldPlanner:需在星球上触发", 5f);
				return;
			}
			if ((int)localPlanet.type == 5)
			{
				Log.LogWarning((object)"[ShieldPlanner] 气态星无法放置护盾");
				ShieldPlannerUI.ShowBanner("ShieldPlanner:气态星无法放置护盾", 5f);
				return;
			}
			if (localPlanet.factory == null || !localPlanet.factoryLoaded)
			{
				Log.LogWarning((object)"[ShieldPlanner] 当前星球工厂尚未加载完成");
				ShieldPlannerUI.ShowBanner("ShieldPlanner:当前星球工厂尚未加载完成", 5f);
				return;
			}
			Log.LogInfo((object)("[ShieldPlanner] " + (place ? "代拍" : (asBlueprint ? "蓝图" : "计划")) + ":" + (place ? "计算并放置" : (asBlueprint ? "计算并生成粘贴蓝图" : "计算计划")) + "…"));
			PlannerOptions opt = new PlannerOptions
			{
				FullShield = PluginConfig.FullShield.Value,
				AlphaDeg = (PluginConfig.AlphaAuto.Value ? ((double?)null) : new double?(PluginConfig.AlphaDeg.Value)),
				BlockVeins = PluginConfig.BlockVeins.Value,
				VeinInflateDeg = PluginConfig.VeinInflateDeg.Value,
				GridDeg = PluginConfig.GridDeg.Value,
				BlockInflateDeg = PluginConfig.BlockInflateDeg.Value,
				DarkFogMode = PluginConfig.DarkFogMode.Value,
				DarkFogAggroMarginM = PluginConfig.DarkFogAggroMarginM.Value
			};
			PlanSnapshot snap = ShieldPlannerRunner.Snapshot(opt);
			if (snap == null)
			{
				return;
			}
			LastSolveAlpha = snap.Alpha;
			CancellationTokenSource cts = new CancellationTokenSource();
			CancellationToken token = cts.Token;
			instance._taskPlanet = localPlanet;
			instance._taskPlace = place;
			instance._taskAsBlueprint = asBlueprint;
			instance._taskExisting = new List<SVec3>(snap.InitialShields);
			instance._taskSnap = snap;
			instance._taskCts = cts;
			instance._taskStartRealtime = Time.realtimeSinceStartup;
			Task<PlanOutcome> task = Task.Run(delegate
			{
				try
				{
					return ShieldPlannerRunner.Compute(snap, token);
				}
				catch (OperationCanceledException)
				{
					return (PlanOutcome?)null;
				}
			}, token);
			task.ContinueWith(delegate
			{
				cts.Dispose();
			}, TaskScheduler.Default);
			instance._task = task;
			ShieldPlannerUI.SetBusy(busy: true);
			ShieldPlannerUI.ShowBanner(place ? "ShieldPlanner 求解中…(完成自动放置)" : (asBlueprint ? "ShieldPlanner 求解中…(完成后打开蓝图粘贴)" : "ShieldPlanner 求解中…(仅计算,不放置)"), 5f, BannerTag.Solving);
			Log.LogInfo((object)"[ShieldPlanner] 后台计算中…(游戏不卡,完成后自动落地;求解中触发键已禁用)");
		}

		private void LandResult()
		{
			Task<PlanOutcome> task = _task;
			PlanetData taskPlanet = _taskPlanet;
			bool taskPlace = _taskPlace;
			bool taskAsBlueprint = _taskAsBlueprint;
			List<SVec3> taskExisting = _taskExisting;
			PlanSnapshot taskSnap = _taskSnap;
			try
			{
				ShieldPlannerUI.HideBannerIf(BannerTag.Solving);
				if (task.IsCanceled)
				{
					return;
				}
				PlanOutcome result = task.GetAwaiter().GetResult();
				if (result == null)
				{
					return;
				}
				List<SVec3> dirs = result.Dirs;
				if (!IsInPlayableGame() || GameMain.localPlanet != taskPlanet || taskPlanet.factory == null)
				{
					Log.LogWarning((object)"[ShieldPlanner] 求解结果已丢弃:已离开目标星球(或切换存档)");
					ShieldPlannerUI.SetStatus("状态:求解结果已丢弃(已离开目标星球)");
					ShieldPlannerUI.ShowBanner("求解结果已丢弃:已离开目标星球", 6f);
					return;
				}
				if (taskSnap != null && taskPlanet.factory != null)
				{
					PlanetFactory factory = taskPlanet.factory;
					if (factory.entityCursor != taskSnap.EntityCursor || factory.prebuildCursor != taskSnap.PrebuildCursor)
					{
						Log.LogWarning((object)($"[ShieldPlanner] 求解期间星球建造有变化(实体 {taskSnap.EntityCursor}→{factory.entityCursor})," + "结果基于旧快照;冲突点会被自动跳过(AddPrebuildData 失败计数见落地日志)"));
					}
				}
				if (dirs.Count == 0)
				{
					if (result.CandidateCount == 0)
					{
						Log.LogWarning((object)"[ShieldPlanner] 无可用候选点(请调小建筑/矿脉避让缓冲后重试)");
						ShieldPlannerUI.SetStatus("状态:无可用候选点(请调小建筑/矿脉避让缓冲后重试)");
						ShieldPlannerUI.ShowBanner("无可用候选点:请调小建筑/矿脉避让缓冲后重试", 7f);
					}
					else
					{
						Log.LogInfo((object)"[ShieldPlanner] 当前已有护盾已满足目标覆盖,无需新增护盾");
						ShieldPlannerUI.SetStatus("状态:当前已有护盾已满足覆盖,无需新增");
						ShieldPlannerUI.ShowBanner("当前已有护盾已满足覆盖,无需新增", 6f);
					}
					return;
				}
				if (taskAsBlueprint)
				{
					RecordLastSolve(taskPlanet, "蓝图", taskSnap, result);
					if (PlayerInBuildMode())
					{
						_pendingBlueprint = dirs;
						_pendingPlanet = taskPlanet;
						_pendingExisting = taskExisting;
						Log.LogInfo((object)"[ShieldPlanner] 玩家正处建造/粘贴模式:蓝图已就绪,退出模式后自动打开粘贴预览");
						ShieldPlannerUI.SetStatus($"状态:蓝图已就绪({dirs.Count} 盾),退出建造模式后自动打开");
						ShieldPlannerUI.ShowBanner("蓝图已就绪:退出建造/粘贴模式后自动打开", 8f, BannerTag.PendingBlueprint);
					}
					else
					{
						OpenPasteBlueprint(taskPlanet, dirs, taskExisting);
					}
					return;
				}
				ShieldPlannerRunner.Finalize(taskPlanet, dirs, taskPlace, out var ok, out var fail, out var waterCount, taskSnap?.DarkFogMode ?? PluginConfig.DarkFogMode.Value, taskSnap?.DarkFogAggroMarginM ?? PluginConfig.DarkFogAggroMarginM.Value);
				RecordLastSolve(taskPlanet, taskPlace ? "代拍" : "计划", taskSnap, result, taskPlace, ok, fail, waterCount);
				string text = (result.FullShield ? $"预测满盾 {result.ExactFillRatio * 100.0:F2}%" : $"预测防降落 {result.ExactDefenceRatio * 100.0:F2}%");
				if (taskPlace)
				{
					string text2 = ((waterCount > 0) ? $"({waterCount} 处位于水面/低地需补地基)" : "");
					ShieldPlannerUI.SetStatus($"代拍完成:成功 {ok},失败 {fail}{text2} | {text}");
					ShieldPlannerUI.ShowBanner($"代拍完成:成功 {ok},失败 {fail}{text2} | {text}(充能后点「诊断」核验)");
				}
				else
				{
					string arg = ((result.AddedCount > 0 || result.PrunedCount > 0) ? $"(基础 {result.PlanACount},+{result.AddedCount}/-{result.PrunedCount})" : "");
					ShieldPlannerUI.SetStatus($"计划完成:建议新增 {dirs.Count} 盾{arg} | {text}");
					ShieldPlannerUI.ShowBanner($"计划完成:建议新增 {dirs.Count} 盾{arg},{text}(坐标已写入日志)");
				}
			}
			catch (OperationCanceledException)
			{
				Log.LogInfo((object)"[ShieldPlanner] 后台求解已取消");
			}
			catch (Exception ex2)
			{
				Log.LogError((object)("[ShieldPlanner] 求解失败: " + ex2.Message + "\n" + ex2.StackTrace));
				ShieldPlannerUI.SetStatus("状态:求解出错(" + ex2.Message + ")");
				ShieldPlannerUI.ShowBanner("求解出错,请查看 BepInEx 日志", 6f);
			}
			finally
			{
				_task = null;
				_taskCts = null;
				_taskPlanet = null;
				_taskExisting = null;
				_taskSnap = null;
				_pausedLogged = false;
				ShieldPlannerUI.SetBusy(busy: false);
			}
		}

		private void RecordLastSolve(PlanetData planet, string actionName, PlanSnapshot? snap, PlanOutcome outcome, bool hasPlacement = false, int placedOk = 0, int placedFail = 0, int waterCount = 0)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//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_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			if (!PluginConfig.DebugRecord.Value)
			{
				_lastSolve = null;
				return;
			}
			SVec3[] array = (SVec3[])((snap != null && snap.InitialShields.Length != 0) ? ((Array)new SVec3[snap.InitialShields.Length]) : ((Array)Array.Empty<SVec3>()));
			if (snap != null)
			{
				for (int i = 0; i < snap.InitialShields.Length; i++)
				{
					array[i] = ShieldPlannerRunner.SolverToGameSv(snap.InitialShields[i]);
				}
			}
			List<SVec3> list = new List<SVec3>(outcome.Dirs.Count);
			foreach (SVec3 dir in outcome.Dirs)
			{
				list.Add(ShieldPlannerRunner.SolverToGameSv(dir));
			}
			_lastSolve = new LastSolveRecord
			{
				Planet = planet,
				ActionName = actionName,
				FullShield = outcome.FullShield,
				Alpha = outcome.Alpha,
				ElapsedSec = Math.Max(0.0, (double)Time.realtimeSinceStartup - _taskStartRealtime),
				CandidateCount = outcome.CandidateCount,
				ExistingCount = outcome.ExistingCount,
				PlanACount = outcome.PlanACount,
				AddedCount = outcome.AddedCount,
				PrunedCount = outcome.PrunedCount,
				FinalNewCount = outcome.Dirs.Count,
				PredictedFill = outcome.ExactFillRatio,
				PredictedDef = outcome.ExactDefenceRatio,
				HasPlacement = hasPlacement,
				PlacedOk = placedOk,
				PlacedFail = placedFail,
				WaterCount = waterCount,
				ExistingDirs = array,
				NewDirs = list
			};
		}

		private static bool PlayerInBuildMode()
		{
			Player mainPlayer = GameMain.mainPlayer;
			PlayerAction_Build val = ((mainPlayer == null) ? null : mainPlayer.controller?.actionBuild);
			if (val != null && val.activeTool != null)
			{
				return (object)val.activeTool != val.noneTool;
			}
			return false;
		}

		private static void OpenPasteBlueprint(PlanetData planet, List<SVec3> dirs, List<SVec3>? existing)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Invalid comparison between Unknown and I4
			Player mainPlayer = GameMain.mainPlayer;
			if (mainPlayer == null || (Object)(object)mainPlayer.controller == (Object)null)
			{
				return;
			}
			BlueprintData val = BlueprintBuilder.Build(planet, dirs, existing);
			if (val == null)
			{
				Log.LogWarning((object)"[ShieldPlanner] 无护盾点,无法生成蓝图");
				return;
			}
			mainPlayer.controller.OpenBlueprintPasteMode(val, "", true);
			PlayerAction_Build actionBuild = mainPlayer.controller.actionBuild;
			if (actionBuild == null || (int)actionBuild.blueprintMode != 2)
			{
				Log.LogWarning((object)"[ShieldPlanner] 未能进入蓝图粘贴模式(可能尚未解锁蓝图科技)");
				ShieldPlannerUI.SetStatus("状态:未能进入蓝图粘贴模式(请确认已解锁蓝图科技,或改用「代拍」)");
				ShieldPlannerUI.ShowBanner("无法打开蓝图粘贴(请确认已解锁蓝图科技,或改用「代拍」)", 6f);
				return;
			}
			int num = existing?.Count ?? 0;
			if (num > 0)
			{
				Log.LogInfo((object)($"[ShieldPlanner] 已打开粘贴预览:{val.buildings.Length} 个护盾(含 {num} 个已有盾作参考)。" + "注意:多 area 全球蓝图经度相位跟随光标,无法与已有盾精确对齐——补洞请改用面板「代拍」按钮;若仍需粘贴蓝图,请将光标放在赤道附近并保持 0° 旋转(勿按 R),地基由游戏提示后按 Shift+F 补。"));
				ShieldPlannerUI.SetStatus($"蓝图已打开:{dirs.Count} 新盾 + {num} 已有参考(补洞建议改用「代拍」)");
				ShieldPlannerUI.ShowBanner("已有盾补洞请改用「代拍」;蓝图需赤道附近 + 0° 旋转(勿按 R)", 8f, BannerTag.BlueprintPaste);
			}
			else
			{
				Log.LogInfo((object)($"[ShieldPlanner] 已打开全球蓝图粘贴:{val.buildings.Length} 个护盾。" + "请将光标放赤道(0° 纬线)附近 + 保持 0° 旋转(勿按 R),否则提示\"蓝图子区域被分割\";地基由游戏提示后按 Shift+F 补。"));
				ShieldPlannerUI.SetStatus($"全球蓝图已打开:共 {dirs.Count} 盾(赤道附近 + 0° 旋转粘贴,Shift+F 补地基)");
				ShieldPlannerUI.ShowBanner("全球蓝图粘贴:光标放赤道附近 + 保持 0° 旋转(勿按 R),地基按 Shift+F", 10f, BannerTag.BlueprintPaste);
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "dsp.shieldplanner";

		public const string PLUGIN_NAME = "DSP ShieldPlanner";

		public const string PLUGIN_VERSION = "0.7.0";
	}
	public static class PluginConfig
	{
		public static ConfigEntry<bool> FullShield;

		public static ConfigEntry<bool> AlphaAuto;

		public static ConfigEntry<float> AlphaDeg;

		public static ConfigEntry<bool> BlockVeins;

		public static ConfigEntry<float> VeinInflateDeg;

		public static ConfigEntry<float> BlockInflateDeg;

		public static ConfigEntry<float> GridDeg;

		public static ConfigEntry<DarkFogAvoidMode> DarkFogMode;

		public static ConfigEntry<float> DarkFogAggroMarginM;

		public static ConfigEntry<KeyboardShortcut> HotkeyPlan;

		public static ConfigEntry<KeyboardShortcut> HotkeyPlace;

		public static ConfigEntry<KeyboardShortcut> HotkeyBlueprint;

		public static ConfigEntry<KeyboardShortcut> HotkeyDiagnostic;

		public static ConfigEntry<bool> DebugRecord;

		public static void Init(ConfigFile config)
		{
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			FullShield = config.Bind<bool>("Shield", "FullShield", true, "满盾 100%(true)或防降落 7 盾(false)");
			AlphaAuto = config.Bind<bool>("Shield", "AlphaAuto", true, "α 覆盖角自动按星球半径计算(true);false 用 AlphaDeg 手动值");
			AlphaDeg = config.Bind<float>("Shield", "AlphaDeg", 38.05f, "手动 α 覆盖角(度),AlphaAuto=false 时生效");
			BlockVeins = config.Bind<bool>("Block", "BlockVeins", true, "矿脉当禁点(默认开启:护盾不压矿脉,矿簇留待开采)");
			VeinInflateDeg = config.Bind<float>("Block", "VeinInflateDeg", 1.5f, "矿脉禁点膨胀(度,有效范围 0.5°~5.0°);矿簇由密集节点组成,膨胀圈互相叠成区域,1.5° 与建筑一致即可");
			BlockInflateDeg = config.Bind<float>("Block", "BlockInflateDeg", 1.5f, "禁点膨胀(度,有效范围 0.5°~4.0°)");
			GridDeg = config.Bind<float>("Block", "GridDeg", 1f, "候选网格间隔(度,仅高级 cfg 调整,建议保持 1.0°)");
			DarkFogMode = config.Bind<DarkFogAvoidMode>("Block", "DarkFogMode", DarkFogAvoidMode.Buildings, "黑雾避让模式:Ignore=无视,CoreOnly=仅避核心/地热坑,Buildings=避开黑雾建筑(默认),AggroRange=避开引怪/射程范围");
			DarkFogAggroMarginM = config.Bind<float>("Block", "DarkFogAggroMarginM", 8f, "引怪模式额外安全余量(米,有效范围 0~40m,仅 AggroRange 模式生效)");
			HotkeyPlan = config.Bind<KeyboardShortcut>("Hotkeys", "Plan", KeyboardShortcut.Empty, "只计算计划(默认不绑定;格式如 LeftControl + LeftShift + F9,留空=不绑定)");
			HotkeyPlace = config.Bind<KeyboardShortcut>("Hotkeys", "Place", KeyboardShortcut.Empty, "计算并代拍(默认不绑定;格式如 LeftControl + LeftShift + F10)");
			HotkeyBlueprint = config.Bind<KeyboardShortcut>("Hotkeys", "Blueprint", KeyboardShortcut.Empty, "计算并生成全球蓝图(默认不绑定;格式如 LeftControl + LeftShift + F11)");
			HotkeyDiagnostic = config.Bind<KeyboardShortcut>("Hotkeys", "Diagnostic", KeyboardShortcut.Empty, "实测诊断(默认不绑定;格式如 LeftControl + LeftShift + F12)");
			DebugRecord = config.Bind<bool>("Debug", "DebugRecord", false, "开启调试记录:求解时额外采集轨迹,并解锁面板「复制摘要」与「导出完整包」按钮");
		}
	}
}
namespace DSP.ShieldPlanner.UI
{
	public class MyCheckBox : MonoBehaviour
	{
		private const float BoxSize = 20f;

		private const float CheckInset = 4f;

		private const float LabelGap = 8f;

		private const float RowHeight = 26f;

		public RectTransform rectTrans;

		public Image checkImage;

		public Text labelText;

		private Button _button;

		private Image _boxImage;

		private bool _checked;

		private static readonly Color BoxColor = new Color(1f, 1f, 1f, 20f / 51f);

		private static readonly Color CheckColor = new Color(1f, 1f, 1f, 1f);

		private static readonly Color TextColor = new Color(43f / 51f, 43f / 51f, 43f / 51f, 0.88235295f);

		private static readonly Color DimColor = new Color(0.5f, 0.5f, 0.5f, 0.5f);

		public bool Checked
		{
			get
			{
				return _checked;
			}
			set
			{
				_checked = value;
				((Behaviour)checkImage).enabled = value;
			}
		}

		public event Action? OnClicked;

		public static MyCheckBox CreateCheckBox(float x, float y, RectTransform parent, string label = "", int fontSize = 15)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Expected O, but got Unknown
			//IL_017b: 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_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Expected O, but got Unknown
			GameObject val = new GameObject("sp-checkbox", new Type[3]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(Button)
			});
			MyCheckBox cb = val.AddComponent<MyCheckBox>();
			cb.rectTrans = UIUtil.NormalizeTopLeft((Component)(object)cb, x, y, (Transform?)(object)parent);
			((Graphic)val.GetComponent<Image>()).color = Color.clear;
			cb._button = val.GetComponent<Button>();
			((Selectable)cb._button).transition = (Transition)0;
			GameObject val2 = new GameObject("box", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			cb._boxImage = val2.GetComponent<Image>();
			((Graphic)cb._boxImage).color = BoxColor;
			((Graphic)cb._boxImage).raycastTarget = false;
			RectTransform val3 = UIUtil.NormalizeTopLeft((Component)(object)cb._boxImage, 0f, 3f, (Transform?)(object)cb.rectTrans);
			val3.sizeDelta = new Vector2(20f, 20f);
			GameObject val4 = new GameObject("checked", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			cb.checkImage = val4.GetComponent<Image>();
			((Graphic)cb.checkImage).color = CheckColor;
			((Graphic)cb.checkImage).raycastTarget = false;
			UIUtil.NormalizeTopLeft((Component)(object)cb.checkImage, 4f, 4f, (Transform?)(object)val3).sizeDelta = new Vector2(12f, 12f);
			cb.labelText = UIUtil.AddText(28f, 0f, cb.rectTrans, "", fontSize, 0f, 26f, (TextAnchor)3);
			((Graphic)cb.labelText).color = TextColor;
			((Graphic)cb.labelText).raycastTarget = false;
			((UnityEvent)cb._button.onClick).AddListener((UnityAction)delegate
			{
				cb.Checked = !cb.Checked;
				cb.OnClicked?.Invoke();
			});
			cb.Checked = false;
			cb.SetLabelText(label);
			return cb;
		}

		private void UpdateLabelTextWidth()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			float num = labelText.preferredWidth + 4f;
			((Graphic)labelText).rectTransform.sizeDelta = new Vector2(num, 26f);
			rectTrans.sizeDelta = new Vector2(28f + num, 26f);
		}

		public void SetLabelText(string val)
		{
			labelText.text = val;
			UpdateLabelTextWidth();
		}

		public void SetEnable(bool on)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			((Selectable)_button).interactable = on;
			((Graphic)_boxImage).color = (on ? BoxColor : DimColor);
			((Graphic)checkImage).color = (on ? CheckColor : DimColor);
			((Graphic)labelText).color = (on ? TextColor : DimColor);
		}
	}
	public class MySlider : MonoBehaviour
	{
		public RectTransform rectTrans;

		public Slider slider;

		public Text valueText;

		public string labelFormat = "G";

		public string suffix = "";

		private Image? _bgImage;

		private Image? _fillImage;

		private Image? _handleImage;

		private Text? _linkedLabel;

		private string? _overrideText;

		private static GameObject _baseObject;

		public float Value
		{
			get
			{
				return slider.value;
			}
			set
			{
				float value2 = Mathf.Clamp(value, slider.minValue, slider.maxValue);
				slider.value = value2;
				UpdateLabel();
			}
		}

		public static void InitBaseObject()
		{
			if (!Object.op_Implicit((Object)(object)_baseObject))
			{
				GameObject obj = Object.Instantiate<GameObject>(((Component)UIRoot.instance.optionWindow.audioVolumeComp).gameObject);
				((Object)obj).name = "sp-slider-base";
				obj.SetActive(false);
				_baseObject = obj;
			}
		}

		internal static void DestroyBaseObject()
		{
			if ((Object)(object)_baseObject != (Object)null)
			{
				Object.Destroy((Object)(object)_baseObject);
				_baseObject = null;
			}
		}

		public static MySlider CreateSlider(float x, float y, RectTransform parent, float value, float minValue, float maxValue, string format = "G", float width = 280f, bool wholeNumbers = false, string suffix = "", float valueWidth = 90f, Text? linkedLabel = null)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(_baseObject);
			((Object)val).name = "sp-slider";
			val.SetActive(true);
			MySlider sl = val.AddComponent<MySlider>();
			RectTransform val2 = UIUtil.NormalizeTopLeft((Component)(object)sl, x, y, (Transform?)(object)parent);
			sl.rectTrans = val2;
			val2.sizeDelta = new Vector2(width, 20f);
			sl.slider = val.GetComponent<Slider>();
			sl.slider.wholeNumbers = wholeNumbers;
			sl.slider.minValue = minValue;
			sl.slider.maxValue = maxValue;
			((UnityEventBase)sl.slider.onValueChanged).RemoveAllListeners();
			((UnityEvent<float>)(object)sl.slider.onValueChanged).AddListener((UnityAction<float>)delegate
			{
				sl.UpdateLabel();
			});
			sl.labelFormat = format;
			sl.suffix = suffix;
			sl._linkedLabel = linkedLabel;
			RectTransform handleRect = sl.slider.handleRect;
			Transform val3 = ((handleRect != null) ? ((Transform)handleRect).Find("Text") : null);
			if ((Object)(object)val3 != (Object)null)
			{
				Text component = ((Component)val3).GetComponent<Text>();
				if ((Object)(object)component != (Object)null)
				{
					component.text = "";
				}
				((Component)val3).gameObject.SetActive(false);
			}
			sl.valueText = UIUtil.AddText(width + 10f, -4f, val2, "", 15, valueWidth, 28f, (TextAnchor)5);
			sl.valueText.horizontalOverflow = (HorizontalWrapMode)1;
			((Graphic)sl.valueText).color = new Color(0.92f, 0.92f, 0.92f, 0.92f);
			MySlider mySlider = sl;
			Transform obj = ((Component)sl.slider).transform.Find("Background");
			mySlider._bgImage = ((obj != null) ? ((Component)obj).GetComponent<Image>() : null);
			if ((Object)(object)sl._bgImage != (Object)null)
			{
				((Graphic)sl._bgImage).color = new Color(0.5f, 0.5f, 0.5f, 0.5f);
			}
			sl._fillImage = (((Object)(object)sl.slider.fillRect != (Object)null) ? ((Component)sl.slider.fillRect).GetComponent<Image>() : null);
			if ((Object)(object)sl._fillImage != (Object)null)
			{
				((Graphic)sl._fillImage).color = new Color(1f, 1f, 1f, 0.28f);
			}
			sl._handleImage = (((Object)(object)sl.slider.handleRect != (Object)null) ? ((Component)sl.slider.handleRect).GetComponent<Image>() : null);
			sl.Value = value;
			return sl;
		}

		public void SetOverrideText(string? text)
		{
			_overrideText = text;
			UpdateLabel();
		}

		public void UpdateLabel()
		{
			if ((Object)(object)valueText != (Object)null)
			{
				valueText.text = _overrideText ?? (slider.value.ToString(labelFormat) + suffix);
			}
		}

		public void SetEnable(bool on)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: 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_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)slider))
			{
				((Selectable)slider).interactable = on;
			}
			if ((Object)(object)_bgImage != (Object)null)
			{
				((Graphic)_bgImage).color = (on ? new Color(0.5f, 0.5f, 0.5f, 0.5f) : new Color(0.35f, 0.35f, 0.35f, 0.25f));
			}
			if ((Object)(object)_fillImage != (Object)null)
			{
				((Graphic)_fillImage).color = (on ? new Color(1f, 1f, 1f, 0.28f) : new Color(0.6f, 0.6f, 0.6f, 0.12f));
			}
			if ((Object)(object)_handleImage != (Object)null)
			{
				((Graphic)_handleImage).color = (Color)(on ? Color.white : new Color(0.6f, 0.6f, 0.6f, 0.45f));
			}
			if ((Object)(object)valueText != (Object)null)
			{
				((Graphic)valueText).color = (on ? new Color(0.92f, 0.92f, 0.92f, 0.92f) : new Color(0.65f, 0.72f, 0.78f, 0.65f));
			}
			if ((Object)(object)_linkedLabel != (Object)null)
			{
				((Graphic)_linkedLabel).color = (on ? new Color(0.9f, 0.9f, 0.9f, 0.78f) : new Color(0.6f, 0.6f, 0.6f, 0.42f));
			}
		}
	}
	public enum BannerTag
	{
		General,
		Solving,
		PendingBlueprint,
		BlueprintPaste
	}
	public static class ShieldPlannerUI
	{
		private const string DefaultStatusText = "状态:空闲(点击下方按钮开始规划或诊断)";

		private static ShieldPlannerWindow? _win;

		private static Banner? _banner;

		private static bool _busy;

		private static float _busyStart;

		private static string _statusText = "状态:空闲(点击下方按钮开始规划或诊断)";

		public static bool IsOpen
		{
			get
			{
				if ((Object)(object)_win != (Object)null)
				{
					return ((ManualBehaviour)_win).active;
				}
				return false;
			}
		}

		public static bool IsBusy => _busy;

		public static float BusyStart => _busyStart;

		public static string StatusText => _statusText;

		private static bool CanInit
		{
			get
			{
				if ((Object)(object)UIRoot.instance != (Object)null)
				{
					return (Object)(object)UIRoot.instance.uiGame != (Object)null;
				}
				return false;
			}
		}

		public static void Toggle()
		{
			if (!Plugin.IsInPlayableGame() || !CanInit)
			{
				Plugin.Log.LogWarning((object)"[ShieldPlanner] 游戏 UI 未就绪(面板需在游戏场景内打开)");
				return;
			}
			if ((Object)(object)_win == (Object)null)
			{
				ShieldPlannerWindow.InitBaseObject();
				MySlider.InitBaseObject();
				_win = ShieldPlannerWindow.Create();
			}
			if (IsOpen)
			{
				_win.Close();
			}
			else
			{
				_win.Open();
			}
		}

		public static void Close()
		{
			if ((Object)(object)_win != (Object)null && ((ManualBehaviour)_win).active)
			{
				_win.Close();
			}
		}

		public static void Tick()
		{
			if ((Object)(object)_win != (Object)null && ((ManualBehaviour)_win).active)
			{
				((ManualBehaviour)_win)._Update();
			}
		}

		public static void SetBusy(bool busy)
		{
			if (busy && !_busy)
			{
				_busyStart = Time.realtimeSinceStartup;
			}
			_busy = busy;
			_win?.RefreshState();
		}

		public static void SetStatus(string text)
		{
			_statusText = text;
			_win?.RefreshState();
		}

		public static void ResetStatus()
		{
			_statusText = "状态:空闲(点击下方按钮开始规划或诊断)";
			_win?.RefreshState();
		}

		public static void ShowBanner(string text, float seconds = 8f, BannerTag tag = BannerTag.General)
		{
			if (!Plugin.IsInPlayableGame() || !CanInit)
			{
				return;
			}
			if ((Object)(object)_banner == (Object)null)
			{
				_banner = Banner.Create();
				if ((Object)(object)_banner == (Object)null)
				{
					return;
				}
			}
			_banner.Show(text, seconds, tag);
		}

		public static void HideBanner()
		{
			_banner?.Hide();
		}

		public static void HideBannerIf(BannerTag tag)
		{
			if ((Object)(object)_banner != (Object)null && _banner.IsShowingTag(tag))
			{
				_banner.Hide();
			}
		}

		public static void OnPlanetChanged()
		{
			_win?.OnPlanetChanged();
		}

		public static void OnUIRootDestroy()
		{
			_win = null;
			_banner = null;
		}

		public static void ResetSessionUI()
		{
			Close();
			HideBanner();
			ResetStatus();
			SetBusy(busy: false);
		}

		public static void OnModDestroy()
		{
			if ((Object)(object)_win != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_win).gameObject);
				_win = null;
			}
			if ((Object)(object)_banner != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_banner).gameObject);
				_banner = null;
			}
			ShieldPlannerWindow.DestroyBaseObject();
			MySlider.DestroyBaseObject();
		}
	}
	public class ShieldPlannerWindow : ManualBehaviour
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__35_0;

			public static UnityAction <>9__35_1;

			public static UnityAction <>9__35_2;

			public static UnityAction <>9__35_3;

			public static UnityAction <>9__35_4;

			public static UnityAction <>9__35_5;

			internal void <_OnCreate>b__35_0()
			{
				Plugin.TryTrigger(place: false, asBlueprint: false);
			}

			internal void <_OnCreate>b__35_1()
			{
				Plugin.TryTrigger(place: true, asBlueprint: false);
			}

			internal void <_OnCreate>b__35_2()
			{
				Plugin.TryTrigger(place: false, asBlueprint: true);
			}

			internal void <_OnCreate>b__35_3()
			{
				Plugin.RunDiagnostic();
			}

			internal void <_OnCreate>b__35_4()
			{
				Plugin.RunCopyDiagnosticSummary();
			}

			internal void <_OnCreate>b__35_5()
			{
				Plugin.RunExportFullDiagnosticBundle();
			}
		}

		private const float WinWidth = 620f;

		private const float WinHeight = 662f;

		private const float PadX = 28f;

		private const float ContentWidth = 564f;

		private const float LabelWidth = 176f;

		private const float SliderX = 212f;

		private const float SliderWidth = 280f;

		private Text _statusText;

		private Text _modeHint;

		private Text _darkFogHint;

		private UIButton _planBtn;

		private UIButton _placeBtn;

		private UIButton _blueprintBtn;

		private UIButton _diagBtn;

		private UIButton _copySummaryBtn;

		private UIButton _exportBundleBtn;

		private UIButton[] _dfModeBtns;

		private MyCheckBox _fullCb;

		private MyCheckBox _alphaAutoCb;

		private MyCheckBox _veinsCb;

		private MyCheckBox _debugCb;

		private MySlider _alphaSlider;

		private MySlider _blockInflateSlider;

		private MySlider _veinInflateSlider;

		private MySlider _dfMarginSlider;

		private int _lastEstKB = -2;

		private static GameObject _baseObject;

		public static void InitBaseObject()
		{
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: 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_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)_baseObject))
			{
				return;
			}
			GameObject val = Object.Instantiate<GameObject>(((Component)UIRoot.instance.uiGame.inserterWindow).gameObject);
			val.SetActive(false);
			((Object)val).name = "sp-window-base";
			Object.DestroyImmediate((Object)(object)val.GetComponent<UIInserterWindow>());
			Object.DestroyImmediate((Object)(object)val.GetComponent<Localizer>());
			LayoutGroup[] components = val.GetComponents<LayoutGroup>();
			for (int i = 0; i < components.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)components[i]);
			}
			AspectRatioFitter[] components2 = val.GetComponents<AspectRatioFitter>();
			for (int i = 0; i < components2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)components2[i]);
			}
			for (int num = val.transform.childCount - 1; num >= 0; num--)
			{
				GameObject gameObject = ((Component)val.transform.GetChild(num)).gameObject;
				if (((Object)gameObject).name != "panel-bg" && ((Object)gameObject).name != "shadow")
				{
					Object.DestroyImmediate((Object)(object)gameObject);
				}
			}
			Transform val2 = val.transform.Find("panel-bg");
			if ((Object)(object)val2 != (Object)null)
			{
				string[] array = new string[3] { "filter-back", "take-back", "state" };
				foreach (string text in array)
				{
					Transform val3 = val2.Find(text);
					if ((Object)(object)val3 != (Object)null)
					{
						Object.DestroyImmediate((Object)(object)((Component)val3).gameObject);
					}
				}
			}
			Transform obj = val.transform.Find("panel-bg");
			RectTransform val4 = ((obj != null) ? ((Component)obj).GetComponent<RectTransform>() : null);
			Transform obj2 = val.transform.Find("shadow");
			RectTransform val5 = ((obj2 != null) ? ((Component)obj2).GetComponent<RectTransform>() : null);
			if ((Object)(object)val4 != (Object)null)
			{
				val4.anchorMin = Vector2.zero;
				val4.anchorMax = Vector2.one;
				val4.pivot = new Vector2(0.5f, 0.5f);
				val4.offsetMin = Vector2.zero;
				val4.offsetMax = Vector2.zero;
			}
			if ((Object)(object)val5 != (Object)null)
			{
				val5.anchorMin = Vector2.zero;
				val5.anchorMax = Vector2.one;
				val5.pivot = new Vector2(0.5f, 0.5f);
				val5.offsetMin = Vector2.zero;
				val5.offsetMax = Vector2.zero;
			}
			_baseObject = val;
		}

		public static ShieldPlannerWindow Create()
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected O, but got Unknown
			GameObject obj = Object.Instantiate<GameObject>(_baseObject, ((Component)UIRoot.instance.uiGame).transform.parent);
			((Object)obj).name = "sp-config-window";
			obj.SetActive(false);
			ShieldPlannerWindow shieldPlannerWindow = obj.AddComponent<ShieldPlannerWindow>();
			Transform obj2 = obj.transform.Find("panel-bg");
			Button val = ((obj2 != null) ? ((Component)obj2).gameObject.GetComponentInChildren<Button>() : null);
			if ((Object)(object)val != (Object)null)
			{
				((UnityEventBase)val.onClick).RemoveAllListeners();
				((UnityEvent)val.onClick).AddListener(new UnityAction(shieldPlannerWindow.Close));
			}
			shieldPlannerWindow.SetTitle("DSP ShieldPlanner 护盾规划");
			((ManualBehaviour)shieldPlannerWindow)._Create();
			((ManualBehaviour)shieldPlannerWindow)._Init((object)null);
			return shieldPlannerWindow;
		}

		public void Open()
		{
			((ManualBehaviour)this)._Open();
			((Component)this).transform.SetAsLastSibling();
		}

		public void Close()
		{
			((ManualBehaviour)this)._Close();
		}

		private void SetTitle(string title)
		{
			Transform obj = ((Component)this).transform.Find("panel-bg/title-text");
			Text val = ((obj != null) ? ((Component)obj).gameObject.GetComponent<Text>() : null);
			if ((Object)(object)val != (Object)null)
			{
				Localizer component = ((Component)val).GetComponent<Localizer>();
				if ((Object)(object)component != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)component);
				}
				UIUtil.ApplyTextFont(val, val.fontSize);
				UIUtil.StripTextFx(((Component)val).gameObject);
				val.horizontalOverflow = (HorizontalWrapMode)1;
				val.verticalOverflow = (VerticalWrapMode)1;
				val.text = title;
			}
		}

		private void ApplyWindowRect()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = ((Component)this).transform;
			RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			if (val != null)
			{
				val.anchorMin = new Vector2(0.5f, 0.5f);
				val.anchorMax = new Vector2(0.5f, 0.5f);
				val.pivot = new Vector2(0.5f, 0.5f);
				val.anchoredPosition = Vector2.zero;
				val.sizeDelta = new Vector2(620f, 662f);
			}
		}

		protected override void _OnOpen()
		{
			((ManualBehaviour)this)._OnOpen();
			ApplyWindowRect();
			UpdateModeHint();
			UpdateAlphaDisplay();
			UpdateDarkFogUI();
			RefreshState();
		}

		protected override bool _OnInit()
		{
			if (!((ManualBehaviour)this)._OnInit())
			{
				return false;
			}
			ApplyWindowRect();
			return true;
		}

		protected override void _OnCreate()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ee: Expected O, but got Unknown
			//IL_043f: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04da: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e0: Expected O, but got Unknown
			//IL_0525: Unknown result type (might be due to invalid IL or missing references)
			//IL_052a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0530: Expected O, but got Unknown
			//IL_0575: Unknown result type (might be due to invalid IL or missing references)
			//IL_057a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0580: Expected O, but got Unknown
			//IL_05c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d0: Expected O, but got Unknown
			//IL_0632: Unknown result type (might be due to invalid IL or missing references)
			//IL_0637: Unknown result type (might be due to invalid IL or missing references)
			//IL_063d: Expected O, but got Unknown
			//IL_06dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0682: Unknown result type (might be due to invalid IL or missing references)
			//IL_0687: Unknown result type (might be due to invalid IL or missing references)
			//IL_068d: Expected O, but got Unknown
			((ManualBehaviour)this)._OnCreate();
			ApplyWindowRect();
			RectTransform parent = (RectTransform)((Component)this).transform;
			_statusText = UIUtil.AddText(28f, 56f, parent, ShieldPlannerUI.StatusText, 15, 564f, 40f, (TextAnchor)0);
			((Graphic)_statusText).color = new Color(1f, 0.9f, 0.65f, 0.95f);
			((Graphic)UIUtil.AddText(28f, 104f, parent, "—— 覆盖模式 ——", 15, 564f, 22f, (TextAnchor)3)).color = new Color(0.68f, 0.85f, 1f, 0.92f);
			_fullCb = MyCheckBox.CreateCheckBox(28f, 132f, parent, "满盾模式(100% 覆盖;取消勾选 = 防降落 7 盾)");
			_modeHint = UIUtil.AddText(28f, 162f, parent, "", 13, 564f, 34f, (TextAnchor)0);
			((Graphic)_modeHint).color = new Color(0.75f, 0.78f, 0.82f, 0.82f);
			_alphaAutoCb = MyCheckBox.CreateCheckBox(28f, 202f, parent, "自动计算覆盖角 α(推荐,按星球半径适配)");
			Text linkedLabel = UIUtil.AddText(28f, 234f, parent, "手动覆盖角 α", 15, 176f, 28f, (TextAnchor)3);
			_alphaSlider = MySlider.CreateSlider(212f, 238f, parent, 38.05f, 30f, 60f, "F2", 280f, wholeNumbers: false, "°", 90f, linkedLabel);
			((Graphic)UIUtil.AddText(28f, 274f, parent, "—— 避让设置 ——", 15, 564f, 22f, (TextAnchor)3)).color = new Color(0.68f, 0.85f, 1f, 0.92f);
			Text linkedLabel2 = UIUtil.AddText(28f, 302f, parent, "建筑避让缓冲", 15, 176f, 28f, (TextAnchor)3);
			_blockInflateSlider = MySlider.CreateSlider(212f, 306f, parent, 1.5f, 0.5f, 4f, "F1", 280f, wholeNumbers: false, "°", 90f, linkedLabel2);
			_veinsCb = MyCheckBox.CreateCheckBox(28f, 338f, parent, "避开矿脉(不把护盾压在矿簇上)");
			Text linkedLabel3 = UIUtil.AddText(28f, 370f, parent, "矿脉避让缓冲", 15, 176f, 28f, (TextAnchor)3);
			_veinInflateSlider = MySlider.CreateSlider(212f, 374f, parent, 1.5f, 0.5f, 5f, "F1", 280f, wholeNumbers: false, "°", 90f, linkedLabel3);
			UIUtil.AddText(28f, 406f, parent, "黑雾避让", 15, 176f, 26f, (TextAnchor)3);
			string[] array = new string[4] { "无视", "仅地热坑", "黑雾建筑", "引怪范围" };
			DarkFogAvoidMode[] array2 = new DarkFogAvoidMode[4]
			{
				DarkFogAvoidMode.Ignore,
				DarkFogAvoidMode.CoreOnly,
				DarkFogAvoidMode.Buildings,
				DarkFogAvoidMode.AggroRange
			};
			(string, string)[] array3 = new(string, string)[4]
			{
				("无视黑雾", "求解与代拍均不避开黑雾建筑或地热坑,适合先拆光再铺或纯理论规划。"),
				("仅避核心/地热坑", "只避开黑雾基地核心与未填埋基地坑(为地热发电站留位),外围建筑不挡路。"),
				("避开黑雾建筑(默认)", "避开全部黑雾地面建筑与基地坑,求解与代拍均不重叠,允许贴近外围建盾。"),
				("避开引怪/射程范围", "避开基地实时警戒圈与炮塔射程并叠加安全余量,安全不引怪。")
			};
			_dfModeBtns = (UIButton[])(object)new UIButton[4];
			for (int i = 0; i < 4; i++)
			{
				DarkFogAvoidMode mode = array2[i];
				float x = 212f + (float)i * 92f;
				_dfModeBtns[i] = UIUtil.AddButton(x, 406f, 86f, parent, array[i], 13, (UnityAction)delegate
				{
					PluginConfig.DarkFogMode.Value = mode;
					UpdateDarkFogUI();
				}, 26f, array3[i].Item1, array3[i].Item2);
			}
			_darkFogHint = UIUtil.AddText(28f, 436f, parent, "", 13, 564f, 22f, (TextAnchor)0);
			((Graphic)_darkFogHint).color = new Color(0.75f, 0.78f, 0.82f, 0.85f);
			Text linkedLabel4 = UIUtil.AddText(28f, 462f, parent, "引怪安全余量", 15, 176f, 28f, (TextAnchor)3);
			_dfMarginSlider = MySlider.CreateSlider(212f, 466f, parent, 8f, 0f, 40f, "F0", 280f, wholeNumbers: false, "m", 90f, linkedLabel4);
			object obj = <>c.<>9__35_0;
			if (obj == null)
			{
				UnityAction val = delegate
				{
					Plugin.TryTrigger(place: false, asBlueprint: false);
				};
				<>c.<>9__35_0 = val;
				obj = (object)val;
			}
			_planBtn = UIUtil.AddButton(28f, 520f, 180f, parent, "计划", 17, (UnityAction?)obj, 34f, "仅计算计划", "只计算推荐护盾数量与坐标并写入日志,不在星球放置任何建筑。");
			object obj2 = <>c.<>9__35_1;
			if (obj2 == null)
			{
				UnityAction val2 = delegate
				{
					Plugin.TryTrigger(place: true, asBlueprint: false);
				};
				<>c.<>9__35_1 = val2;
				obj2 = (object)val2;
			}
			_placeBtn = UIUtil.AddButton(220f, 520f, 180f, parent, "代拍", 17, (UnityAction?)obj2, 34f, "计算并代拍(推荐补洞)", "按绝对坐标将护盾加入无人机预建造队列,已有护盾会自动避让计入。");
			object obj3 = <>c.<>9__35_2;
			if (obj3 == null)
			{
				UnityAction val3 = delegate
				{
					Plugin.TryTrigger(place: false, asBlueprint: true);
				};
				<>c.<>9__35_2 = val3;
				obj3 = (object)val3;
			}
			_blueprintBtn = UIUtil.AddButton(412f, 520f, 180f, parent, "蓝图", 17, (UnityAction?)obj3, 34f, "生成全球粘贴蓝图(仅全新铺设)", "打开游戏蓝图粘贴预览:请将光标放在赤道附近并保持 0° 旋转(勿按 R)。");
			object obj4 = <>c.<>9__35_3;
			if (obj4 == null)
			{
				UnityAction val4 = delegate
				{
					Plugin.RunDiagnostic();
				};
				<>c.<>9__35_3 = val4;
				obj4 = (object)val4;
			}
			_diagBtn = UIUtil.AddButton(28f, 564f, 80f, parent, "诊断", 14, (UnityAction?)obj4, 28f, "轻量实测诊断", "仅读取当前星球官方覆盖率、充能阶段与塔数摘要并显示在状态栏/日志;不修改剪贴板,不写入文件。");
			_debugCb = MyCheckBox.CreateCheckBox(120f, 565f, parent, "调试记录", 14);
			object obj5 = <>c.<>9__35_4;
			if (obj5 == null)
			{
				UnityAction val5 = delegate
				{
					Plugin.RunCopyDiagnosticSummary();
				};
				<>c.<>9__35_4 = val5;
				obj5 = (object)val5;
			}
			_copySummaryBtn = UIUtil.AddButton(224f, 564f, 176f, parent, "复制摘要 ~2KB", 13, (UnityAction?)obj5, 28f, "复制紧凑排障摘要(会覆盖剪贴板)", "注意:点击后会直接覆盖系统剪贴板!生成约 1.5~3 KB 的紧凑 Markdown 报告,可直接 Ctrl+V 贴入 GitHub Issue;不写入磁盘文件。需先勾选「调试记录」。");
			object obj6 = <>c.<>9__35_5;
			if (obj6 == null)
			{
				UnityAction val6 = delegate
				{
					Plugin.RunExportFullDiagnosticBundle();
				};
				<>c.<>9__35_5 = val6;
				obj6 = (object)val6;
			}
			_exportBundleBtn = UIUtil.AddButton(412f, 564f, 180f, parent, "导出完整包 ~20KB", 13, (UnityAction?)obj6, 28f, "导出完整复现包 (.zip,不改剪贴板)", "仅写入磁盘,不修改系统剪贴板。将 report.md 与压缩禁点快照 snapshot.json.gz 打包为单个 .zip,可直接拖拽上传 Issue 或供离线复跑。需先勾选「调试记录」。");
			((Graphic)UIUtil.AddText(28f, 602f, parent, "补洞请用「代拍」(蓝图仅适合空星赤道 0° 旋转)。悬停按钮可看详细提示;勾选「调试记录」可在求解时采集轨迹并解锁摘要/完整包导出。", 13, 564f, 44f, (TextAnchor)0)).color = new Color(0.7f, 0.72f, 0.76f, 0.75f);
			LoadFromConfig();
			RefreshState();
		}

		private void LoadFromConfig()
		{
			_fullCb.Checked = PluginConfig.FullShield.Value;
			_alphaAutoCb.Checked = PluginConfig.AlphaAuto.Value;
			_alphaSlider.Value = PluginConfig.AlphaDeg.Value;
			_blockInflateSlider.Value = PluginConfig.BlockInflateDeg.Value;
			_veinsCb.Checked = PluginConfig.BlockVeins.Value;
			_veinInflateSlider.Value = PluginConfig.VeinInflateDeg.Value;
			_dfMarginSlider.Value = PluginConfig.DarkFogAggroMarginM.Value;
			_debugCb.Checked = PluginConfig.DebugRecord.Value;
			_fullCb.OnClicked += delegate
			{
				PluginConfig.FullShield.Value = _fullCb.Checked;
				UpdateModeHint();
				UpdateAlphaDisplay();
			};
			_alphaAutoCb.OnClicked += delegate
			{
				PluginConfig.AlphaAuto.Value = _alphaAutoCb.Checked;
				UpdateModeHint();
				UpdateAlphaDisplay();
			};
			((UnityEvent<float>)(object)_alphaSlider.slider.onValueChanged).AddListener((UnityAction<float>)delegate
			{
				PluginConfig.AlphaDeg.Value = _alphaSlider.Value;
			});
			((UnityEvent<float>)(object)_blockInflateSlider.slider.onValueChanged).AddListener((UnityAction<float>)delegate
			{
				PluginConfig.BlockInflateDeg.Value = _blockInflateSlider.Value;
			});
			_veinsCb.OnClicked += delegate
			{
				PluginConfig.BlockVeins.Value = _veinsCb.Checked;
				_veinInflateSlider.SetEnable(_veinsCb.Checked);
			};
			((UnityEvent<float>)(object)_veinInflateSlider.slider.onValueChanged).AddListener((UnityAction<float>)delegate
			{
				PluginConfig.VeinInflateDeg.Value = _veinInflateSlider.Value;
			});
			((UnityEvent<float>)(object)_dfMarginSlider.slider.onValueChanged).AddListener((UnityAction<float>)delegate
			{
				PluginConfig.DarkFogAggroMarginM.Value = _dfMarginSlider.Value;
				UpdateDarkFogUI();
			});
			_debugCb.OnClicked += delegate
			{
				PluginConfig.DebugRecord.Value = _debugCb.Checked;
				RefreshState();
			};
			_veinInflateSlider.SetEnable(_veinsCb.Checked);
			UpdateModeHint();
			UpdateAlphaDisplay();
			UpdateDarkFogUI();
		}

		private void UpdateDarkFogUI()
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			if (_dfModeBtns == null || (Object)(object)_darkFogHint == (Object)null || (Object)(object)_dfMarginSlider == (Object)null)
			{
				return;
			}
			DarkFogAvoidMode value = PluginConfig.DarkFogMode.Value;
			int num = (int)value;
			for (int i = 0; i < _dfModeBtns.Length; i++)
			{
				UIButton val = _dfModeBtns[i];
				if (!((Object)(object)val == (Object)null))
				{
					bool flag = (val.highlighted = i == num);
					val.RefreshTransitionsImmediately();
					Transform obj = ((Component)val).transform.Find("button-text");
					Text val2 = ((obj != null) ? ((Component)obj).GetComponent<Text>() : null);
					if ((Object)(object)val2 != (Object)null)
					{
						((Graphic)val2).color = (flag ? new Color(1f, 0.88f, 0.45f, 1f) : new Color(0.72f, 0.76f, 0.82f, 0.78f));
					}
				}
			}
			bool flag2 = value == DarkFogAvoidMode.AggroRange;
			_dfMarginSlider.SetEnable(flag2);
			_dfMarginSlider.SetOverrideText(flag2 ? null : "仅引怪模式");
			Text darkFogHint = _darkFogHint;
			darkFogHint.text = value switch
			{
				DarkFogAvoidMode.Ignore => "当前状态:无视黑雾(允许叠放,适合先清理黑雾后再建造)", 
				DarkFogAvoidMode.CoreOnly => "当前状态:仅避基地核心与地热坑(保留地热发电站位置,外围不挡路)", 
				DarkFogAvoidMode.Buildings => "当前状态:避开全部黑雾建筑与地热坑(防重叠,允许贴外围建盾)", 
				DarkFogAvoidMode.AggroRange => $"当前状态:避开基地警戒与炮塔射程 + {PluginConfig.DarkFogAggroMarginM.Value:F0}m 安全余量", 
				_ => "", 
			};
		}

		private void UpdateAlphaDisplay()
		{
			if (!((Object)(object)_alphaSlider == (Object)null))
			{
				if (_alphaAutoCb.Checked)
				{
					_alphaSlider.SetEnable(on: false);
					double num = (_fullCb.Checked ? ShieldPlannerRunner.ComputeFullAlpha(GameMain.localPlanet) : 52.0);
					_alphaSlider.SetOverrideText($"自动 {num:F2}°");
				}
				else
				{
					_alphaSlider.SetEnable(on: true);
					_alphaSlider.SetOverrideText(null);
				}
			}
		}

		private void UpdateModeHint()
		{
			if (!((Object)(object)_modeHint == (Object)null))
			{
				if (!_alphaAutoCb.Checked)
				{
					_modeHint.text = "手动 α 已接管覆盖角;上方勾选仅决定初始布局种子(20/7),已有盾覆盖会自动计入。";
				}
				else if (_fullCb.Checked)
				{
					_modeHint.text = "满盾模式:已有 N 个护盾时新盾约 20-N 个;已有护盾覆盖会自动计入并避开。";
				}
				else
				{
					_modeHint.text = "防降落模式:7 盾为数学下限,已有盾靠近两极/赤道圈才能省盾,否则按需补洞。";
				}
			}
		}

		internal static void DestroyBaseObject()
		{
			if ((Object)(object)_baseObject != (Object)null)
			{
				Object.Destroy((Object)(object)_baseObject);
				_baseObject = null;
			}
		}

		public void OnPlanetChanged()
		{
			UpdateAlphaDisplay();
			RefreshState();
		}

		protected override void _OnUpdate()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			((ManualBehaviour)this)._OnUpdate();
			if (!Plugin.IsInPlayableGame())
			{
				((ManualBehaviour)this)._Close();
				return;
			}
			Transform transform = ((Component)this).transform;
			RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			if (val != null && val.sizeDelta != new Vector2(620f, 662f))
			{
				val.sizeDelta = new Vector2(620f, 662f);
			}
			if (VFInput.escape && !VFInput.inputing)
			{
				VFInput.UseEscape();
				((ManualBehaviour)this)._Close();
			}
			else
			{
				RefreshState();
			}
		}

		public void RefreshState()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Invalid comparison between Unknown and I4
			if (ShieldPlannerUI.IsBusy)
			{
				_statusText.text = $"状态:求解中… {Time.realtimeSinceStartup - ShieldPlannerUI.BusyStart:F0}s(游戏可正常操作)";
				SetPrimaryButtonsEnabled(on: false);
				RefreshExportButtons(planetValid: false, debugEnabled: false);
				return;
			}
			PlanetData localPlanet = GameMain.localPlanet;
			if (localPlanet == null || (int)localPlanet.type == 5)
			{
				_statusText.text = ((localPlanet == null) ? "状态:当前位于太空/星系视图,操作按钮已禁用" : "状态:气态行星无法放置护盾,操作按钮已禁用");
				SetPrimaryButtonsEnabled(on: false);
				RefreshExportButtons(planetValid: false, debugEnabled: false);
			}
			else
			{
				_statusText.text = ShieldPlannerUI.StatusText;
				SetPrimaryButtonsEnabled(on: true);
				RefreshExportButtons(planetValid: true, PluginConfig.DebugRecord.Value);
			}
		}

		private void RefreshExportButtons(bool planetValid, bool debugEnabled)
		{
			int num = (planetValid ? DiagnosticReportBuilder.EstimateFullBundleKB(GameMain.localPlanet) : 0);
			if (num != _lastEstKB)
			{
				_lastEstKB = num;
				Transform obj = ((Component)_exportBundleBtn).transform.Find("button-text");
				Text val = ((obj != null) ? ((Component)obj).GetComponent<Text>() : null);
				if ((Object)(object)val != (Object)null)
				{
					val.text = ((num > 0) ? $"导出完整包 ~{num}KB" : "导出完整包");
				}
				_exportBundleBtn.tips.tipText = "仅写入磁盘,不修改系统剪贴板。将 report.md 与压缩禁点快照 snapshot.json.gz 打包为单个 .zip" + ((num > 0) ? $"(当前星球预估约 {num} KB)" : "") + ",可直接拖拽上传 Issue 或供离线复跑。需先勾选「调试记录」。";
				_exportBundleBtn.UpdateTip();
			}
			bool flag = planetValid && debugEnabled;
			SetButtonEnabled(_copySummaryBtn, flag);
			SetButtonEnabled(_exportBundleBtn, flag);
		}

		private void SetPrimaryButtonsEnabled(bool on)
		{
			SetButtonEnabled(_planBtn, on);
			SetButtonEnabled(_placeBtn, on);
			SetButtonEnabled(_blueprintBtn, on);
			SetButtonEnabled(_diagBtn, on);
		}

		private static void SetButtonEnabled(UIButton btn, bool on)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			((Behaviour)btn).enabled = true;
			((Selectable)btn.button).interactable = on;
			Transform obj = ((Component)btn).transform.Find("button-text");
			Text val = ((obj != null) ? ((Component)obj).GetComponent<Text>() : null);
			if ((Object)(object)val != (Object)null)
			{
				((Graphic)val).color = (on ? new Color(1f, 1f, 1f, 0.9f) : new Color(0.6f, 0.6f, 0.6f, 0.45f));
			}
		}
	}
	public class Banner : MonoBehaviour
	{
		private Text _text;

		private float _until;

		private BannerTag _tag;

		public bool IsShowingTag(BannerTag tag)
		{
			if (((Component)this).gameObject.activeSelf)
			{
				return _tag == tag;
			}
			return false;
		}

		public static Banner Create()
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: 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_0105: 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)
			Text val = Object.Instantiate<Text>(UIRoot.instance.uiGame.assemblerWindow.stateText);
			((Object)((Component)val).gameObject).name = "sp-banner";
			Localizer component = ((Component)val).GetComponent<Localizer>();
			if ((Object)(object)component != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)component);
			}
			UIUtil.StripTextFx(((Component)val).gameObject);
			UIUtil.ApplyTextFont(val, 24);
			val.text = "";
			val.fontSize = 24;
			((Graphic)val).color = new Color(1f, 0.85f, 0.5f, 1f);
			val.alignment = (TextAnchor)1;
			val.horizontalOverflow = (HorizontalWrapMode)0;
			val.verticalOverflow = (VerticalWrapMode)1;
			RectTransform rectTransform = ((Graphic)val).rectTransform;
			((Transform)rectTransform).SetParent(((Component)UIRoot.instance.uiGame).transform.parent, false);
			rectTransform.anchorMin = new Vector2(0.5f, 1f);
			rectTransform.anchorMax = new Vector2(0.5f, 1f);
			rectTransform.pivot = new Vector2(0.5f, 1f);
			rectTransform.anchoredPosition = new Vector2(0f, -70f);
			rectTransform.sizeDelta = new Vector2(1200f, 80f);
			Banner banner = ((Component)val).gameObject.AddComponent<Banner>();
			banner._text = val;
			((Component)val).gameObject.SetActive(false);
			return banner;
		}

		public void Show(string text, float seconds, BannerTag tag)
		{
			_tag = tag;
			_text.text = text;
			_until = Time.realtimeSinceStartup + seconds;
			((Component)this).gameObject.SetActive(true);
		}

		public void Hide()
		{
			_tag = BannerTag.General;
			if ((Object)(object)_text != (Object)null)
			{
				_text.text = "";
			}
			if (((Component)this).gameObject.activeSelf)
			{
				((Component)this).gameObject.SetActive(false);
			}
		}

		private void Update()
		{
			if (!Plugin.IsInPlayableGame() || Time.realtimeSinceStartup >= _until)
			{
				Hide();
			}
		}
	}
	public static class UIUtil
	{
		private static readonly Dictionary<int, Font> FontCache = new Dictionary<int, Font>();

		internal static void ApplyTextFont(Text text, int fontSize)
		{
			if (!FontCache.TryGetValue(fontSize, out Font value))
			{
				value = Font.CreateDynamicFontFromOSFont("Microsoft YaHei", fontSize);
				FontCache.Add(fontSize, value);
			}
			text.font = value;
			((Graphic)text).material = value.material;
		}

		internal static void StripTextFx(GameObject go)
		{
			if (!((Object)(object)go == (Object)null))
			{
				Shadow[] components = go.GetComponents<Shadow>();
				for (int i = 0; i < components.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)components[i]);
				}
				Outline[] components2 = go.GetComponents<Outline>();
				for (int i = 0; i < components2.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)components2[i]);
				}
				PositionAsUV1[] components3 = go.GetComponents<PositionAsUV1>();
				for (int i = 0; i < components3.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)components3[i]);
				}
			}
		}

		public static RectTransform NormalizeTopLeft(Component cmp, float left, float top, Transform? parent = null)
		{
			//IL_002d: 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_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: 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 (val == null)
			{
				return null;
			}
			if ((Object)(object)parent != (Object)null)
			{
				((Transform)val).SetParent(parent, false);
			}
			val.anchorMax = new Vector2(0f, 1f);
			val.anchorMin = new Vector2(0f, 1f);
			val.pivot = new Vector2(0f, 1f);
			val.anchoredPosition3D = new Vector3(left, 0f - top, 0f);
			return val;
		}

		public static Text AddText(float x, float y, RectTransform parent, string label, int fontSize = 14, float maxWidth = 0f, float height = 0f, TextAnchor alignment = (TextAnchor)3)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: 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)
			Text val = Object.Instantiate<Text>(UIRoot.instance.uiGame.assemblerWindow.stateText);
			((Object)((Component)val).gameObject).name = "sp-label";
			Localizer component = ((Component)val).GetComponent<Localizer>();
			if ((Object)(object)component != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)component);
			}
			StripTextFx(((Component)val).gameObject);
			ApplyTextFont(val, fontSize);
			val.text = label;
			((Graphic)val).color = new Color(0.9f, 0.9f, 0.9f, 0.78f);
			val.alignment = alignment;
			val.fontSize = fontSize;
			if (maxWidth > 0f)
			{
				val.horizontalOverflow = (HorizontalWrapMode)0;
				val.verticalOverflow = (VerticalWrapMode)1;
				((Graphic)val).rectTransform.sizeDelta = new Vector2(maxWidth, (height > 0f) ? height : (val.preferredHeight + 6f));
			}
			else
			{
				val.horizontalOverflow = (HorizontalWrapMode)1;
				val.verticalOverflow = (VerticalWrapMode)1;
				((Graphic)val).rectTransform.sizeDelta = new Vector2(val.preferredWidth + 8f, (height > 0f) ? height : (val.preferredHeight + 4f));
			}
			NormalizeTopLeft((Component)(object)val, x, y, (Transform?)(object)parent);
			return val;
		}

		public static UIButton AddButton(float x, float y, float width, RectTransform parent, string text, int fontSize = 16, UnityAction? onClick = null, float height = 34f, string? tipTitle = null, string? tipText = null)
		{
			//IL_003b: 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_00c0: 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)
			UIButton val = Object.Instantiate<UIButton>(UIRoot.instance.uiGame.statWindow.performancePanelUI.cpuActiveButton);
			((Object)((Component)val).gameObject).name = "sp-button";
			NormalizeTopLeft((Component)(object)val, x, y, (Transform?)(object)parent).sizeDelta = new Vector2(width, height);
			Transform obj = ((Component)val).transform.Find("button-text");
			Localizer val2 = ((obj != null) ? ((Component)obj).GetComponent<Localizer>() : null);
			if ((Object)(object)val2 != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)val2);
			}
			Text val3 = ((obj != null) ? ((Component)obj).GetComponent<Text>() : null);
			if ((Object)(object)val3 != (Object)null)
			{
				StripTextFx(((Component)val3).gameObject);
				ApplyTextFont(val3, fontSize);
				val3.text = text;
				val3.fontSize = fontSize;
				((Graphic)val3).color = new Color(1f, 1f, 1f, 0.9f);
				val3.fontStyle = (FontStyle)0;
				val3.alignment = (TextAnchor)4;
			}
			val.tips = default(TipSettings);
			if (!string.IsNullOrEmpty(tipTitle) || !string.IsNullOrEmpty(tipText))
			{
				val.tips.topLevel = true;
				val.tips.corner = 2;
				val.tips.width = 280;
				val.tips.delay = 0.2f;
				val.tips.offset = new Vector2(0f, 10f);
				val.tips.tipTitle = tipTitle ?? text;
				val.tips.tipText = tipText ?? "";
				val.UpdateTip();
			}
			((UnityEventBase)val.button.onClick).RemoveAllListeners();
			if (onClick != null)
			{
				((UnityEvent)val.button.onClick).AddListener(onClick);
			}
			return val;
		}
	}
}
namespace DSP.ShieldPlanner.Placement
{
	public static class BlueprintBuilder
	{
		public static BlueprintData? Build(PlanetData planet, List<SVec3> dirs, List<SVec3>? existingDirs = null)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: 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_00f8: 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_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Expected O, but got Unknown
			//IL_011c: 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_0128: 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_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Expected O, but got Unknown
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Expected O, but got Unknown
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: 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_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Expected O, but got Unknown
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: 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_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Expected O, but got Unknown
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0292: Unknown result type (might be due to invalid IL or missing references)
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Expected O, but got Unknown
			//IL_0387: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ba: Expected O, but got Unknown
			//IL_035a: Unknown result type (might be due to invalid IL or missing references)
			if (dirs.Count == 0)
			{
				return null;
			}
			BlueprintData bp = BlueprintData.CreateNew();
			bp.shortDesc = $"护盾×{dirs.Count} (DSP ShieldPlanner)";
			bp.author = "DSP ShieldPlanner";
			bp.desc = "自动生成:全球护盾放置(DSP ShieldPlanner)";
			bp.icon0 = 3008;
			bp.layout = (EIconLayout)10;
			bp.cursorOffset_x = 478;
			bp.cursorOffset_y = 80;
			bp.dragBoxSize_x = 956;
			bp.dragBoxSize_y = 315;
			bp.cursorTargetArea = 3;
			bp.primaryAreaIdx = 3;
			bp.areas = (BlueprintArea[])(object)new BlueprintArea[7]
			{
				new BlueprintArea
				{
					index = 0,
					parentIndex = 1,
					tropicAnchor = 3,
					areaSegments = 100,
					anchorLocalOffsetX = 3,
					anchorLocalOffsetY = -2,
					width = 479,
					height = 2
				},
				new BlueprintArea
				{
					index = 1,
					parentIndex = 2,
					tropicAnchor = 0,
					areaSegments = 120,
					anchorLocalOffsetX = 0,
					anchorLocalOffsetY = -25,
					width = 574,
					height = 25
				},
				new BlueprintArea
				{
					index = 2,
					parentIndex = 3,
					tropicAnchor = 0,
					areaSegments = 160,
					anchorLocalOffsetX = 0,
					anchorLocalOffsetY = -50,
					width = 765,
					height = 50
				},
				new BlueprintArea
				{
					index = 3,
					parentIndex = -1,
					tropicAnchor = 0,
					areaSegments = 200,
					anchorLocalOffsetX = 0,
					anchorLocalOffsetY = 0,
					width = 956,
					height = 161
				},
				new BlueprintArea
				{
					index = 4,
					parentIndex = 3,
					tropicAnchor = 0,
					areaSegments = 160,
					anchorLocalOffsetX = 0,
					anchorLocalOffsetY = 161,
					width = 765,
					height = 50
				},
				new BlueprintArea
				{
					index = 5,
					parentIndex = 4,
					tropicAnchor = 0,
					areaSegments = 120,
					anchorLocalOffsetX = 0,
					anchorLocalOffsetY = 50,
					width = 574,
					height = 25
				},
				new BlueprintArea
				{
					index = 6,
					parentIndex = 5,
					tropicAnchor = 3,
					areaSegments = 100,
					anchorLocalOffsetX = 3,
					anchorLocalOffsetY = 25,
					width = 479,
					height = 2
				}
			};
			short model = ShieldModels.GetModelIndex(planet.factory, 3008);
			int num = existingDirs?.Count ?? 0;
			int count = dirs.Count;
			bp.buildings = (BlueprintBuilding[])(object)new BlueprintBuilding[num + count];
			double[] anchorLat = new double[7] { -59.7, -58.9, -49.4, -30.4, 30.8, 49.8, 59.3 };
			int[] areaH = new int[7] { 2, 25, 50, 161, 50, 25, 2 };
			int bi = 0;
			if (existingDirs != null)
			{
				foreach (SVec3 existingDir in existingDirs)
				{
					AddBuilding(existingDir);
				}
			}
			for (int i = 0; i < count; i++)
			{
				AddBuilding(dirs[i]);
			}
			bp.reformData = new BPReformData
			{
				rects = (BPReformRect[])(object)new BPReformRect[0]
			};
			return bp;
			void AddBuilding(SVec3 d)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: 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_0118: Unknown result type (might be due to invalid IL or missing references)
				//IL_0120: 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_0131: 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_0147: Unknown result type (might be due to invalid IL or missing references)
				//IL_0152: Unknown result type (might be due to invalid IL or missing references)
				//IL_015d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0168: 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_0194: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a1: Expected O, but got Unknown
				double num2 = d.LatitudeDeg();
				double num3 = d.LongitudeDeg();
				if (num3 < 0.0)
				{
					num3 += 360.0;
				}
				int num4 = ((!(num2 < -58.9)) ? ((num2 < -49.4) ? 1 : ((num2 < -30.4) ? 2 : ((num2 < 30.8) ? 3 : ((num2 < 49.8) ? 4 : ((!(num2 < 59.3)) ? 6 : 5))))) : 0);
				double val = (num2 - anchorLat[num4]) / 0.38;
				val = Math.Max(0.0, Math.Min((double)areaH[num4] - 0.5, val));
				double num5 = num3 / 360.0 * (double)bp.areas[num4].width;
				bp.buildings[bi++] = new BlueprintBuilding
				{
					index = bi - 1,
					areaIndex = (sbyte)num4,
					localOffset_x = (float)num5,
					localOffset_y = (float)val,
					localOffset_z = 0f,
					localOffset_x2 = 0f,
					localOffset_y2 = 0f,
					localOffset_z2 = 0f,
					pitch = 0f,
					yaw = ((num4 >= 5) ? 180f : 0f),
					tilt = 0f,
					itemId = 3008,
					modelIndex = model
				};
			}
		}
	}
	internal static class SvDirExt
	{
		public static double LatitudeDeg(this SVec3 v)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Math.Asin(Mathf.Clamp(v.Z / ((SVec3)(ref v)).Length(), -1f, 1f)) * 57.295780181884766;
		}

		public static double LongitudeDeg(this SVec3 v)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			double num = Math.Atan2(v.Y, v.X) * 57.295780181884766;
			if (num < 0.0)
			{
				num += 360.0;
			}
			return num;
		}
	}
	public static class PrebuildPlacer
	{
		public static bool IsClearForShield(PlanetFactory factory, Vector3 gridPos, float minDist = 2.6f, DarkFogAvoidMode darkFogMode = DarkFogAvoidMode.Ignore, float darkFogAggroMarginM = 8f)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type

plugins/DSP.ShieldPlanner.Solver.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 System.Threading;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("DSP.ShieldPlanner.Solver")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+76a32125039c0a53a32885b22dcdbb6038068fb0")]
[assembly: AssemblyProduct("DSP.ShieldPlanner.Solver")]
[assembly: AssemblyTitle("DSP.ShieldPlanner.Solver")]
[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]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DSP.ShieldPlanner.Solver
{
	public sealed class SimReport
	{
		public double FillRatio;

		public double DefenceRatio;

		public long FillSum;

		public long DefSum;

		public long MaxSum;

		public int WorstFillIdx = -1;

		public float WorstFillVal = 1f;

		public int WorstDefIdx = -1;

		public float WorstDefVal = 1f;

		public List<int> DeficientFillIndices = new List<int>();

		public List<int> DeficientDefIndices = new List<int>();
	}
	public sealed class RefineResult
	{
		public List<SVec3> Dirs = new List<SVec3>();

		public SimReport FinalReport = new SimReport();

		public int AddedCount;

		public int PrunedCount;
	}
	public sealed class RedundancyReport
	{
		public double[] FillDrops = Array.Empty<double>();

		public double[] DefDrops = Array.Empty<double>();

		public List<int> RedundantIndices = new List<int>();
	}
	public static class ATFieldSim
	{
		private const float FieldAltitude = 60.8f;

		private const float TowerOffset = 0.2f;

		private const float TangentStep = 12.5f;

		public static float EvalPoint(float px, float py, float pz, SVec3[] genPositions, float invHalfR, float k)
		{
			float num = 0f;
			for (int i = 0; i < genPositions.Length; i++)
			{
				SVec3 sVec = genPositions[i];
				float num2 = px - sVec.X;
				float num3 = py - sVec.Y;
				float num4 = pz - sVec.Z;
				float num5 = (float)Math.Sqrt(num2 * num2 + num3 * num3 + num4 * num4) * invHalfR;
				float num6 = ((num5 < 0f) ? 0f : ((num5 > 1f) ? 1f : num5));
				float num7 = 1f - num5 * num5;
				float num8 = 1f - num5;
				float num9 = num7 + num6 * (num8 - num7);
				float num10 = 0.5f - 0.5f * (num9 - num) / k;
				if (num10 < 0f)
				{
					num10 = 0f;
				}
				else if (num10 > 1f)
				{
					num10 = 1f;
				}
				num = num9 + num10 * (num - num9) + k * num10 * (1f - num10);
			}
			float num11 = ((num < 0f) ? 0f : ((num > 1f) ? 1f : num));
			num11 = num11 * num11 * (3f - 2f * num11);
			return num11 * num11 * num11;
		}

		public static void EvaluateVertex(SVec3 n, SVec3[] genPositions, float planetRadius, float invHalfR, float k, out int fillInt, out int defInt, out float fillF0, out float defF)
		{
			float num3;
			float num4;
			float num5;
			if (Math.Abs(n.Y) < 0.999999f)
			{
				float num = (float)Math.Sqrt(n.Z * n.Z + n.X * n.X);
				float num2 = ((num > 1E-08f) ? (1f / num) : 1f);
				num3 = (0f - n.Z) * num2;
				num4 = 0f;
				num5 = n.X * num2;
			}
			else
			{
				float num6 = (float)Math.Sqrt(n.Y * n.Y + n.X * n.X);
				float num7 = ((num6 > 1E-08f) ? (1f / num6) : 1f);
				num3 = n.Y * num7;
				num4 = (0f - n.X) * num7;
				num5 = 0f;
			}
			float num8 = n.Y * num5 - n.Z * num4;
			float num9 = n.Z * num3 - n.X * num5;
			float num10 = n.X * num4 - n.Y * num3;
			float num11 = (float)Math.Sqrt(num8 * num8 + num9 * num9 + num10 * num10);
			if (num11 > 1E-08f)
			{
				float num12 = 1f / num11;
				num8 *= num12;
				num9 *= num12;
				num10 *= num12;
			}
			float num13 = n.X * planetRadius;
			float num14 = n.Y * planetRadius;
			float num15 = n.Z * planetRadius;
			float num16 = EvalPoint(num13, num14, num15, genPositions, invHalfR, k);
			float num17 = EvalPoint(num13 - 12.5f * num3, num14 - 12.5f * num4, num15 - 12.5f * num5, genPositions, invHalfR, k);
			float num18 = EvalPoint(num13 + 12.5f * num3, num14 + 12.5f * num4, num15 + 12.5f * num5, genPositions, invHalfR, k);
			float num19 = EvalPoint(num13 - 12.5f * num8, num14 - 12.5f * num9, num15 - 12.5f * num10, genPositions, invHalfR, k);
			float num20 = EvalPoint(num13 + 12.5f * num8, num14 + 12.5f * num9, num15 + 12.5f * num10, genPositions, invHalfR, k);
			float num21 = 0.5f * num16 + 0.125f * (num17 + num18 + num19 + num20);
			fillF0 = num21 * 1.005f - 0.0025f;
			if (fillF0 < 0f)
			{
				fillF0 = 0f;
			}
			else if (fillF0 > 1f)
			{
				fillF0 = 1f;
			}
			fillInt = (int)(fillF0 * 1000f + 0.5f);
			float num22 = planetRadius + 60.8f * num16;
			if (num22 < planetRadius + 4.5f)
			{
				num22 *= 0.96f;
			}
			defF = (num22 - (planetRadius - 5f)) * 0.1f;
			if (defF < 0f)
			{
				defF = 0f;
			}
			else if (defF > 1f)
			{
				defF = 1f;
			}
			defInt = (int)(defF * 1000f + 0.5f);
		}

		private static SVec3[] ToGenPositions(IReadOnlyList<SVec3> unitGameDirs, float genRadius)
		{
			SVec3[] array = new SVec3[unitGameDirs.Count];
			for (int i = 0; i < unitGameDirs.Count; i++)
			{
				SVec3 sVec = SVec3.Normalize(unitGameDirs[i]);
				array[i] = new SVec3(sVec.X * genRadius, sVec.Y * genRadius, sVec.Z * genRadius);
			}
			return array;
		}

		public static SimReport Evaluate(IReadOnlyList<SVec3> unitGameDirs, SVec3[] meshGameVerts, float planetRadius = 200f, float k = 2.1f, CancellationToken ct = default(CancellationToken))
		{
			SimReport simReport = new SimReport();
			if (meshGameVerts.Length == 0)
			{
				return simReport;
			}
			float genRadius = planetRadius + 0.2f;
			float invHalfR = 1f / (0.5f * planetRadius);
			float k2 = ((k > 0.01f) ? k : 2.1f);
			SVec3[] array = ToGenPositions(unitGameDirs, genRadius);
			long num = (simReport.MaxSum = (long)meshGameVerts.Length * 1000L);
			if (array.Length == 0)
			{
				simReport.WorstFillIdx = 0;
				simReport.WorstFillVal = 0f;
				simReport.WorstDefIdx = 0;
				simReport.WorstDefVal = 0f;
				for (int i = 0; i < meshGameVerts.Length; i++)
				{
					simReport.DeficientFillIndices.Add(i);
					simReport.DeficientDefIndices.Add(i);
				}
				return simReport;
			}
			long num2 = 0L;
			long num3 = 0L;
			for (int j = 0; j < meshGameVerts.Length; j++)
			{
				if ((j & 0xFF) == 0)
				{
					ct.ThrowIfCancellationRequested();
				}
				EvaluateVertex(meshGameVerts[j], array, planetRadius, invHalfR, k2, out var fillInt, out var defInt, out var fillF, out var defF);
				num2 += fillInt;
				num3 += defInt;
				if (fillInt < 1000)
				{
					simReport.DeficientFillIndices.Add(j);
				}
				if (defInt < 1000)
				{
					simReport.DeficientDefIndices.Add(j);
				}
				if (fillF < simReport.WorstFillVal)
				{
					simReport.WorstFillVal = fillF;
					simReport.WorstFillIdx = j;
				}
				if (defF < simReport.WorstDefVal)
				{
					simReport.WorstDefVal = defF;
					simReport.WorstDefIdx = j;
				}
			}
			simReport.FillSum = num2;
			simReport.DefSum = num3;
			simReport.FillRatio = (double)num2 / (double)num;
			simReport.DefenceRatio = (double)num3 / (double)num;
			return simReport;
		}

		public static RefineResult RefineAndPrune(List<SVec3> chosenGameDirs, SVec3[] initialGameDirs, SVec3[] candGameDirs, SVec3[] meshGameVerts, bool fullShield, float planetRadius = 200f, float k = 2.1f, int maxPatch = 12, CancellationToken ct = default(CancellationToken))
		{
			List<SVec3> list = new List<SVec3>(chosenGameDirs.Count);
			foreach (SVec3 chosenGameDir in chosenGameDirs)
			{
				list.Add(SVec3.Normalize(chosenGameDir));
			}
			if (meshGameVerts.Length == 0)
			{
				return new RefineResult
				{
					Dirs = list,
					FinalReport = new SimReport()
				};
			}
			float k2 = ((k > 0.01f) ? k : 2.1f);
			float num = planetRadius + 0.2f;
			float invHalfR = 1f / (0.5f * planetRadius);
			int num2 = 0;
			SphereBucketIndex sphereBucketIndex = ((candGameDirs.Length != 0) ? new SphereBucketIndex(candGameDirs) : null);
			for (int i = 0; i < maxPatch; i++)
			{
				if (sphereBucketIndex == null)
				{
					break;
				}
				ct.ThrowIfCancellationRequested();
				List<SVec3> unitGameDirs = BuildCombined(list);
				SimReport simReport = Evaluate(unitGameDirs, meshGameVerts, planetRadius, k2, ct);
				if (fullShield ? (simReport.FillSum >= simReport.MaxSum) : (simReport.DefSum >= simReport.MaxSum))
				{
					break;
				}
				List<int> list2 = (fullShield ? simReport.DeficientFillIndices : simReport.DeficientDefIndices);
				int num3 = (fullShield ? simReport.WorstFillIdx : simReport.WorstDefIdx);
				if (num3 < 0 || list2.Count == 0)
				{
					break;
				}
				SVec3 sVec = meshGameVerts[num3];
				List<int> list3 = sphereBucketIndex.Query(sVec, 42.0);
				if (list3.Count == 0)
				{
					break;
				}
				List<(float, SVec3)> list4 = new List<(float, SVec3)>();
				foreach (int item in list3)
				{
					SVec3 sVec2 = candGameDirs[item];
					bool flag = false;
					for (int j = 0; j < initialGameDirs.Length; j++)
					{
						if (SphereMath.AngleDeg(sVec2, initialGameDirs[j]) < 3.0)
						{
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						for (int l = 0; l < list.Count; l++)
						{
							if (SphereMath.AngleDeg(sVec2, list[l]) < 3.0)
							{
								flag = true;
								break;
							}
						}
					}
					if (!flag)
					{
						list4.Add((SVec3.DistanceSquared(sVec2, sVec), sVec2));
					}
				}
				if (list4.Count == 0)
				{
					break;
				}
				list4.Sort(((float dist2, SVec3 dir) a, (float dist2, SVec3 dir) b) => a.dist2.CompareTo(b.dist2));
				List<SVec3> list5 = new List<SVec3>(48);
				int num4 = Math.Min(24, list4.Count);
				for (int num5 = 0; num5 < num4; num5++)
				{
					list5.Add(list4[num5].Item2);
				}
				if (list4.Count > num4)
				{
					int num6 = list4.Count - num4;
					int num7 = Math.Min(24, num6);
					for (int num8 = 0; num8 < num7; num8++)
					{
						int index = num4 + (int)((long)num8 * (long)num6 / num7);
						list5.Add(list4[index].Item2);
					}
				}
				SVec3[] array = ToGenPositions(unitGameDirs, num);
				long num9 = 0L;
				double num10 = 0.0;
				foreach (int item2 in list2)
				{
					EvaluateVertex(meshGameVerts[item2], array, planetRadius, invHalfR, k2, out var fillInt, out var defInt, out var fillF, out var defF);
					num9 += (fullShield ? fillInt : defInt);
					num10 += (double)(fullShield ? fillF : defF);
				}
				SVec3? sVec3 = null;
				long num11 = num9;
				double num12 = num10;
				SVec3[] array2 = new SVec3[array.Length + 1];
				Array.Copy(array, array2, array.Length);
				foreach (SVec3 item3 in list5)
				{
					ct.ThrowIfCancellationRequested();
					SVec3 value = SVec3.Normalize(item3);
					array2[array.Length] = new SVec3(value.X * num, value.Y * num, value.Z * num);
					long num13 = 0L;
					double num14 = 0.0;
					foreach (int item4 in list2)
					{
						EvaluateVertex(meshGameVerts[item4], array2, planetRadius, invHalfR, k2, out var fillInt2, out var defInt2, out var fillF2, out var defF2);
						num13 += (fullShield ? fillInt2 : defInt2);
						num14 += (double)(fullShield ? fillF2 : defF2);
					}
					if (num13 > num11 || (num13 == num11 && num14 > num12 + 0.0001))
					{
						num11 = num13;
						num12 = num14;
						sVec3 = value;
					}
				}
				if (!sVec3.HasValue || (num11 <= num9 && num12 <= num10 + 0.0001))
				{
					break;
				}
				list.Add(sVec3.Value);
				num2++;
			}
			SimReport simReport2 = Evaluate(BuildCombined(list), meshGameVerts, planetRadius, k2, ct);
			long fillSum = simReport2.FillSum;
			long defSum = simReport2.DefSum;
			int num15 = 0;
			bool flag2 = true;
			while (flag2 && list.Count > 0)
			{
				flag2 = false;
				for (int num16 = list.Count - 1; num16 >= 0; num16--)
				{
					ct.ThrowIfCancellationRequested();
					SimReport simReport3 = Evaluate(BuildCombined(list, num16), meshGameVerts, planetRadius, k2, ct);
					bool num17;
					if (!fullShield)
					{
						num17 = simReport3.DefSum >= defSum;
					}
					else
					{
						if (simReport3.FillSum < fillSum)
						{
							continue;
						}
						num17 = simReport3.DefSum >= defSum;
					}
					if (num17)
					{
						list.RemoveAt(num16);
						num15++;
						flag2 = true;
					}
				}
			}
			SimReport finalReport = Evaluate(BuildCombined(list), meshGameVerts, planetRadius, k2, ct);
			return new RefineResult
			{
				Dirs = list,
				FinalReport = finalReport,
				AddedCount = num2,
				PrunedCount = num15
			};
			List<SVec3> BuildCombined(List<SVec3> curChosen, int skipIdx = -1)
			{
				List<SVec3> list6 = new List<SVec3>(initialGameDirs.Length + curChosen.Count);
				for (int m = 0; m < initialGameDirs.Length; m++)
				{
					list6.Add(initialGameDirs[m]);
				}
				for (int n = 0; n < curChosen.Count; n++)
				{
					if (n != skipIdx)
					{
						list6.Add(curChosen[n]);
					}
				}
				return list6;
			}
		}

		public static RedundancyReport FindRedundantTowers(IReadOnlyList<SVec3> allGameDirs, SVec3[] meshGameVerts, float planetRadius = 200f, float k = 2.1f)
		{
			int count = allGameDirs.Count;
			RedundancyReport redundancyReport = new RedundancyReport
			{
				FillDrops = new double[count],
				DefDrops = new double[count]
			};
			if (count == 0 || meshGameVerts.Length == 0)
			{
				return redundancyReport;
			}
			SimReport simReport = Evaluate(allGameDirs, meshGameVerts, planetRadius, k);
			List<SVec3> list = new List<SVec3>(count - 1);
			for (int i = 0; i < count; i++)
			{
				list.Clear();
				for (int j = 0; j < count; j++)
				{
					if (j != i)
					{
						list.Add(allGameDirs[j]);
					}
				}
				SimReport simReport2 = Evaluate(list, meshGameVerts, planetRadius, k);
				double num = Math.Max(0.0, simReport.FillRatio - simReport2.FillRatio);
				double num2 = Math.Max(0.0, simReport.DefenceRatio - simReport2.DefenceRatio);
				redundancyReport.FillDrops[i] = num;
				redundancyReport.DefDrops[i] = num2;
				if (num <= 1E-06 && num2 <= 1E-06)
				{
					redundancyReport.RedundantIndices.Add(i);
				}
			}
			return redundancyReport;
		}
	}
	public readonly struct BlockedZone
	{
		public readonly SVec3 Dir;

		public readonly double RadiusDeg;

		public BlockedZone(SVec3 dir, double radiusDeg)
		{
			Dir = dir;
			RadiusDeg = radiusDeg;
		}
	}
	public sealed class CoverResult
	{
		public List<int> Chosen = new List<int>();

		public double Coverage;

		public List<SVec3> ChosenDirs = new List<SVec3>();

		public int DebugSkippedSeeds;

		public SVec3[] DebugHoles = Array.Empty<SVec3>();
	}
	public static class SphereCoverSolver
	{
		private static int Words(int sampleCount)
		{
			return sampleCount + 63 >> 6;
		}

		private static int PopCount(ulong x)
		{
			x -= (x >> 1) & 0x5555555555555555L;
			x = (x & 0x3333333333333333L) + ((x >> 2) & 0x3333333333333333L);
			x = (x + (x >> 4)) & 0xF0F0F0F0F0F0F0FL;
			return (int)(x * 72340172838076673L >> 56);
		}

		public static CoverResult Solve(SVec3[] candidates, SVec3[] samples, double alphaDeg, string? seedName = null, double seedRepairDeg = 8.0, SVec3[]? initialDirs = null, CancellationToken ct = default(CancellationToken))
		{
			int words = Words(samples.Length);
			SphereBucketIndex sphereBucketIndex = new SphereBucketIndex(samples, 3);
			ulong[] masks = new ulong[candidates.Length * words];
			List<int> list = new List<int>();
			for (int i = 0; i < candidates.Length; i++)
			{
				if ((i & 0xFF) == 0)
				{
					ct.ThrowIfCancellationRequested();
				}
				list.Clear();
				sphereBucketIndex.QueryInto(candidates[i], alphaDeg, list);
				int num = i * words;
				foreach (int item in list)
				{
					masks[num + (item >> 6)] |= (ulong)(1L << item);
				}
			}
			ulong[] uncovered = new ulong[words];
			for (int j = 0; j < words; j++)
			{
				uncovered[j] = ulong.MaxValue;
			}
			int num2 = samples.Length & 0x3F;
			if (num2 != 0)
			{
				uncovered[words - 1] &= (ulong)((1L << num2) - 1);
			}
			List<int> list2 = new List<int>();
			ulong[] array = new ulong[words];
			ulong[] array2 = new ulong[words];
			SVec3[] array3;
			if (initialDirs != null && initialDirs.Length != 0)
			{
				SphereBucketIndex sphereBucketIndex2 = new SphereBucketIndex(samples);
				List<int> list3 = new List<int>();
				array3 = initialDirs;
				foreach (SVec3 center in array3)
				{
					ct.ThrowIfCancellationRequested();
					list3.Clear();
					sphereBucketIndex2.QueryInto(center, alphaDeg, list3);
					foreach (int item2 in list3)
					{
						int num3 = item2 >> 6;
						ulong num4 = (ulong)(1L << item2);
						array2[num3] |= num4;
						array[num3] |= num4;
						uncovered[num3] &= ~num4;
					}
				}
			}
			int num5 = 0;
			SVec3[] array4;
			SphereBucketIndex sphereBucketIndex3;
			SphereBucketIndex sphereBucketIndex4;
			switch (seedName)
			{
			case "7":
				array3 = Seeds.Seven();
				goto IL_027a;
			case "8":
				array3 = Seeds.Eight();
				goto IL_027a;
			case "20":
				array3 = Seeds.Twenty();
				goto IL_027a;
			default:
				throw new ArgumentException("未知种子布局: " + seedName);
			case null:
				break;
				IL_027a:
				array4 = array3;
				sphereBucketIndex3 = new SphereBucketIndex(candidates, 3);
				sphereBucketIndex4 = ((initialDirs != null && initialDirs.Length != 0) ? new SphereBucketIndex(initialDirs) : null);
				array3 = array4;
				foreach (SVec3 sVec in array3)
				{
					ct.ThrowIfCancellationRequested();
					if (sphereBucketIndex4 != null && sphereBucketIndex4.Query(sVec, alphaDeg).Count > 0)
					{
						num5++;
						continue;
					}
					int num6 = -1;
					float num7 = float.MaxValue;
					List<int> list4 = sphereBucketIndex3.Query(sVec, seedRepairDeg);
					foreach (int item3 in list4)
					{
						float num8 = SVec3.DistanceSquared(candidates[item3], sVec);
						if (num8 < num7)
						{
							num7 = num8;
							num6 = item3;
						}
					}
					if (num6 < 0 || GainOf(num6) == 0)
					{
						num6 = -1;
						int num9 = 0;
						foreach (int item4 in list4)
						{
							if (!list2.Contains(item4))
							{
								int num10 = GainOf(item4);
								if (num10 > num9)
								{
									num9 = num10;
									num6 = item4;
								}
							}
						}
					}
					if (num6 >= 0 && GainOf(num6) > 0 && !list2.Contains(num6))
					{
						list2.Add(num6);
						int num11 = num6 * words;
						for (int l = 0; l < words; l++)
						{
							ulong num12 = masks[num11 + l];
							array[l] |= num12;
							uncovered[l] &= ~num12;
						}
					}
				}
				break;
			}
			bool flag = true;
			SphereBucketIndex sphereBucketIndex5 = new SphereBucketIndex(candidates, 2);
			ulong[] array5 = new ulong[words];
			while (flag)
			{
				flag = false;
				for (int m = 0; m < list2.Count; m++)
				{
					ct.ThrowIfCancellationRequested();
					int num13 = list2[m];
					Array.Copy(array2, array5, words);
					for (int n = 0; n < list2.Count; n++)
					{
						if (n != m)
						{
							int num14 = list2[n] * words;
							for (int num15 = 0; num15 < words; num15++)
							{
								array5[num15] |= masks[num14 + num15];
							}
						}
					}
					int num16 = num13 * words;
					int num17 = num13;
					int num18 = 0;
					for (int num19 = 0; num19 < words; num19++)
					{
						num18 += PopCount(masks[num16 + num19] & ~array5[num19]);
					}
					foreach (int item5 in sphereBucketIndex5.Query(candidates[num13], 3.0))
					{
						if (!list2.Contains(item5))
						{
							int num20 = 0;
							int num21 = item5 * words;
							for (int num22 = 0; num22 < words; num22++)
							{
								num20 += PopCount(masks[num21 + num22] & ~array5[num22]);
							}
							if (num20 > num18)
							{
								num18 = num20;
								num17 = item5;
							}
						}
					}
					if (num17 != num13)
					{
						list2[m] = num17;
						flag = true;
					}
				}
			}
			for (int num23 = 0; num23 < words; num23++)
			{
				ulong num24 = (array[num23] = array2[num23]);
				uncovered[num23] = ~num24;
			}
			if (num2 != 0)
			{
				uncovered[words - 1] &= (ulong)((1L << num2) - 1);
			}
			foreach (int item6 in list2)
			{
				int num25 = item6 * words;
				for (int num26 = 0; num26 < words; num26++)
				{
					ulong num27 = masks[num25 + num26];
					array[num26] |= num27;
					uncovered[num26] &= ~num27;
				}
			}
			List<int> list5 = new List<int>();
			for (int num28 = 0; num28 < candidates.Length; num28++)
			{
				list5.Add(num28);
			}
			int num29 = 0;
			for (int num30 = 0; num30 < words; num30++)
			{
				num29 += PopCount(uncovered[num30]);
			}
			while (true)
			{
				ct.ThrowIfCancellationRequested();
				bool flag2 = false;
				for (int num31 = 0; num31 < words; num31++)
				{
					if (uncovered[num31] != 0L)
					{
						flag2 = true;
						break;
					}
				}
				if (!flag2)
				{
					break;
				}
				int num32 = -1;
				int num33 = 0;
				List<int> list6 = new List<int>();
				int num34 = 0;
				foreach (int item7 in list5)
				{
					if ((num34++ & 0x3FF) == 0)
					{
						ct.ThrowIfCancellationRequested();
					}
					int num35 = GainOf(item7);
					if (num35 <= 0)
					{
						continue;
					}
					list6.Add(item7);
					if (num35 > num33)
					{
						num33 = num35;
						num32 = item7;
						if (num33 >= num29)
						{
							break;
						}
					}
				}
				list5 = list6;
				if (num33 == 0)
				{
					break;
				}
				list2.Add(num32);
				int num36 = num32 * words;
				for (int num37 = 0; num37 < words; num37++)
				{
					ulong num38 = masks[num36 + num37];
					array[num37] |= num38;
					uncovered[num37] &= ~num38;
				}
				num29 -= num33;
			}
			bool flag3 = true;
			ulong[] array6 = new ulong[words];
			while (flag3)
			{
				flag3 = false;
				for (int num39 = list2.Count - 1; num39 >= 0; num39--)
				{
					ct.ThrowIfCancellationRequested();
					bool flag4 = true;
					Array.Copy(array2, array6, words);
					for (int num40 = 0; num40 < list2.Count; num40++)
					{
						if (num40 != num39)
						{
							int num41 = list2[num40] * words;
							for (int num42 = 0; num42 < words; num42++)
							{
								array6[num42] |= masks[num41 + num42];
							}
						}
					}
					for (int num43 = 0; num43 < words; num43++)
					{
						ulong num44 = (ulong)((num43 == words - 1 && num2 != 0) ? ((1L << num2) - 1) : (-1));
						if ((array6[num43] & num44) != num44)
						{
							flag4 = false;
							break;
						}
					}
					if (flag4)
					{
						list2.RemoveAt(num39);
						flag3 = true;
					}
				}
			}
			CoverResult coverResult = new CoverResult();
			if (initialDirs != null && initialDirs.Length != 0)
			{
				SVec3[] array7 = SphereMath.FibSphere(41000);
				SphereBucketIndex sphereBucketIndex6 = new SphereBucketIndex(array7, 8);
				bool[] array8 = new bool[array7.Length];
				array3 = initialDirs;
				foreach (SVec3 center2 in array3)
				{
					foreach (int item8 in sphereBucketIndex6.Query(center2, alphaDeg))
					{
						array8[item8] = true;
					}
				}
				foreach (int item9 in list2)
				{
					foreach (int item10 in sphereBucketIndex6.Query(candidates[item9], alphaDeg))
					{
						array8[item10] = true;
					}
				}
				SphereBucketIndex sphereBucketIndex7 = new SphereBucketIndex(candidates, 8);
				while (true)
				{
					ct.ThrowIfCancellationRequested();
					List<int> list7 = new List<int>();
					for (int num45 = 0; num45 < array8.Length; num45++)
					{
						if (!array8[num45])
						{
							list7.Add(num45);
						}
					}
					if (list7.Count == 0)
					{
						break;
					}
					int num46 = -1;
					int num47 = 0;
					int num48 = 0;
					foreach (int item11 in list7)
					{
						if ((num48++ & 0x3F) == 0)
						{
							ct.ThrowIfCancellationRequested();
						}
						foreach (int item12 in sphereBucketIndex7.Query(array7[item11], alphaDeg))
						{
							if (list2.Contains(item12))
							{
								continue;
							}
							int num49 = 0;
							foreach (int item13 in sphereBucketIndex6.Query(candidates[item12], alphaDeg))
							{
								if (!array8[item13])
								{
									num49++;
								}
							}
							if (num49 > num47)
							{
								num47 = num49;
								num46 = item12;
							}
						}
					}
					if (num46 < 0 || num47 == 0)
					{
						break;
					}
					list2.Add(num46);
					foreach (int item14 in sphereBucketIndex6.Query(candidates[num46], alphaDeg))
					{
						array8[item14] = true;
					}
				}
				List<SVec3> list8 = new List<SVec3>();
				for (int num50 = 0; num50 < array8.Length; num50++)
				{
					if (!array8[num50])
					{
						list8.Add(array7[num50]);
					}
				}
				coverResult.DebugHoles = list8.ToArray();
			}
			coverResult.DebugSkippedSeeds = num5;
			int num51 = 0;
			foreach (int item15 in list2)
			{
				coverResult.Chosen.Add(item15);
				coverResult.ChosenDirs.Add(candidates[item15]);
				int num52 = item15 * words;
				for (int num53 = 0; num53 < words; num53++)
				{
					array[num53] |= masks[num52 + num53];
				}
			}
			for (int num54 = 0; num54 < words; num54++)
			{
				num51 += PopCount(array[num54]);
			}
			coverResult.Coverage = (double)num51 / (double)samples.Length;
			return coverResult;
			int GainOf(int num56)
			{
				int num55 = num56 * words;
				int num57 = 0;
				for (int num58 = 0; num58 < words; num58++)
				{
					num57 += PopCount(masks[num55 + num58] & uncovered[num58]);
				}
				return num57;
			}
		}

		public static double Verify(SVec3[] chosenDirs, double alphaDeg, int nIndep, CancellationToken ct = default(CancellationToken))
		{
			SVec3[] array = SphereMath.FibSphere(nIndep);
			SphereBucketIndex sphereBucketIndex = new SphereBucketIndex(array, 3);
			bool[] array2 = new bool[array.Length];
			foreach (SVec3 center in chosenDirs)
			{
				ct.ThrowIfCancellationRequested();
				foreach (int item in sphereBucketIndex.Query(center, alphaDeg))
				{
					array2[item] = true;
				}
			}
			int num = 0;
			for (int j = 0; j < array2.Length; j++)
			{
				if (array2[j])
				{
					num++;
				}
			}
			return (double)num / (double)array.Length;
		}

		public static SVec3[] BuildCandidates(double gridDeg, SVec3[] blocked, double inflateDeg, SVec3[] veinBlocked, double veinInflateDeg, CancellationToken ct = default(CancellationToken))
		{
			return BuildCandidates(gridDeg, blocked, inflateDeg, veinBlocked, veinInflateDeg, null, ct);
		}

		public static SVec3[] BuildCandidates(double gridDeg, SVec3[] blocked, double inflateDeg, SVec3[] veinBlocked, double veinInflateDeg, BlockedZone[]? extraZones, CancellationToken ct = default(CancellationToken))
		{
			List<SVec3> list = new List<SVec3>();
			SphereBucketIndex sphereBucketIndex = ((blocked.Length != 0) ? new SphereBucketIndex(blocked) : null);
			SphereBucketIndex sphereBucketIndex2 = ((veinBlocked.Length != 0) ? new SphereBucketIndex(veinBlocked) : null);
			double[] array = null;
			if (extraZones != null && extraZones.Length != 0)
			{
				array = new double[extraZones.Length];
				for (int i = 0; i < extraZones.Length; i++)
				{
					double num = Math.Min(180.0, Math.Max(0.0, extraZones[i].RadiusDeg));
					array[i] = Math.Cos(num * Math.PI / 180.0);
				}
			}
			List<int> list2 = new List<int>();
			for (double num2 = -90.0; num2 <= 90.000000001; num2 += gridDeg)
			{
				ct.ThrowIfCancellationRequested();
				for (double num3 = 0.0; num3 < 359.999999999; num3 += gridDeg)
				{
					SVec3 sVec = SphereMath.LatLon(num2, num3);
					if (sphereBucketIndex != null)
					{
						list2.Clear();
						sphereBucketIndex.QueryInto(sVec, inflateDeg, list2);
						if (list2.Count > 0)
						{
							continue;
						}
					}
					if (sphereBucketIndex2 != null)
					{
						list2.Clear();
						sphereBucketIndex2.QueryInto(sVec, veinInflateDeg, list2);
						if (list2.Count > 0)
						{
							continue;
						}
					}
					if (extraZones != null && array != null)
					{
						bool flag = false;
						for (int j = 0; j < extraZones.Length; j++)
						{
							if (extraZones[j].RadiusDeg > 0.0 && (double)SVec3.Dot(sVec, extraZones[j].Dir) >= array[j])
							{
								flag = true;
								break;
							}
						}
						if (flag)
						{
							continue;
						}
					}
					list.Add(sVec);
				}
			}
			return list.ToArray();
		}
	}
	public struct SVec3
	{
		public float X;

		public float Y;

		public float Z;

		public SVec3(float x, float y, float z)
		{
			X = x;
			Y = y;
			Z = z;
		}

		public float Length()
		{
			return (float)Math.Sqrt((double)X * (double)X + (double)Y * (double)Y + (double)Z * (double)Z);
		}

		public static SVec3 Normalize(SVec3 v)
		{
			float num = v.Length();
			if (num < 1E-12f)
			{
				return new SVec3(0f, 0f, 1f);
			}
			return new SVec3(v.X / num, v.Y / num, v.Z / num);
		}

		public static float Dot(SVec3 a, SVec3 b)
		{
			return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
		}

		public static float DistanceSquared(SVec3 a, SVec3 b)
		{
			float num = a.X - b.X;
			float num2 = a.Y - b.Y;
			float num3 = a.Z - b.Z;
			return num * num + num2 * num2 + num3 * num3;
		}
	}
	public static class SphereMath
	{
		public static SVec3[] FibSphere(int n)
		{
			SVec3[] array = new SVec3[n];
			double num = Math.PI * (3.0 - Math.Sqrt(5.0));
			for (int i = 0; i < n; i++)
			{
				double num2 = 1.0 - 2.0 * ((double)i + 0.5) / (double)n;
				double num3 = Math.Sqrt(Math.Max(0.0, 1.0 - num2 * num2));
				double num4 = num * (double)i;
				array[i] = new SVec3((float)(num3 * Math.Cos(num4)), (float)(num3 * Math.Sin(num4)), (float)num2);
			}
			return array;
		}

		public static SVec3 LatLon(double latDeg, double lonDeg)
		{
			double num = latDeg * Math.PI / 180.0;
			double num2 = lonDeg * Math.PI / 180.0;
			return new SVec3((float)(Math.Cos(num) * Math.Cos(num2)), (float)(Math.Cos(num) * Math.Sin(num2)), (float)Math.Sin(num));
		}

		public static SVec3 LatLonDir(double latDeg, double lonDeg, SVec3 dir)
		{
			SVec3 sVec = dir;
			SVec3 b = SVec3.Normalize(Cross(((double)Math.Abs(sVec.Y) < 0.9) ? new SVec3(0f, 1f, 0f) : new SVec3(1f, 0f, 0f), sVec));
			SVec3 sVec2 = Cross(sVec, b);
			double num = latDeg * Math.PI / 180.0;
			double num2 = lonDeg * Math.PI / 180.0;
			return SVec3.Normalize(new SVec3((float)((double)sVec.X * Math.Cos(num) + ((double)b.X * Math.Cos(num2) + (double)sVec2.X * Math.Sin(num2)) * Math.Sin(num)), (float)((double)sVec.Y * Math.Cos(num) + ((double)b.Y * Math.Cos(num2) + (double)sVec2.Y * Math.Sin(num2)) * Math.Sin(num)), (float)((double)sVec.Z * Math.Cos(num) + ((double)b.Z * Math.Cos(num2) + (double)sVec2.Z * Math.Sin(num2)) * Math.Sin(num))));
		}

		private static SVec3 Cross(SVec3 a, SVec3 b)
		{
			return new SVec3(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X);
		}

		public static (double lat, double lon) ToLatLon(SVec3 v)
		{
			double num = v.Length();
			double item = Math.Asin(Clamp((double)v.Z / num, -1.0, 1.0)) * 180.0 / Math.PI;
			double num2 = Math.Atan2(v.Y, v.X) * 180.0 / Math.PI;
			if (num2 < 0.0)
			{
				num2 += 360.0;
			}
			return (lat: item, lon: num2);
		}

		public static float ChordOf(double alphaDeg)
		{
			return 2f * (float)Math.Sin(alphaDeg * Math.PI / 360.0);
		}

		public static double AngleDeg(SVec3 a, SVec3 b)
		{
			return Math.Acos(Clamp(SVec3.Dot(a, b), -1f, 1f)) * 180.0 / Math.PI;
		}

		public static double Clamp(double v, double lo, double hi)
		{
			if (!(v < lo))
			{
				if (!(v > hi))
				{
					return v;
				}
				return hi;
			}
			return lo;
		}

		public static float Clamp(float v, float lo, float hi)
		{
			if (!(v < lo))
			{
				if (!(v > hi))
				{
					return v;
				}
				return hi;
			}
			return lo;
		}
	}
	public static class Seeds
	{
		public static SVec3[] Seven()
		{
			List<SVec3> list = new List<SVec3>
			{
				SphereMath.LatLon(90.0, 0.0),
				SphereMath.LatLon(-90.0, 0.0)
			};
			for (int i = 0; i < 5; i++)
			{
				list.Add(SphereMath.LatLon(0.0, i * 72));
			}
			return list.ToArray();
		}

		public static SVec3[] Eight()
		{
			List<SVec3> list = new List<SVec3>();
			double[] array = new double[2] { 35.26438968, -35.26438968 };
			foreach (double latDeg in array)
			{
				int[] array2 = new int[4] { 45, 135, 225, 315 };
				foreach (int num in array2)
				{
					list.Add(SphereMath.LatLon(latDeg, num));
				}
			}
			return list.ToArray();
		}

		public static SVec3[] Twenty()
		{
			List<SVec3> list = new List<SVec3>();
			for (int i = 0; i < 4; i++)
			{
				list.Add(SphereMath.LatLon(0.0, 13.2 + 90.0 * (double)i));
			}
			for (int j = 0; j < 4; j++)
			{
				list.Add(SphereMath.LatLon(20.9, 60.3 + 90.0 * (double)j));
				list.Add(SphereMath.LatLon(-20.9, 60.3 + 90.0 * (double)j));
			}
			for (int k = 0; k < 4; k++)
			{
				list.Add(SphereMath.LatLon(58.9, 13.2 + 90.0 * (double)k));
				list.Add(SphereMath.LatLon(-58.9, 13.2 + 90.0 * (double)k));
			}
			return list.ToArray();
		}
	}
	public sealed class SphereBucketIndex
	{
		private readonly int _n;

		private readonly List<int>[,,] _bins;

		private readonly SVec3[] _points;

		public SphereBucketIndex(SVec3[] points, int n = 16)
		{
			_n = n;
			_points = points;
			_bins = new List<int>[n, n, n];
			for (int i = 0; i < points.Length; i++)
			{
				SVec3 sVec = points[i];
				int num = BucketOf(sVec.X);
				int num2 = BucketOf(sVec.Y);
				int num3 = BucketOf(sVec.Z);
				List<int>[,,] bins = _bins;
				int num4 = num;
				int num5 = num2;
				int num6 = num3;
				(bins[num4, num5, num6] ?? (bins[num4, num5, num6] = new List<int>())).Add(i);
			}
		}

		private int BucketOf(float v)
		{
			int num = (int)((v + 1f) * 0.5f * (float)_n);
			if (num >= 0)
			{
				if (num < _n)
				{
					return num;
				}
				return _n - 1;
			}
			return 0;
		}

		public List<int> Query(SVec3 center, double radiusDeg)
		{
			List<int> result = new List<int>();
			QueryInto(center, radiusDeg, result);
			return result;
		}

		public void QueryInto(SVec3 center, double radiusDeg, List<int> result)
		{
			float num = SphereMath.ChordOf(radiusDeg);
			float num2 = 2f / (float)_n * 1.7320508f;
			float num3 = 0f - num - num2;
			float num4 = num + num2;
			int num5 = BucketOf(center.X + num3);
			int num6 = BucketOf(center.X + num4);
			int num7 = BucketOf(center.Y + num3);
			int num8 = BucketOf(center.Y + num4);
			int num9 = BucketOf(center.Z + num3);
			int num10 = BucketOf(center.Z + num4);
			float num11 = num * num;
			for (int i = num5; i <= num6; i++)
			{
				for (int j = num7; j <= num8; j++)
				{
					for (int k = num9; k <= num10; k++)
					{
						List<int> list = _bins[i, j, k];
						if (list == null)
						{
							continue;
						}
						foreach (int item in list)
						{
							if (SVec3.DistanceSquared(_points[item], center) <= num11)
							{
								result.Add(item);
							}
						}
					}
				}
			}
		}
	}
}