Decompiled source of MissileControlMod v1.0.1

MissileControlMod.dll

Decompiled 2 days ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;
using crecheng.DSPModSave;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("MissileControlMod")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Missile Turret Relay Station Control Mod")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("MissileControlMod")]
[assembly: AssemblyTitle("MissileControlMod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 MissileControlMod
{
	[BepInPlugin("com.yourname.MissileControlMod", "Missile Control Mod", "1.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class MissileControlPlugin : BaseUnityPlugin, IModCanSave
	{
		public static MissileControlPlugin Instance;

		private const int MAGIC = 1296256257;

		private void Awake()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			Instance = this;
			Harmony harmony = new Harmony("com.yourname.MissileControlMod");
			Harmony.CreateAndPatchAll(typeof(TurretLogic), (string)null);
			BuildPatch.ManualPatch(harmony);
			Harmony.CreateAndPatchAll(typeof(UIExtension), (string)null);
			Harmony.CreateAndPatchAll(typeof(ModSave), (string)null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Missile Control Mod Loaded");
		}

		public void Export(BinaryWriter w)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"[MissileControlMod] Exporting save data...");
			w.Write(1);
			Dictionary<long, TurretConfig> dictionary = new Dictionary<long, TurretConfig>();
			foreach (KeyValuePair<long, TurretConfig> config in TurretLogic.configs)
			{
				if (config.Value.RelayMode || config.Value.MinHp != 0.1f || config.Value.MaxHp != 0.95f || config.Value.TargetRelayId != 0)
				{
					dictionary.Add(config.Key, config.Value);
				}
			}
			w.Write(dictionary.Count);
			foreach (KeyValuePair<long, TurretConfig> item in dictionary)
			{
				w.Write(item.Key);
				w.Write(item.Value.RelayMode);
				w.Write(item.Value.MinHp);
				w.Write(item.Value.MaxHp);
				w.Write(item.Value.TargetRelayId);
			}
			Dictionary<long, TurretConfig> dictionary2 = new Dictionary<long, TurretConfig>();
			foreach (KeyValuePair<long, TurretConfig> prebuildConfig in TurretLogic.prebuildConfigs)
			{
				if (prebuildConfig.Value.RelayMode || prebuildConfig.Value.MinHp != 0.1f || prebuildConfig.Value.MaxHp != 0.95f || prebuildConfig.Value.TargetRelayId != 0)
				{
					dictionary2.Add(prebuildConfig.Key, prebuildConfig.Value);
				}
			}
			w.Write(dictionary2.Count);
			foreach (KeyValuePair<long, TurretConfig> item2 in dictionary2)
			{
				w.Write(item2.Key);
				w.Write(item2.Value.RelayMode);
				w.Write(item2.Value.MinHp);
				w.Write(item2.Value.MaxHp);
				w.Write(item2.Value.TargetRelayId);
			}
		}

		public void Import(BinaryReader r)
		{
			try
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"[MissileControlMod] Importing save data...");
				int num = r.ReadInt32();
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"[MissileControlMod] Data version: {num}");
				if (num < 1)
				{
					return;
				}
				int num2 = r.ReadInt32();
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"[MissileControlMod] Loading {num2} turret configs...");
				for (int i = 0; i < num2; i++)
				{
					long num3 = r.ReadInt64();
					TurretConfig turretConfig = new TurretConfig();
					turretConfig.RelayMode = r.ReadBoolean();
					turretConfig.MinHp = r.ReadSingle();
					turretConfig.MaxHp = r.ReadSingle();
					turretConfig.TargetRelayId = r.ReadInt32();
					TurretLogic.configs[num3] = turretConfig;
					if (i < 5)
					{
						int num4 = (int)(num3 >> 32);
						int num5 = (int)(num3 & 0xFFFFFFFFu);
						((BaseUnityPlugin)this).Logger.LogInfo((object)$"[MissileControlMod] Loaded Config - Planet: {num4}, Turret: {num5}, RelayMode: {turretConfig.RelayMode}");
					}
				}
				int num6 = r.ReadInt32();
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"[MissileControlMod] Loading {num6} prebuild configs...");
				for (int j = 0; j < num6; j++)
				{
					long key = r.ReadInt64();
					TurretConfig turretConfig2 = new TurretConfig();
					turretConfig2.RelayMode = r.ReadBoolean();
					turretConfig2.MinHp = r.ReadSingle();
					turretConfig2.MaxHp = r.ReadSingle();
					turretConfig2.TargetRelayId = r.ReadInt32();
					TurretLogic.prebuildConfigs[key] = turretConfig2;
				}
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"[MissileControlMod] Import error: {arg}");
			}
		}

		public void IntoOtherSave()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"[MissileControlMod] IntoOtherSave called (Clearing data).");
			TurretLogic.configs.Clear();
			TurretLogic.monitorStatus.Clear();
			TurretLogic.monitoringState.Clear();
			TurretLogic.prebuildConfigs.Clear();
			TurretLogic.ClipboardConfig = null;
		}

		public void LegacyImport(BinaryReader r)
		{
			try
			{
				if (r.BaseStream.Position + 4 > r.BaseStream.Length)
				{
					return;
				}
				int num = r.ReadInt32();
				if (num != 1296256257)
				{
					r.BaseStream.Position -= 4L;
					return;
				}
				int num2 = r.ReadInt32();
				long num3 = r.BaseStream.Position + num2;
				int num4 = r.ReadInt32();
				if (num4 >= 1)
				{
					int num5 = r.ReadInt32();
					for (int i = 0; i < num5; i++)
					{
						long key = r.ReadInt64();
						TurretConfig turretConfig = new TurretConfig();
						turretConfig.RelayMode = r.ReadBoolean();
						turretConfig.MinHp = r.ReadSingle();
						turretConfig.MaxHp = r.ReadSingle();
						turretConfig.TargetRelayId = r.ReadInt32();
						TurretLogic.configs[key] = turretConfig;
					}
					int num6 = r.ReadInt32();
					for (int j = 0; j < num6; j++)
					{
						long key2 = r.ReadInt64();
						TurretConfig turretConfig2 = new TurretConfig();
						turretConfig2.RelayMode = r.ReadBoolean();
						turretConfig2.MinHp = r.ReadSingle();
						turretConfig2.MaxHp = r.ReadSingle();
						turretConfig2.TargetRelayId = r.ReadInt32();
						TurretLogic.prebuildConfigs[key2] = turretConfig2;
					}
				}
				if (r.BaseStream.Position != num3)
				{
					r.BaseStream.Position = num3;
				}
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"[MissileControlMod] Legacy Import error: {arg}");
			}
		}
	}
	public static class ModSave
	{
		[HarmonyPatch(typeof(GameData), "Import")]
		[HarmonyPostfix]
		public static void Import_Postfix(GameData __instance, BinaryReader r)
		{
			if ((Object)(object)MissileControlPlugin.Instance != (Object)null)
			{
				MissileControlPlugin.Instance.LegacyImport(r);
				if (TurretLogic.configs.Count > 0)
				{
					Debug.Log((object)$"[MissileControlMod] Loaded {TurretLogic.configs.Count} turrets from legacy save data.");
				}
			}
		}
	}
	public class TurretConfig
	{
		public bool RelayMode;

		public float MinHp = 0.1f;

		public float MaxHp = 0.95f;

		public int TargetRelayId;

		public TurretConfig Clone()
		{
			return new TurretConfig
			{
				RelayMode = RelayMode,
				MinHp = MinHp,
				MaxHp = MaxHp,
				TargetRelayId = TargetRelayId
			};
		}
	}
	public static class TurretLogic
	{
		public static ConcurrentDictionary<long, TurretConfig> configs = new ConcurrentDictionary<long, TurretConfig>();

		public static ConcurrentDictionary<long, TurretConfig> prebuildConfigs = new ConcurrentDictionary<long, TurretConfig>();

		public static ConcurrentDictionary<long, string> monitorStatus = new ConcurrentDictionary<long, string>();

		public static ConcurrentDictionary<long, bool> monitoringState = new ConcurrentDictionary<long, bool>();

		public static TurretConfig ClipboardConfig = null;

		private static List<int> foundRelayIds = new List<int>();

		private static object relayListLock = new object();

		public static long GetUniqueId(int planetId, int turretId)
		{
			return ((long)planetId << 32) | (uint)turretId;
		}

		public static TurretConfig GetConfig(int planetId, int turretId)
		{
			long uniqueId = GetUniqueId(planetId, turretId);
			return configs.ContainsKey(uniqueId) ? configs[uniqueId] : null;
		}

		public static TurretConfig GetOrCreateConfig(int planetId, int turretId)
		{
			long uniqueId = GetUniqueId(planetId, turretId);
			if (!configs.ContainsKey(uniqueId))
			{
				configs[uniqueId] = new TurretConfig();
			}
			return configs[uniqueId];
		}

		public static bool IsInRelayMode(int planetId, int turretId)
		{
			return GetConfig(planetId, turretId)?.RelayMode ?? false;
		}

		public static void ToggleRelayMode(int planetId, int turretId, PlanetFactory factory)
		{
			TurretConfig orCreateConfig = GetOrCreateConfig(planetId, turretId);
			orCreateConfig.RelayMode = !orCreateConfig.RelayMode;
			if (orCreateConfig.RelayMode)
			{
				ScanRelays(factory);
				CycleNextRelay(planetId, turretId, factory);
			}
		}

		public static void SetThresholds(int planetId, int turretId, float min, float max)
		{
			TurretConfig orCreateConfig = GetOrCreateConfig(planetId, turretId);
			orCreateConfig.MinHp = Mathf.Clamp(min, 0.01f, 0.99f);
			orCreateConfig.MaxHp = Mathf.Clamp(max, orCreateConfig.MinHp + 0.01f, 1f);
		}

		public static void ScanRelays(PlanetFactory factory)
		{
			if (factory == null && GameMain.localPlanet != null)
			{
				factory = GameMain.localPlanet.factory;
			}
			lock (relayListLock)
			{
				foundRelayIds.Clear();
				if (GameMain.data?.spaceSector?.enemyPool == null)
				{
					return;
				}
				SpaceSector spaceSector = GameMain.data.spaceSector;
				EnemyData[] enemyPool = spaceSector.enemyPool;
				if (((factory != null) ? factory.planet : null) != null)
				{
					int astroId = factory.planet.astroId;
					int enemyCursor = spaceSector.enemyCursor;
					for (int i = 1; i < enemyCursor; i++)
					{
						if (enemyPool[i].id == i && enemyPool[i].dfRelayId > 0 && enemyPool[i].astroId == astroId && !foundRelayIds.Contains(i))
						{
							foundRelayIds.Add(i);
						}
					}
				}
				foundRelayIds.Sort();
			}
		}

		public static void CycleNextRelay(int planetId, int turretId, PlanetFactory factory)
		{
			ChangeRelaySelection(planetId, turretId, factory, 1);
		}

		private static void ChangeRelaySelection(int planetId, int turretId, PlanetFactory factory, int direction)
		{
			long uniqueId = GetUniqueId(planetId, turretId);
			TurretConfig orCreateConfig = GetOrCreateConfig(planetId, turretId);
			lock (relayListLock)
			{
				monitoringState[uniqueId] = false;
				if (foundRelayIds.Count == 0)
				{
					ScanRelays(factory);
				}
				if (foundRelayIds.Count == 0)
				{
					string text = ((factory != null) ? "当前星球" : "全局");
					monitorStatus[uniqueId] = "扫描:" + text + "无中继站";
					orCreateConfig.TargetRelayId = 0;
					return;
				}
				int num = foundRelayIds.IndexOf(orCreateConfig.TargetRelayId);
				if (num == -1)
				{
					num = 0;
				}
				else
				{
					num += direction;
					if (num >= foundRelayIds.Count)
					{
						num = 0;
					}
					if (num < 0)
					{
						num = foundRelayIds.Count - 1;
					}
				}
				orCreateConfig.TargetRelayId = foundRelayIds[num];
				string text2 = $"中继站 {orCreateConfig.TargetRelayId} ({num + 1}/{foundRelayIds.Count})";
				monitorStatus[uniqueId] = "目标锁定: " + text2;
			}
		}

		[HarmonyPatch(typeof(GameMain), "FixedUpdate")]
		[HarmonyPrefix]
		public static void GameTick_Patch(GameMain __instance)
		{
			if (!GameMain.isPaused && GameMain.data != null && GameMain.data.spaceSector != null)
			{
				UpdateAllTurrets(GameMain.data);
			}
		}

		private static void UpdateAllTurrets(GameData gameData)
		{
			foreach (KeyValuePair<long, TurretConfig> config in configs)
			{
				if (config.Value.RelayMode)
				{
					long key = config.Key;
					int num = (int)(key >> 32);
					int num2 = (int)(key & 0xFFFFFFFFu);
					PlanetData val = gameData.galaxy.PlanetById(num);
					if (val != null && val.factory != null)
					{
						UpdateTurretStatus(key, config.Value, val.factory, gameData.spaceSector);
					}
				}
			}
		}

		private static void UpdateTurretStatus(long key, TurretConfig cfg, PlanetFactory factory, SpaceSector sector)
		{
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: 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)
			try
			{
				EnemyData[] enemyPool = sector.enemyPool;
				int targetRelayId = cfg.TargetRelayId;
				bool flag = false;
				if (targetRelayId > 0 && targetRelayId < enemyPool.Length && enemyPool[targetRelayId].id == targetRelayId && enemyPool[targetRelayId].dfRelayId > 0)
				{
					flag = true;
				}
				if (!flag)
				{
					int planetId = factory.planetId;
					int turretId = (int)(key & 0xFFFFFFFFu);
					CycleNextRelay(planetId, turretId, factory);
					targetRelayId = cfg.TargetRelayId;
				}
				if (targetRelayId <= 0)
				{
					monitorStatus[key] = "空闲:无中继站";
					return;
				}
				ref EnemyData reference = ref enemyPool[targetRelayId];
				if (sector.skillSystem?.combatStats?.buffer == null)
				{
					return;
				}
				SkillSystem skillSystem = sector.skillSystem;
				int combatStatId = reference.combatStatId;
				float num = 1f;
				bool flag2 = false;
				if (combatStatId > 0 && combatStatId < skillSystem.combatStats.buffer.Length)
				{
					CombatStat val = skillSystem.combatStats.buffer[combatStatId];
					if (val.hpMax > 0)
					{
						num = (float)val.hp / (float)val.hpMax;
						flag2 = true;
					}
				}
				string text = (flag2 ? $"中继站 {targetRelayId} (耐久度: {num:P1})" : $"中继站 {targetRelayId} (满血)");
				bool flag3 = monitoringState.ContainsKey(key) && monitoringState[key];
				if (num <= cfg.MinHp)
				{
					if (!flag3)
					{
						monitoringState[key] = true;
					}
					monitorStatus[key] = text + " [压制中]";
				}
				else if (num >= cfg.MaxHp)
				{
					if (flag3)
					{
						monitoringState[key] = false;
					}
					monitorStatus[key] = text + " [攻击中]";
				}
				else if (flag3)
				{
					monitorStatus[key] = text + " [等待恢复]";
				}
				else
				{
					monitorStatus[key] = text + " [攻击中]";
				}
			}
			catch
			{
			}
		}

		[HarmonyPatch(typeof(TurretComponent), "Shoot_Missile")]
		[HarmonyPrefix]
		public static bool Shoot_Missile_Prefix(ref TurretComponent __instance, PlanetFactory factory, EnemyData[] spaceEnemyPool)
		{
			return ProcessTurretLogic(ref __instance, factory, spaceEnemyPool);
		}

		[HarmonyPatch(typeof(TurretComponent), "Shoot_Plasma")]
		[HarmonyPrefix]
		public static bool Shoot_Plasma_Prefix(ref TurretComponent __instance, PlanetFactory factory, EnemyData[] spaceEnemyPool)
		{
			return ProcessTurretLogic(ref __instance, factory, spaceEnemyPool);
		}

		private static bool ProcessTurretLogic(ref TurretComponent __instance, PlanetFactory factory, EnemyData[] spaceEnemyPool)
		{
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			if (factory == null || spaceEnemyPool == null)
			{
				return true;
			}
			int id = __instance.id;
			int planetId = factory.planetId;
			long uniqueId = GetUniqueId(planetId, id);
			TurretConfig config = GetConfig(planetId, id);
			if (config == null || !config.RelayMode)
			{
				if (monitorStatus.ContainsKey(uniqueId))
				{
					monitorStatus.TryRemove(uniqueId, out var _);
				}
				return true;
			}
			try
			{
				int targetRelayId = config.TargetRelayId;
				if (targetRelayId <= 0)
				{
					return true;
				}
				ref EnemyData reference = ref spaceEnemyPool[targetRelayId];
				__instance.target.id = targetRelayId;
				int originAstroId = reference.originAstroId;
				__instance.target.astroId = ((originAstroId != 0) ? originAstroId : reference.astroId);
				__instance.target.type = (ETargetType)4;
				if (monitoringState.ContainsKey(uniqueId) && monitoringState[uniqueId])
				{
					return false;
				}
				return true;
			}
			catch
			{
				return true;
			}
		}
	}
	public static class BuildPatch
	{
		public static void ManualPatch(Harmony harmony)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(PlanetFactory), "AddEntityDataWithComponents", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(BuildPatch), "Postfix_AddEntityDataWithComponents", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(BuildingParameters), "CopyFromFactoryObject", (Type[])null, (Type[])null);
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(BuildPatch), "Postfix_CopyBuildingSetting", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo3 = AccessTools.Method(typeof(BuildingParameters), "PasteToFactoryObject", (Type[])null, (Type[])null);
			if (methodInfo3 != null)
			{
				harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(BuildPatch), "Postfix_PasteBuildingSetting", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo4 = AccessTools.Method(typeof(PlayerAction_Build), "Close", (Type[])null, (Type[])null);
			if (methodInfo4 != null)
			{
				harmony.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, new HarmonyMethod(typeof(BuildPatch), "Postfix_BuildClose", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		public static void Postfix_BuildClose()
		{
			TurretLogic.ClipboardConfig = null;
		}

		public static void Postfix_CopyBuildingSetting(int objectId, PlanetFactory factory)
		{
			if (factory == null || objectId <= 0 || objectId >= factory.entityPool.Length)
			{
				return;
			}
			int turretId = factory.entityPool[objectId].turretId;
			if (turretId > 0)
			{
				TurretConfig config = TurretLogic.GetConfig(factory.planetId, turretId);
				if (config != null)
				{
					TurretLogic.ClipboardConfig = config.Clone();
				}
				else
				{
					TurretLogic.ClipboardConfig = null;
				}
			}
		}

		public static void Postfix_PasteBuildingSetting(int objectId, PlanetFactory factory)
		{
			if (factory != null && objectId > 0 && objectId < factory.entityPool.Length)
			{
				int turretId = factory.entityPool[objectId].turretId;
				if (turretId > 0 && TurretLogic.ClipboardConfig != null)
				{
					long uniqueId = TurretLogic.GetUniqueId(factory.planetId, turretId);
					TurretLogic.configs[uniqueId] = TurretLogic.ClipboardConfig.Clone();
				}
			}
		}

		public static void Postfix_AddEntityDataWithComponents(PlanetFactory __instance, int __result)
		{
			if (__result <= 0)
			{
				return;
			}
			if (__result >= __instance.entityPool.Length)
			{
				return;
			}
			int turretId = __instance.entityPool[__result].turretId;
			if (turretId > 0)
			{
				long uniqueId = TurretLogic.GetUniqueId(__instance.planetId, turretId);
				if (TurretLogic.ClipboardConfig != null)
				{
					TurretLogic.configs[uniqueId] = TurretLogic.ClipboardConfig.Clone();
				}
				else if (!TurretLogic.configs.ContainsKey(uniqueId))
				{
					TurretLogic.configs[uniqueId] = new TurretConfig();
				}
			}
		}
	}
	public class WindowDragHandler : MonoBehaviour, IDragHandler, IEventSystemHandler, IBeginDragHandler
	{
		private RectTransform dragRectTransform;

		private Canvas canvas;

		private void Start()
		{
			dragRectTransform = ((Component)((Component)this).transform.parent).GetComponent<RectTransform>();
			canvas = ((Component)this).GetComponentInParent<Canvas>();
		}

		public void OnBeginDrag(PointerEventData eventData)
		{
			if ((Object)(object)canvas == (Object)null)
			{
				canvas = ((Component)this).GetComponentInParent<Canvas>();
			}
		}

		public void OnDrag(PointerEventData eventData)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)dragRectTransform != (Object)null && (Object)(object)canvas != (Object)null)
			{
				RectTransform obj = dragRectTransform;
				obj.anchoredPosition += eventData.delta / canvas.scaleFactor;
			}
		}
	}
	public static class UIExtension
	{
		private struct TurretInfo
		{
			public int ProtoId;

			public int ModelIndex;

			public int ItemId;
		}

		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<Font, bool> <>9__23_0;

			public static UnityAction <>9__23_1;

			public static UnityAction<bool> <>9__23_2;

			public static UnityAction <>9__23_3;

			public static UnityAction<string> <>9__24_0;

			public static UnityAction<string> <>9__24_1;

			public static UnityAction <>9__25_0;

			internal bool <CreateOverlayUI>b__23_0(Font f)
			{
				return ((Object)f).name == "SAIRASEMICONDENSED-BOLD";
			}

			internal void <CreateOverlayUI>b__23_1()
			{
				if ((Object)(object)_menuPanelObj != (Object)null)
				{
					_menuPanelObj.SetActive(!_menuPanelObj.activeSelf);
				}
			}

			internal void <CreateOverlayUI>b__23_2(bool isOn)
			{
				if (_isSyncing)
				{
					return;
				}
				Debug.Log((object)$"[MissileControlMod] Toggle Clicked: {isOn}");
				if (GameMain.localPlanet == null)
				{
					return;
				}
				int id = GameMain.localPlanet.id;
				try
				{
					TurretConfig orCreateConfig = TurretLogic.GetOrCreateConfig(id, _currentTurretId);
					if (orCreateConfig.RelayMode != isOn)
					{
						orCreateConfig.RelayMode = isOn;
						if (orCreateConfig.RelayMode)
						{
							TurretLogic.ScanRelays(GameMain.localPlanet.factory);
							TurretLogic.CycleNextRelay(id, _currentTurretId, GameMain.localPlanet.factory);
						}
						Debug.Log((object)$"[MissileControlMod] RelayMode set to {isOn}");
					}
					UpdateStatusText();
				}
				catch (Exception arg)
				{
					Debug.LogWarning((object)$"[MissileControlMod] Toggle Error: {arg}");
				}
			}

			internal void <CreateOverlayUI>b__23_3()
			{
				_menuPanelObj.SetActive(false);
			}

			internal void <CreateThresholdsRow>b__24_0(string val)
			{
				OnThresholdChanged();
			}

			internal void <CreateThresholdsRow>b__24_1(string val)
			{
				OnThresholdChanged();
			}

			internal void <CreateSelectorRow>b__25_0()
			{
				if (GameMain.localPlanet != null)
				{
					int id = GameMain.localPlanet.id;
					if (_currentTurretId != 0)
					{
						TurretLogic.ScanRelays(GameMain.localPlanet.factory);
						TurretLogic.CycleNextRelay(id, _currentTurretId, GameMain.localPlanet.factory);
						UpdateStatusText();
						Debug.Log((object)$"[MissileControlMod] Switched Relay. Current ID: {TurretLogic.GetConfig(id, _currentTurretId)?.TargetRelayId}");
					}
				}
			}
		}

		private static GameObject _settingsBtnObj;

		private static GameObject _menuPanelObj;

		private static Text _mainStatusText;

		private static Toggle _modeToggle;

		private static InputField _minInput;

		private static InputField _maxInput;

		private static Text _menuStatusText;

		private static int _currentTurretId;

		private static bool _isCurrentSupported;

		private static bool _uiInitialized;

		private static bool _isSyncing;

		private static FieldInfo _cachedTurretIdField;

		private static bool _fieldLookupAttempted;

		private static int GetTurretId(object window)
		{
			if (window == null)
			{
				return 0;
			}
			if (_cachedTurretIdField != null)
			{
				try
				{
					return (int)_cachedTurretIdField.GetValue(window);
				}
				catch
				{
					return 0;
				}
			}
			if (_fieldLookupAttempted)
			{
				return 0;
			}
			_fieldLookupAttempted = true;
			try
			{
				Type type = window.GetType();
				FieldInfo fieldInfo = type.GetField("turretId", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (fieldInfo == null)
				{
					fieldInfo = type.GetField("turretID", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				}
				if (fieldInfo == null)
				{
					fieldInfo = type.GetField("_turretId", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				}
				if (fieldInfo == null)
				{
					List<FieldInfo> declaredFields = AccessTools.GetDeclaredFields(type);
					foreach (FieldInfo item in declaredFields)
					{
						if (item.FieldType == typeof(int) && item.Name.ToLower().Contains("turretid"))
						{
							fieldInfo = item;
							break;
						}
					}
				}
				if (fieldInfo != null)
				{
					_cachedTurretIdField = fieldInfo;
					return (int)fieldInfo.GetValue(window);
				}
				Debug.LogWarning((object)"[MissileControlMod] Could not find turretId field in UITurretWindow.");
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("[MissileControlMod] GetTurretId error: " + ex.Message));
			}
			return 0;
		}

		private static bool IsPlasmaTurret(int turretId)
		{
			TurretInfo turretInfo = GetTurretInfo(turretId);
			return turretInfo.ProtoId == 3004 || turretInfo.ModelIndex == 3004;
		}

		private static bool IsSupportedTurret(int turretId)
		{
			TurretInfo turretInfo = GetTurretInfo(turretId);
			if (turretInfo.ProtoId == 3005 || turretInfo.ModelIndex == 407)
			{
				return true;
			}
			if (turretInfo.ProtoId == 3004 || turretInfo.ModelIndex == 408)
			{
				return true;
			}
			if (turretInfo.ModelIndex == 813 || turretInfo.ModelIndex == 815)
			{
				return true;
			}
			return false;
		}

		private static TurretInfo GetTurretInfo(int turretId)
		{
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			TurretInfo result = default(TurretInfo);
			try
			{
				if (GameMain.localPlanet == null || GameMain.localPlanet.factory == null)
				{
					return result;
				}
				PlanetFactory factory = GameMain.localPlanet.factory;
				object obj = null;
				Array array = null;
				FieldInfo fieldInfo = AccessTools.Field(typeof(PlanetFactory), "defenseSystem");
				if (fieldInfo != null)
				{
					object value = fieldInfo.GetValue(factory);
					if (value != null)
					{
						FieldInfo fieldInfo2 = AccessTools.Field(value.GetType(), "turrets");
						if (fieldInfo2 != null)
						{
							obj = fieldInfo2.GetValue(value);
						}
					}
				}
				if (obj == null)
				{
					FieldInfo fieldInfo3 = AccessTools.Field(typeof(PlanetFactory), "turretPool");
					if (fieldInfo3 != null)
					{
						array = fieldInfo3.GetValue(factory) as Array;
					}
				}
				else
				{
					FieldInfo fieldInfo4 = AccessTools.Field(obj.GetType(), "buffer");
					if (fieldInfo4 != null)
					{
						array = fieldInfo4.GetValue(obj) as Array;
					}
				}
				if (array == null)
				{
					Debug.LogWarning((object)"[MissileControlMod] Could not find turret buffer (checked DefenseSystem and legacy turretPool).");
					return result;
				}
				if (turretId <= 0 || turretId >= array.Length)
				{
					Debug.LogWarning((object)$"[MissileControlMod] TurretID {turretId} out of range (Length: {array.Length})");
					return result;
				}
				object value2 = array.GetValue(turretId);
				try
				{
					FieldInfo fieldInfo5 = AccessTools.Field(value2.GetType(), "itemId");
					if (fieldInfo5 != null)
					{
						object value3 = fieldInfo5.GetValue(value2);
						result.ItemId = Convert.ToInt32(value3);
					}
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)("[MissileControlMod] Error reading itemId: " + ex.Message));
				}
				int num = 0;
				try
				{
					FieldInfo fieldInfo6 = AccessTools.Field(value2.GetType(), "entityId");
					if (fieldInfo6 != null)
					{
						object value4 = fieldInfo6.GetValue(value2);
						num = Convert.ToInt32(value4);
					}
					else
					{
						Debug.LogWarning((object)"[MissileControlMod] entityId field not found on TurretComponent.");
					}
				}
				catch (Exception ex2)
				{
					Debug.LogWarning((object)("[MissileControlMod] Error reading entityId: " + ex2.Message));
				}
				if (num <= 0 || num >= factory.entityPool.Length)
				{
					Debug.LogWarning((object)$"[MissileControlMod] EntityId {num} invalid (PoolLen: {factory.entityPool.Length})");
					if (result.ItemId > 0)
					{
						result.ProtoId = result.ItemId;
					}
					return result;
				}
				EntityData val = factory.entityPool[num];
				result.ProtoId = val.protoId;
				result.ModelIndex = val.modelIndex;
				if (result.ProtoId == 0 && result.ItemId > 0)
				{
					result.ProtoId = result.ItemId;
				}
				return result;
			}
			catch (Exception)
			{
				return result;
			}
		}

		[HarmonyPatch(typeof(UITurretWindow), "_OnOpen")]
		[HarmonyPostfix]
		public static void UITurretWindow_OnOpen_Postfix(UITurretWindow __instance)
		{
			TryInitUI(__instance);
		}

		[HarmonyPatch(typeof(UITurretWindow), "_OnUpdate")]
		[HarmonyPostfix]
		public static void UITurretWindow_OnUpdate_Postfix(UITurretWindow __instance)
		{
			if (!_uiInitialized)
			{
				TryInitUI(__instance);
			}
			int turretId = GetTurretId(__instance);
			if (turretId != 0 && turretId != _currentTurretId)
			{
				_currentTurretId = turretId;
				bool flag = (_isCurrentSupported = IsSupportedTurret(turretId));
				if ((Object)(object)_settingsBtnObj != (Object)null)
				{
					_settingsBtnObj.SetActive(flag);
				}
				if ((Object)(object)_menuPanelObj != (Object)null && !flag)
				{
					_menuPanelObj.SetActive(false);
				}
				if ((Object)(object)_mainStatusText != (Object)null)
				{
					if (!flag)
					{
						_mainStatusText.text = "";
						((Component)_mainStatusText).gameObject.SetActive(false);
					}
					else
					{
						((Component)_mainStatusText).gameObject.SetActive(true);
					}
				}
				if (flag)
				{
					UpdateButtonPosition(turretId);
					UpdateStatusText();
				}
			}
			else if (_isCurrentSupported)
			{
				UpdateStatusText();
			}
		}

		private static void TryInitUI(UITurretWindow window)
		{
			int turretId = GetTurretId(window);
			if (turretId == 0)
			{
				return;
			}
			_currentTurretId = turretId;
			_uiInitialized = true;
			if ((Object)(object)_settingsBtnObj == (Object)null)
			{
				CreateOverlayUI(window);
			}
			bool flag = (_isCurrentSupported = IsSupportedTurret(turretId));
			if ((Object)(object)_settingsBtnObj != (Object)null)
			{
				_settingsBtnObj.SetActive(flag);
				if (flag)
				{
					UpdateButtonPosition(turretId);
				}
			}
			if ((Object)(object)_menuPanelObj != (Object)null)
			{
				_menuPanelObj.SetActive(false);
			}
			if (flag)
			{
				SyncUI();
				UpdateStatusText();
			}
		}

		private static void UpdateButtonPosition(int turretId)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: 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_0045: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_settingsBtnObj == (Object)null))
			{
				bool flag = IsPlasmaTurret(turretId);
				Vector2 val = default(Vector2);
				((Vector2)(ref val))..ctor(-70f, 10f);
				Vector2 val2 = default(Vector2);
				((Vector2)(ref val2))..ctor(-78f, 10f);
				Vector2 val3 = (flag ? val2 : val);
				Vector2 anchoredPosition = val3 + new Vector2(40f, 12f);
				_settingsBtnObj.GetComponent<RectTransform>().anchoredPosition = anchoredPosition;
			}
		}

		private static void SyncUI()
		{
			if (GameMain.localPlanet == null)
			{
				return;
			}
			int id = GameMain.localPlanet.id;
			_isSyncing = true;
			try
			{
				if ((Object)(object)_modeToggle != (Object)null)
				{
					bool flag = TurretLogic.IsInRelayMode(id, _currentTurretId);
					if (_modeToggle.isOn != flag)
					{
						_modeToggle.isOn = flag;
					}
				}
				if ((Object)(object)_minInput != (Object)null && (Object)(object)_maxInput != (Object)null)
				{
					TurretConfig config = TurretLogic.GetConfig(id, _currentTurretId);
					float num = config?.MinHp ?? 0.1f;
					float num2 = config?.MaxHp ?? 0.95f;
					_minInput.text = Mathf.RoundToInt(num * 100f).ToString();
					_maxInput.text = Mathf.RoundToInt(num2 * 100f).ToString();
				}
			}
			finally
			{
				_isSyncing = false;
			}
		}

		private static void CreateOverlayUI(UITurretWindow window)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: 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_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Expected O, but got Unknown
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_02d4: 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_02ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Expected O, but got Unknown
			//IL_0322: Unknown result type (might be due to invalid IL or missing references)
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_0350: Unknown result type (might be due to invalid IL or missing references)
			//IL_0367: Unknown result type (might be due to invalid IL or missing references)
			//IL_037e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0402: Unknown result type (might be due to invalid IL or missing references)
			//IL_0412: Unknown result type (might be due to invalid IL or missing references)
			//IL_0419: Expected O, but got Unknown
			//IL_0443: Unknown result type (might be due to invalid IL or missing references)
			//IL_045a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0471: Unknown result type (might be due to invalid IL or missing references)
			//IL_0488: Unknown result type (might be due to invalid IL or missing references)
			//IL_049f: 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_04f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f9: Expected O, but got Unknown
			//IL_0519: Unknown result type (might be due to invalid IL or missing references)
			//IL_0539: Unknown result type (might be due to invalid IL or missing references)
			//IL_0550: Unknown result type (might be due to invalid IL or missing references)
			//IL_0567: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0612: Unknown result type (might be due to invalid IL or missing references)
			//IL_0629: Unknown result type (might be due to invalid IL or missing references)
			//IL_0640: Unknown result type (might be due to invalid IL or missing references)
			//IL_0681: Unknown result type (might be due to invalid IL or missing references)
			//IL_0688: Expected O, but got Unknown
			//IL_06b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_06cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_06fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0716: Unknown result type (might be due to invalid IL or missing references)
			//IL_0733: Unknown result type (might be due to invalid IL or missing references)
			//IL_0750: Unknown result type (might be due to invalid IL or missing references)
			//IL_066b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0670: Unknown result type (might be due to invalid IL or missing references)
			//IL_0676: Expected O, but got Unknown
			Transform val = ((Component)window).transform.Find("panel-bg");
			if ((Object)(object)val == (Object)null)
			{
				val = ((Component)window).transform;
			}
			Font val2 = ((IEnumerable<Font>)Resources.FindObjectsOfTypeAll<Font>()).FirstOrDefault((Func<Font, bool>)((Font f) => ((Object)f).name == "SAIRASEMICONDENSED-BOLD"));
			if ((Object)(object)val2 == (Object)null)
			{
				val2 = Resources.GetBuiltinResource<Font>("Arial.ttf");
			}
			_settingsBtnObj = CreateButton("TacticalBtn", "战术设置", val, new Vector2(-70f, 10f), new Vector2(80f, 24f), val2, 12);
			RectTransform component = _settingsBtnObj.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(1f, 0f);
			component.anchorMax = new Vector2(1f, 0f);
			component.pivot = new Vector2(1f, 0f);
			ButtonClickedEvent onClick = _settingsBtnObj.GetComponent<Button>().onClick;
			object obj = <>c.<>9__23_1;
			if (obj == null)
			{
				UnityAction val3 = delegate
				{
					if ((Object)(object)_menuPanelObj != (Object)null)
					{
						_menuPanelObj.SetActive(!_menuPanelObj.activeSelf);
					}
				};
				<>c.<>9__23_1 = val3;
				obj = (object)val3;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
			_mainStatusText = CreateLabel("MainStatusText", "", val, new Vector2(25f, 10f), val2, 11, (TextAnchor)3, new Vector2(250f, 20f)).GetComponent<Text>();
			((Graphic)_mainStatusText).color = Color.yellow;
			_mainStatusText.horizontalOverflow = (HorizontalWrapMode)1;
			((Graphic)_mainStatusText).raycastTarget = false;
			RectTransform component2 = ((Component)_mainStatusText).GetComponent<RectTransform>();
			component2.anchorMin = new Vector2(0f, 0f);
			component2.anchorMax = new Vector2(0f, 0f);
			component2.pivot = new Vector2(0f, 0f);
			_menuPanelObj = new GameObject("TacticalMenuPanel");
			_menuPanelObj.transform.SetParent(val, false);
			RectTransform val4 = _menuPanelObj.AddComponent<RectTransform>();
			val4.anchorMin = new Vector2(1f, 0f);
			val4.anchorMax = new Vector2(1f, 0f);
			val4.pivot = new Vector2(0f, 0f);
			val4.anchoredPosition = new Vector2(10f, 0f);
			val4.sizeDelta = new Vector2(230f, 160f);
			Image val5 = _menuPanelObj.AddComponent<Image>();
			Image component3 = ((Component)val).GetComponent<Image>();
			if ((Object)(object)component3 != (Object)null)
			{
				val5.sprite = component3.sprite;
				val5.type = (Type)1;
				((Graphic)val5).color = ((Graphic)component3).color;
			}
			else
			{
				((Graphic)val5).color = new Color(0.1f, 0.15f, 0.2f, 0.95f);
			}
			((Graphic)val5).raycastTarget = true;
			GameObject val6 = new GameObject("HeaderRow");
			val6.transform.SetParent(_menuPanelObj.transform, false);
			RectTransform val7 = val6.AddComponent<RectTransform>();
			val7.anchorMin = new Vector2(0f, 1f);
			val7.anchorMax = new Vector2(1f, 1f);
			val7.pivot = new Vector2(0.5f, 1f);
			val7.anchoredPosition = new Vector2(0f, 0f);
			val7.sizeDelta = new Vector2(0f, 25f);
			Image val8 = val6.AddComponent<Image>();
			((Graphic)val8).color = new Color(0f, 0f, 0f, 0.01f);
			val6.AddComponent<WindowDragHandler>();
			CreateLabel("Title", "战术压制配置", val6.transform, new Vector2(-70f, -15f), val2, 12, (TextAnchor)3, new Vector2(100f, 25f)).GetComponent<RectTransform>().pivot = new Vector2(0f, 0.5f);
			GameObject val9 = new GameObject("Toggle");
			val9.transform.SetParent(val6.transform, false);
			RectTransform val10 = val9.AddComponent<RectTransform>();
			val10.anchorMin = new Vector2(1f, 0.5f);
			val10.anchorMax = new Vector2(1f, 0.5f);
			val10.pivot = new Vector2(1f, 0.5f);
			val10.anchoredPosition = new Vector2(-85f, -15f);
			val10.sizeDelta = new Vector2(18f, 18f);
			_modeToggle = val9.AddComponent<Toggle>();
			Image val11 = val9.AddComponent<Image>();
			((Graphic)val11).color = new Color(0.3f, 0.3f, 0.3f, 1f);
			((Selectable)_modeToggle).targetGraphic = (Graphic)(object)val11;
			GameObject val12 = new GameObject("Checkmark");
			val12.transform.SetParent(val9.transform, false);
			Image val13 = val12.AddComponent<Image>();
			((Graphic)val13).color = Color.green;
			RectTransform component4 = val12.GetComponent<RectTransform>();
			component4.anchorMin = new Vector2(0.5f, 0.5f);
			component4.anchorMax = new Vector2(0.5f, 0.5f);
			component4.sizeDelta = new Vector2(12f, 12f);
			_modeToggle.graphic = (Graphic)(object)val13;
			((UnityEvent<bool>)(object)_modeToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool isOn)
			{
				if (!_isSyncing)
				{
					Debug.Log((object)$"[MissileControlMod] Toggle Clicked: {isOn}");
					if (GameMain.localPlanet != null)
					{
						int id = GameMain.localPlanet.id;
						try
						{
							TurretConfig orCreateConfig = TurretLogic.GetOrCreateConfig(id, _currentTurretId);
							if (orCreateConfig.RelayMode != isOn)
							{
								orCreateConfig.RelayMode = isOn;
								if (orCreateConfig.RelayMode)
								{
									TurretLogic.ScanRelays(GameMain.localPlanet.factory);
									TurretLogic.CycleNextRelay(id, _currentTurretId, GameMain.localPlanet.factory);
								}
								Debug.Log((object)$"[MissileControlMod] RelayMode set to {isOn}");
							}
							UpdateStatusText();
						}
						catch (Exception arg)
						{
							Debug.LogWarning((object)$"[MissileControlMod] Toggle Error: {arg}");
						}
					}
				}
			});
			GameObject val14 = CreateButton("CloseBtn", "X", val6.transform, new Vector2(0f, 0f), new Vector2(20f, 20f), val2, 11);
			RectTransform component5 = val14.GetComponent<RectTransform>();
			component5.anchorMin = new Vector2(1f, 0.5f);
			component5.anchorMax = new Vector2(1f, 0.5f);
			component5.pivot = new Vector2(1f, 0.5f);
			component5.anchoredPosition = new Vector2(-35f, -15f);
			ButtonClickedEvent onClick2 = val14.GetComponent<Button>().onClick;
			object obj2 = <>c.<>9__23_3;
			if (obj2 == null)
			{
				UnityAction val15 = delegate
				{
					_menuPanelObj.SetActive(false);
				};
				<>c.<>9__23_3 = val15;
				obj2 = (object)val15;
			}
			((UnityEvent)onClick2).AddListener((UnityAction)obj2);
			GameObject val16 = new GameObject("CenterGroup");
			val16.transform.SetParent(_menuPanelObj.transform, false);
			RectTransform val17 = val16.AddComponent<RectTransform>();
			val17.anchorMin = new Vector2(0.5f, 0.5f);
			val17.anchorMax = new Vector2(0.5f, 0.5f);
			val17.anchoredPosition = new Vector2(0f, -10f);
			val17.sizeDelta = new Vector2(220f, 120f);
			CreateThresholdsRow(val16.transform, new Vector2(0f, 20f), val2);
			CreateSelectorRow(val16.transform, new Vector2(0f, -20f), val2);
			CreateStatusRow(val16.transform, new Vector2(0f, -40f), val2);
		}

		private static void CreateThresholdsRow(Transform parent, Vector2 pos, Font font)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_002c: 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_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: 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_0181: 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)
			GameObject val2 = new GameObject("ThresholdsRow");
			val2.transform.SetParent(parent, false);
			RectTransform val3 = val2.AddComponent<RectTransform>();
			val3.anchorMin = new Vector2(0.5f, 0.5f);
			val3.anchorMax = new Vector2(0.5f, 0.5f);
			val3.anchoredPosition = pos;
			val3.sizeDelta = new Vector2(220f, 25f);
			CreateLabel("MinLabel", "停火阈值:", val2.transform, new Vector2(-75f, 0f), font, 11, (TextAnchor)5, new Vector2(50f, 25f));
			_minInput = CreateInputField("MinInput", val2.transform, new Vector2(-30f, 0f), "10", font);
			CreateLabel("MinUnit", "%", val2.transform, new Vector2(-1f, 0f), font, 11, (TextAnchor)3, new Vector2(20f, 25f));
			CreateLabel("MaxLabel", "攻击阈值:", val2.transform, new Vector2(25f, 0f), font, 11, (TextAnchor)5, new Vector2(50f, 25f));
			_maxInput = CreateInputField("MaxInput", val2.transform, new Vector2(70f, 0f), "95", font);
			CreateLabel("MaxUnit", "%", val2.transform, new Vector2(98f, 0f), font, 11, (TextAnchor)3, new Vector2(20f, 25f));
			((UnityEvent<string>)(object)_minInput.onEndEdit).AddListener((UnityAction<string>)delegate
			{
				OnThresholdChanged();
			});
			((UnityEvent<string>)(object)_maxInput.onEndEdit).AddListener((UnityAction<string>)delegate
			{
				OnThresholdChanged();
			});
		}

		private static void CreateSelectorRow(Transform parent, Vector2 pos, Font font)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_002c: 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_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: 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_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			GameObject val = new GameObject("SelectorRow");
			val.transform.SetParent(parent, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = new Vector2(0.5f, 0.5f);
			val2.anchorMax = new Vector2(0.5f, 0.5f);
			val2.anchoredPosition = pos;
			val2.sizeDelta = new Vector2(220f, 25f);
			GameObject val3 = CreateButton("SwitchBtn", "切换中继站", val.transform, new Vector2(40f, 0f), new Vector2(100f, 22f), font, 11);
			val3.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 0.5f);
			ButtonClickedEvent onClick = val3.GetComponent<Button>().onClick;
			object obj = <>c.<>9__25_0;
			if (obj == null)
			{
				UnityAction val4 = delegate
				{
					if (GameMain.localPlanet != null)
					{
						int id = GameMain.localPlanet.id;
						if (_currentTurretId != 0)
						{
							TurretLogic.ScanRelays(GameMain.localPlanet.factory);
							TurretLogic.CycleNextRelay(id, _currentTurretId, GameMain.localPlanet.factory);
							UpdateStatusText();
							Debug.Log((object)$"[MissileControlMod] Switched Relay. Current ID: {TurretLogic.GetConfig(id, _currentTurretId)?.TargetRelayId}");
						}
					}
				};
				<>c.<>9__25_0 = val4;
				obj = (object)val4;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj);
		}

		private static void CreateStatusRow(Transform parent, Vector2 pos, Font font)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_002c: 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_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("StatusRow");
			val.transform.SetParent(parent, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = new Vector2(0.5f, 0.5f);
			val2.anchorMax = new Vector2(0.5f, 0.5f);
			val2.anchoredPosition = pos;
			val2.sizeDelta = new Vector2(220f, 20f);
			_menuStatusText = CreateLabel("StatusText", "", val.transform, new Vector2(0f, 0f), font, 11, (TextAnchor)4, new Vector2(220f, 20f)).GetComponent<Text>();
			((Graphic)_menuStatusText).color = Color.yellow;
			_menuStatusText.horizontalOverflow = (HorizontalWrapMode)1;
		}

		private static InputField CreateInputField(string name, Transform parent, Vector2 localPos, string defaultVal, Font font)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = new Vector2(0.5f, 0.5f);
			val2.anchorMax = new Vector2(0.5f, 0.5f);
			val2.pivot = new Vector2(0.5f, 0.5f);
			val2.anchoredPosition = localPos;
			val2.sizeDelta = new Vector2(35f, 18f);
			Image val3 = val.AddComponent<Image>();
			((Graphic)val3).color = new Color(0.3f, 0.3f, 0.3f, 1f);
			((Graphic)val3).raycastTarget = true;
			InputField val4 = val.AddComponent<InputField>();
			val4.textComponent = CreateText(val.transform, defaultVal, font, 11, (TextAnchor)4);
			val4.text = defaultVal;
			val4.characterLimit = 3;
			val4.contentType = (ContentType)2;
			((Selectable)val4).interactable = true;
			return val4;
		}

		private static Text CreateText(Transform parent, string defaultVal, Font font, int fontSize, TextAnchor alignment)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: 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)
			GameObject val = new GameObject("Text");
			val.transform.SetParent(parent, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = Vector2.zero;
			val2.anchorMax = Vector2.one;
			val2.sizeDelta = Vector2.zero;
			Text val3 = val.AddComponent<Text>();
			val3.text = defaultVal;
			val3.font = font;
			((Graphic)val3).color = Color.white;
			val3.fontSize = fontSize;
			val3.alignment = alignment;
			((Graphic)val3).raycastTarget = false;
			return val3;
		}

		private static GameObject CreateLabel(string name, string text, Transform parent, Vector2 pos, Font font, int fontSize, TextAnchor align, Vector2 size)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: 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_009e: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = new Vector2(0.5f, 0.5f);
			val2.anchorMax = new Vector2(0.5f, 0.5f);
			val2.pivot = new Vector2(0.5f, 0.5f);
			val2.anchoredPosition = pos;
			val2.sizeDelta = size;
			Text val3 = val.AddComponent<Text>();
			val3.text = text;
			val3.font = font;
			((Graphic)val3).color = Color.gray;
			val3.fontSize = fontSize;
			val3.alignment = align;
			return val;
		}

		private static GameObject CreateButton(string name, string text, Transform parent, Vector2 pos, Vector2 size, Font font, int fontSize)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: 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_0037: 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_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_00de: 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_0114: 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)
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent, false);
			RectTransform val2 = val.AddComponent<RectTransform>();
			val2.anchorMin = Vector2.zero;
			val2.anchorMax = Vector2.zero;
			val2.anchoredPosition = pos + new Vector2(size.x / 2f, size.y / 2f);
			val2.sizeDelta = size;
			Button val3 = val.AddComponent<Button>();
			Image val4 = val.AddComponent<Image>();
			((Graphic)val4).color = new Color(0.3f, 0.3f, 0.3f, 1f);
			((Selectable)val3).targetGraphic = (Graphic)(object)val4;
			GameObject val5 = new GameObject("Text");
			val5.transform.SetParent(val.transform, false);
			Text val6 = val5.AddComponent<Text>();
			val6.text = text;
			val6.font = font;
			((Graphic)val6).color = Color.white;
			val6.fontSize = fontSize;
			val6.alignment = (TextAnchor)4;
			RectTransform component = val5.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.sizeDelta = Vector2.zero;
			return val;
		}

		private static void OnThresholdChanged()
		{
			if (GameMain.localPlanet != null && _currentTurretId != 0 && !((Object)(object)_minInput == (Object)null) && !((Object)(object)_maxInput == (Object)null))
			{
				int id = GameMain.localPlanet.id;
				if (int.TryParse(_minInput.text, out var result) && int.TryParse(_maxInput.text, out var result2))
				{
					float num = (float)Mathf.Clamp(result, 1, 99) / 100f;
					float num2 = (float)Mathf.Clamp(result2, result + 1, 100) / 100f;
					TurretLogic.SetThresholds(id, _currentTurretId, num, num2);
					_minInput.text = Mathf.RoundToInt(num * 100f).ToString();
					_maxInput.text = Mathf.RoundToInt(num2 * 100f).ToString();
				}
			}
		}

		private static void UpdateStatusText()
		{
			if (GameMain.localPlanet != null)
			{
				int id = GameMain.localPlanet.id;
				string value = "";
				long uniqueId = TurretLogic.GetUniqueId(id, _currentTurretId);
				bool flag = _currentTurretId != 0 && TurretLogic.monitorStatus.TryGetValue(uniqueId, out value);
				if ((Object)(object)_menuStatusText != (Object)null)
				{
					_menuStatusText.text = (flag ? value : "");
				}
				if ((Object)(object)_mainStatusText != (Object)null)
				{
					bool flag2 = _currentTurretId != 0 && TurretLogic.IsInRelayMode(id, _currentTurretId);
					_mainStatusText.text = ((flag2 && flag) ? value : "");
				}
			}
		}
	}
}