Decompiled source of Siege Mod v0.1.6

BepInEx\plugins\SiegeMod\SkyfallSiege.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Landfall.TABS;
using Landfall.TABS.GameMode;
using Landfall.TABS.GameState;
using Landfall.TABS.WinConditions;
using Landfall.TABS.Workshop;
using TFBGames;
using UnityEngine;
using UnityEngine.SceneManagement;

[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: AssemblyVersion("0.0.0.0")]
namespace SkyfallSiege;

[BepInPlugin("skyfall.tabs.siege", "Siege Mod", "0.1.6")]
public sealed class Plugin : BaseUnityPlugin
{
	private sealed class Entry
	{
		public UnitBlueprint Blueprint;

		public Vector3 Position;

		public Quaternion Rotation;

		public bool IsSkyfallTank;

		public bool Foot;

		public Team Side;
	}

	private sealed class Activation
	{
		public Unit Unit;

		public float Deadline;

		public Team Side;
	}

	private sealed class WavePick
	{
		public Unit Bound;

		public string BlueprintName;

		public string BaseName;

		public Team Side;

		public Vector3 Position;

		public Quaternion Rotation;
	}

	private readonly List<WavePick>[] savedAttackers = (from i in Enumerable.Range(0, 20)
		select new List<WavePick>()).ToArray();

	private readonly List<WavePick>[] savedDefenders = (from i in Enumerable.Range(0, 20)
		select new List<WavePick>()).ToArray();

	private readonly List<Unit>[] groups = (from i in Enumerable.Range(0, 20)
		select new List<Unit>()).ToArray();

	private readonly List<Unit>[] defenderGroups = (from i in Enumerable.Range(0, 20)
		select new List<Unit>()).ToArray();

	private readonly List<Entry>[] roundDefenderGroups = (from i in Enumerable.Range(0, 20)
		select new List<Entry>()).ToArray();

	private readonly List<Entry>[] roundGroups = (from i in Enumerable.Range(0, 20)
		select new List<Entry>()).ToArray();

	private readonly List<Unit> hiddenDeploymentTemplates = new List<Unit>();

	private readonly Dictionary<Unit, HashSet<GameObject>> concealedTankVisuals = new Dictionary<Unit, HashSet<GameObject>>();

	private bool tankVisualStartPatched;

	private readonly Dictionary<Unit, GameObject> selectionGlows = new Dictionary<Unit, GameObject>();

	private readonly Queue<Entry> pending = new Queue<Entry>();

	private readonly List<Activation> activating = new List<Activation>();

	private readonly HashSet<Unit> spawned = new HashSet<Unit>();

	private ConfigEntry<bool> enabledMode;

	private ConfigEntry<bool> redAttacks;

	private ConfigEntry<bool> waitUntilClear;

	private ConfigEntry<bool> defenderReinforcements;

	private ConfigEntry<int> waveCount;

	private ConfigEntry<int> spawnBudget;

	private ConfigEntry<float> firstDelay;

	private ConfigEntry<float> waveInterval;

	private static Plugin instance;

	private Harmony harmony;

	private MethodInfo decide;

	private bool ready;

	private bool armed;

	private bool running;

	private bool finished;

	private bool nativeFinish;

	private bool panel = true;

	private bool roundWait;

	private Team roundAttack;

	private bool editDefenders;

	private int defenderUnitsSent;

	private int editWave;

	private int roundCount;

	private int wavesSent;

	private int waveMembers;

	private int unitsSent;

	private int sceneHandle = -1;

	private int previousPhase = -1;

	private float nextWave;

	private float nextTick;

	private float nextValidation;

	private float roundFirst;

	private float roundInterval;

	private float confirmClearUntil;

	private bool clearing;

	private bool dispatching;

	private Vector2 scroll;

	private readonly HashSet<Unit> dragVisited = new HashSet<Unit>();

	private bool dragActive;

	private bool dragHasMode;

	private bool dragRemove;

	private bool dragDefenders;

	private bool suppressPlacementUntilRelease;

	private int dragWave;

	private Team dragTeam;

	private Vector3 dragPrevious;

	private string status = "Enable Siege for the next sandbox battle. Selected wave units will disappear at battle start and only spawn on their assigned waves.";

	private string selectionMessage = "Choose a wave, then Alt+click or Alt+drag across units.";

	private static readonly int PlacementPhase = 0;

	private static readonly int BattlePhase = 1;

	private Type tankMarker;

	private bool tankMarkerResolved;

	private Team Attack
	{
		get
		{
			if (redAttacks.Value)
			{
				return (Team)0;
			}
			return (Team)1;
		}
	}

	private int WaveCount => Mathf.Clamp(waveCount.Value, 1, 20);

	private bool EditingDefenders
	{
		get
		{
			if (defenderReinforcements.Value)
			{
				return editDefenders;
			}
			return false;
		}
	}

	private List<Unit>[] EditGroups
	{
		get
		{
			if (!EditingDefenders)
			{
				return groups;
			}
			return defenderGroups;
		}
	}

	private List<WavePick>[] EditPicks
	{
		get
		{
			if (!EditingDefenders)
			{
				return savedAttackers;
			}
			return savedDefenders;
		}
	}

	private Team EditTeam
	{
		get
		{
			//IL_0010: 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_0009: Unknown result type (might be due to invalid IL or missing references)
			if (!EditingDefenders)
			{
				return Attack;
			}
			return Other(Attack);
		}
	}

	private static BaseGameMode Mode()
	{
		GameModeService service = ServiceLocator.GetService<GameModeService>();
		if (!((Object)(object)service == (Object)null))
		{
			return service.CurrentGameMode;
		}
		return null;
	}

	private static int Phase()
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected I4, but got Unknown
		GameStateManager service = ServiceLocator.GetService<GameStateManager>();
		if (service != null)
		{
			return (int)service.GameState;
		}
		return -1;
	}

	private static bool Alive(Unit u)
	{
		if ((Object)(object)u != (Object)null && ((Component)u).gameObject.activeInHierarchy && (Object)(object)u.data != (Object)null)
		{
			return !u.data.Dead;
		}
		return false;
	}

	private static Team Other(Team t)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		if ((int)t == 0)
		{
			return (Team)1;
		}
		return (Team)0;
	}

	private void Awake()
	{
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_025f: Expected O, but got Unknown
		//IL_0276: Unknown result type (might be due to invalid IL or missing references)
		//IL_028b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0298: Expected O, but got Unknown
		//IL_0298: Expected O, but got Unknown
		//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c3: Expected O, but got Unknown
		//IL_02db: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e9: Expected O, but got Unknown
		instance = this;
		enabledMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Rules", "Enabled", false, "Use Siege in sandbox. Disable other gamemodes first.");
		redAttacks = ((BaseUnityPlugin)this).Config.Bind<bool>("Rules", "RedAttacks", true, "Red attacks; turn off for Blue attacks.");
		defenderReinforcements = ((BaseUnityPlugin)this).Config.Bind<bool>("Rules", "DefenderReinforcements", false, "Enable separately selected defender groups on numbered waves.");
		waveCount = ((BaseUnityPlugin)this).Config.Bind<int>("Waves", "Count", 10, "Number of separately editable waves, 1-20.");
		firstDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Waves", "FirstDelay", 10f, "First wave delay in game seconds.");
		waveInterval = ((BaseUnityPlugin)this).Config.Bind<float>("Waves", "Interval", 45f, "Delay between complete waves, in game seconds.");
		waitUntilClear = ((BaseUnityPlugin)this).Config.Bind<bool>("Waves", "WaitUntilClear", true, "Start the next countdown only after all active attackers are gone.");
		spawnBudget = ((BaseUnityPlugin)this).Config.Bind<int>("Performance", "UnitsPerTick", 4, "Native spawn calls per 0.2 game seconds.");
		try
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(GameStateManager), "set_GameState", new Type[1] { typeof(GameState) }, (Type[])null);
			decide = AccessTools.Method(typeof(BaseGameMode), "DecideWinner", new Type[2]
			{
				typeof(Team),
				typeof(string)
			}, (Type[])null);
			if (methodInfo == null || decide == null || methodInfo.ReturnType != typeof(void) || decide.ReturnType != typeof(void))
			{
				throw new InvalidOperationException("Required native game hooks unavailable");
			}
			Type type = typeof(BaseGameMode).Assembly.GetType("Landfall.TABS.UnitPlacement.BrushBehaviourBase", throwOnError: false);
			MethodInfo methodInfo2 = ((type == null) ? null : AccessTools.Method(type, "PrimaryActionOnObject", new Type[2]
			{
				typeof(GameObject),
				typeof(Vector3)
			}, (Type[])null));
			if (methodInfo2 == null || methodInfo2.ReturnType != typeof(void))
			{
				throw new InvalidOperationException("Required placement input hook unavailable");
			}
			harmony = new Harmony("skyfall.tabs.siege");
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Plugin), "BeforeState", (Type[])null), new HarmonyMethod(typeof(Plugin), "AfterState", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)decide, new HarmonyMethod(typeof(Plugin), "BeforeWinner", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(Plugin), "BeforePrimaryPlacement", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			ready = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"[Siege] v0.1.6 ready; Alt+drag wave selection enabled; native placement blocked during Alt selection; wave selections persist across battle/placement and same-layout scene reloads.");
		}
		catch (Exception ex)
		{
			ready = false;
			((BaseUnityPlugin)this).Logger.LogError((object)ex);
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}

	private string Conflict()
	{
		string[] array = new string[3] { "SkyfallDomination.Plugin", "SkyfallAttrition.Plugin", "SkyfallHeadquarters.Plugin" };
		foreach (string text in array)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int j = 0; j < assemblies.Length; j++)
			{
				Type type = assemblies[j].GetType(text, throwOnError: false);
				if (type == null)
				{
					continue;
				}
				FieldInfo field = type.GetField("instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				object obj = ((field == null) ? null : field.GetValue(null));
				if (obj == null)
				{
					continue;
				}
				FieldInfo field2 = type.GetField("enabledMode", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				ConfigEntry<bool> val = ((field2 == null) ? null : (field2.GetValue(obj) as ConfigEntry<bool>));
				if (val != null && !val.Value)
				{
					continue;
				}
				if (text.Contains("Domination"))
				{
					FieldInfo field3 = type.GetField("flags", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					ICollection collection = ((field3 == null) ? null : (field3.GetValue(obj) as ICollection));
					if (collection != null && collection.Count == 0)
					{
						continue;
					}
				}
				return text.Split(new char[1] { '.' })[0];
			}
		}
		return null;
	}

	private Rect PanelRect()
	{
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		float num = ((Screen.height >= 500) ? 354f : Mathf.Max(16f, (float)Screen.height * 0.5f));
		float num2 = Mathf.Max(90f, (float)Screen.height - num - 16f);
		float num3 = ((Phase() != PlacementPhase) ? Mathf.Min(150f, num2) : (enabledMode.Value ? num2 : Mathf.Min(68f, num2)));
		return new Rect(16f, num, Mathf.Min(360f, (float)Screen.width - 32f), num3);
	}

	private void ClearGlows()
	{
		foreach (GameObject value in selectionGlows.Values)
		{
			if ((Object)(object)value != (Object)null)
			{
				value.SetActive(false);
				Object.Destroy((Object)(object)value);
			}
		}
		selectionGlows.Clear();
	}

	private void ClearGroups()
	{
		EndSelectionDrag();
		ClearGlows();
		List<Unit>[] array = groups;
		for (int i = 0; i < array.Length; i++)
		{
			array[i].Clear();
		}
		array = defenderGroups;
		for (int i = 0; i < array.Length; i++)
		{
			array[i].Clear();
		}
		List<WavePick>[] array2 = savedAttackers;
		for (int i = 0; i < array2.Length; i++)
		{
			array2[i].Clear();
		}
		array2 = savedDefenders;
		for (int i = 0; i < array2.Length; i++)
		{
			array2[i].Clear();
		}
	}

	private static WavePick CopyPick(WavePick original)
	{
		//IL_002b: 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_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		return new WavePick
		{
			Bound = original.Bound,
			BlueprintName = original.BlueprintName,
			BaseName = original.BaseName,
			Side = original.Side,
			Position = original.Position,
			Rotation = original.Rotation
		};
	}

	private static bool SameBlueprint(WavePick pick, Unit unit)
	{
		//IL_0030: 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)
		if (pick == null || (Object)(object)unit == (Object)null || (Object)(object)unit.unitBlueprint == (Object)null || (Object)(object)unit.unitBlueprint.UnitBase == (Object)null)
		{
			return false;
		}
		if (pick.Side == unit.Team && string.Equals(pick.BlueprintName, BlueprintName(unit.unitBlueprint), StringComparison.Ordinal))
		{
			return string.Equals(pick.BaseName, ((Object)unit.unitBlueprint.UnitBase).name, StringComparison.Ordinal);
		}
		return false;
	}

	private static bool NearOriginalPlacement(WavePick pick, Entry actual)
	{
		//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_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: 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_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: 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)
		if (pick == null || actual == null || (Object)(object)actual.Blueprint == (Object)null || (Object)(object)actual.Blueprint.UnitBase == (Object)null)
		{
			return false;
		}
		if (pick.Side != actual.Side || !string.Equals(pick.BlueprintName, BlueprintName(actual.Blueprint), StringComparison.Ordinal) || !string.Equals(pick.BaseName, ((Object)actual.Blueprint.UnitBase).name, StringComparison.Ordinal))
		{
			return false;
		}
		Vector3 val = pick.Position - actual.Position;
		if (((Vector3)(ref val)).sqrMagnitude > 0.5625f)
		{
			return false;
		}
		return Quaternion.Angle(pick.Rotation, actual.Rotation) <= 35f;
	}

	private static WavePick MakePick(Unit unit, Entry entry)
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		return new WavePick
		{
			Bound = unit,
			BlueprintName = BlueprintName(entry.Blueprint),
			BaseName = ((Object)entry.Blueprint.UnitBase).name,
			Side = entry.Side,
			Position = entry.Position,
			Rotation = entry.Rotation
		};
	}

	private Dictionary<Unit, Entry> PlacementEntries()
	{
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: 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_00ba: 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)
		Dictionary<Unit, Entry> dictionary = new Dictionary<Unit, Entry>();
		BaseGameMode val = Mode();
		RuntimeReferenceService service = ServiceLocator.GetService<RuntimeReferenceService>();
		if (val == null || val.TeamLayouts == null || (Object)(object)service == (Object)null)
		{
			return dictionary;
		}
		Team[] array = (Team[])(object)new Team[2]
		{
			default(Team),
			(Team)1
		};
		foreach (Team val2 in array)
		{
			List<TABSLayoutUnit> teamLayout = val.TeamLayouts.GetTeamLayout(val2);
			if (teamLayout == null)
			{
				continue;
			}
			foreach (TABSLayoutUnit item in teamLayout)
			{
				if (item != null && item.RuntimeReference != null)
				{
					Unit referenceTarget = service.GetReferenceTarget<Unit>((RuntimeReference)(object)item.RuntimeReference);
					if (!((Object)(object)referenceTarget == (Object)null) && referenceTarget.Team == val2 && !IsHQ(referenceTarget) && ValidWaveBlueprint(referenceTarget.unitBlueprint))
					{
						dictionary[referenceTarget] = MakeEntry(referenceTarget, item.m_position, item.GetRotation());
					}
				}
			}
		}
		return dictionary;
	}

	private void Reconcile()
	{
		//IL_00c5: 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_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: 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_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		editWave = Mathf.Clamp(editWave, 0, WaveCount - 1);
		Dictionary<Unit, Entry> dictionary = PlacementEntries();
		int[] array = new int[2] { 0, 1 };
		foreach (int num in array)
		{
			List<WavePick>[] array2 = ((num == 0) ? savedAttackers : savedDefenders);
			List<Unit>[] array3 = ((num == 0) ? groups : defenderGroups);
			for (int j = 0; j < 20; j++)
			{
				array3[j].Clear();
				HashSet<Unit> hashSet = new HashSet<Unit>();
				foreach (WavePick item in array2[j])
				{
					Unit val = item.Bound;
					if ((Object)(object)val != (Object)null && dictionary.TryGetValue(val, out var value) && SameBlueprint(item, val) && !hashSet.Contains(val))
					{
						item.Position = value.Position;
						item.Rotation = value.Rotation;
					}
					else
					{
						val = null;
						float num2 = float.MaxValue;
						foreach (KeyValuePair<Unit, Entry> item2 in dictionary)
						{
							if (!hashSet.Contains(item2.Key) && NearOriginalPlacement(item, item2.Value))
							{
								Vector3 val2 = item.Position - item2.Value.Position;
								float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
								if (!(sqrMagnitude >= num2))
								{
									num2 = sqrMagnitude;
									val = item2.Key;
								}
							}
						}
						item.Bound = val;
					}
					if ((Object)(object)val != (Object)null)
					{
						hashSet.Add(val);
						array3[j].Add(val);
					}
				}
			}
		}
	}

	private string MissingWaveSummary(List<WavePick>[] saved, bool defenders)
	{
		List<string> list = new List<string>();
		for (int i = 0; i < saved.Length; i++)
		{
			int num = saved[i].Count((WavePick pick) => (Object)(object)pick.Bound == (Object)null);
			if (num != 0)
			{
				bool flag = i >= WaveCount || (defenders && !defenderReinforcements.Value);
				list.Add(i + 1 + " (" + num + " missing" + (flag ? ", inactive" : "") + ")");
			}
		}
		return string.Join(", ", list.ToArray());
	}

	private void UnbindPicksForSceneReload()
	{
		ClearGlows();
		foreach (List<WavePick> item in savedAttackers.Concat(savedDefenders))
		{
			foreach (WavePick item2 in item)
			{
				item2.Bound = null;
			}
		}
		List<Unit>[] array = groups;
		for (int i = 0; i < array.Length; i++)
		{
			array[i].Clear();
		}
		array = defenderGroups;
		for (int i = 0; i < array.Length; i++)
		{
			array[i].Clear();
		}
	}

	private static void CopyWave(List<WavePick> from, List<WavePick> to)
	{
		to.Clear();
		foreach (WavePick item in from)
		{
			to.Add(CopyPick(item));
		}
	}

	private void RefreshGlows()
	{
		//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Expected O, but got Unknown
		if (!enabledMode.Value || Phase() != PlacementPhase)
		{
			ClearGlows();
			return;
		}
		List<Unit> list = EditGroups[editWave];
		KeyValuePair<Unit, GameObject>[] array = selectionGlows.ToArray();
		for (int i = 0; i < array.Length; i++)
		{
			KeyValuePair<Unit, GameObject> keyValuePair = array[i];
			if ((Object)(object)keyValuePair.Key == (Object)null || !list.Contains(keyValuePair.Key))
			{
				if ((Object)(object)keyValuePair.Value != (Object)null)
				{
					keyValuePair.Value.SetActive(false);
					Object.Destroy((Object)(object)keyValuePair.Value);
				}
				selectionGlows.Remove(keyValuePair.Key);
			}
		}
		foreach (Unit item in list)
		{
			if (!((Object)(object)item == (Object)null) && !selectionGlows.ContainsKey(item))
			{
				GameObject val = new GameObject("Skyfall_Siege_Selected_Wave_" + (editWave + 1));
				val.transform.SetParent(((Component)item).transform, false);
				MakeGlow(item, val);
				selectionGlows.Add(item, val);
			}
		}
	}

	private static bool AltHeld()
	{
		if (!Input.GetKey((KeyCode)308))
		{
			return Input.GetKey((KeyCode)307);
		}
		return true;
	}

	private bool BlockNativePlacement()
	{
		if (!ready || !enabledMode.Value || !(Mode() is SandboxGameMode) || Phase() != PlacementPhase)
		{
			suppressPlacementUntilRelease = false;
			return false;
		}
		bool flag = AltHeld();
		bool mouseButton = Input.GetMouseButton(0);
		if (!mouseButton || (Input.GetMouseButtonDown(0) && !flag))
		{
			suppressPlacementUntilRelease = false;
		}
		if (flag && mouseButton)
		{
			suppressPlacementUntilRelease = true;
		}
		if (!flag)
		{
			return suppressPlacementUntilRelease;
		}
		return true;
	}

	private static bool BeforePrimaryPlacement()
	{
		Plugin plugin = instance;
		if (!((Object)(object)plugin == (Object)null))
		{
			return !plugin.BlockNativePlacement();
		}
		return true;
	}

	private void EndSelectionDrag()
	{
		dragActive = false;
		dragHasMode = false;
		dragVisited.Clear();
	}

	private bool OverSiegePanel(Vector3 mouse)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: 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)
		if (panel)
		{
			Rect val = PanelRect();
			return ((Rect)(ref val)).Contains(new Vector2(mouse.x, (float)Screen.height - mouse.y));
		}
		return false;
	}

	private Unit PickAt(Camera camera, Vector3 mouse, Dictionary<Unit, Entry> available)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: 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_00fc: 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_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: 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_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0133: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: 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)
		Unit val = null;
		float num = float.MaxValue;
		RaycastHit[] array = Physics.RaycastAll(camera.ScreenPointToRay(mouse), 10000f, -5, (QueryTriggerInteraction)2);
		for (int i = 0; i < array.Length; i++)
		{
			RaycastHit val2 = array[i];
			if (!((Object)(object)((RaycastHit)(ref val2)).collider == (Object)null))
			{
				Unit componentInParent = ((Component)((RaycastHit)(ref val2)).collider).GetComponentInParent<Unit>();
				if ((Object)(object)componentInParent != (Object)null && available.ContainsKey(componentInParent) && ((RaycastHit)(ref val2)).distance < num)
				{
					val = componentInParent;
					num = ((RaycastHit)(ref val2)).distance;
				}
			}
		}
		if ((Object)(object)val == (Object)null)
		{
			float num2 = 1764f;
			foreach (Unit key in available.Keys)
			{
				if ((Object)(object)key == (Object)null)
				{
					continue;
				}
				Vector3 val3 = (((Object)(object)key.data != (Object)null && (Object)(object)key.data.mainRig != (Object)null) ? key.data.mainRig.position : ((Component)key).transform.position);
				Vector3 val4 = camera.WorldToScreenPoint(val3 + Vector3.up * 1.25f);
				if (!(val4.z <= 0f))
				{
					Vector2 val5 = new Vector2(val4.x - mouse.x, val4.y - mouse.y);
					float sqrMagnitude = ((Vector2)(ref val5)).sqrMagnitude;
					if (sqrMagnitude < num2)
					{
						val = key;
						num2 = sqrMagnitude;
					}
				}
			}
		}
		return val;
	}

	private bool PaintUnit(Unit chosen, Dictionary<Unit, Entry> available)
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)chosen == (Object)null || chosen.Team != dragTeam || !dragVisited.Add(chosen))
		{
			return false;
		}
		if (!available.TryGetValue(chosen, out var selected))
		{
			return false;
		}
		List<WavePick> list = EditPicks[editWave];
		int num = list.FindIndex((WavePick p) => (Object)(object)p.Bound == (Object)(object)chosen);
		if (num < 0)
		{
			num = list.FindIndex((WavePick p) => (Object)(object)p.Bound == (Object)null && NearOriginalPlacement(p, selected));
		}
		if (!dragHasMode)
		{
			dragRemove = num >= 0;
			dragHasMode = true;
		}
		if (dragRemove)
		{
			if (num < 0)
			{
				return false;
			}
			list.RemoveAt(num);
		}
		else
		{
			if (num >= 0)
			{
				return false;
			}
			list.Add(MakePick(chosen, selected));
		}
		return true;
	}

	private void UpdateSelectionDrag(bool alt)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: 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_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: 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)
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: 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_0117: 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_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_0164: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
		if (!alt || !Input.GetMouseButton(0))
		{
			EndSelectionDrag();
			return;
		}
		Vector3 mousePosition = Input.mousePosition;
		if (Input.GetMouseButtonDown(0))
		{
			EndSelectionDrag();
			if (OverSiegePanel(mousePosition) || Conflict() != null)
			{
				return;
			}
			dragActive = true;
			dragWave = editWave;
			dragDefenders = EditingDefenders;
			dragTeam = EditTeam;
			dragPrevious = mousePosition;
		}
		if (!dragActive)
		{
			return;
		}
		if (dragWave != editWave || dragDefenders != EditingDefenders || dragTeam != EditTeam || OverSiegePanel(mousePosition) || Conflict() != null)
		{
			EndSelectionDrag();
			return;
		}
		bool mouseButtonDown = Input.GetMouseButtonDown(0);
		float num = Vector3.Distance(dragPrevious, mousePosition);
		if (!mouseButtonDown && num < 1f)
		{
			return;
		}
		Camera val = PlacementCamera();
		if ((Object)(object)val == (Object)null)
		{
			EndSelectionDrag();
			return;
		}
		Dictionary<Unit, Entry> available = PlacementEntries();
		int num2 = Mathf.Clamp(Mathf.CeilToInt(num / 16f), 1, 12);
		int num3 = 0;
		for (int i = 1; i <= num2; i++)
		{
			Vector3 mouse = Vector3.Lerp(dragPrevious, mousePosition, (float)i / (float)num2);
			if (OverSiegePanel(mouse))
			{
				EndSelectionDrag();
				break;
			}
			Unit chosen = PickAt(val, mouse, available);
			if (PaintUnit(chosen, available))
			{
				num3++;
			}
		}
		dragPrevious = mousePosition;
		if (num3 > 0)
		{
			Reconcile();
			selectionMessage = (dragDefenders ? "Defender" : "Attacker") + " wave " + (dragWave + 1) + ": " + EditPicks[editWave].Count + " assigned.";
		}
		else if (mouseButtonDown && !dragHasMode)
		{
			selectionMessage = "Select a placed " + ((object)EditTeam/*cast due to .constrained prefix*/).ToString() + " unit for this group.";
		}
	}

	private void OnApplicationFocus(bool focused)
	{
		if (!focused)
		{
			EndSelectionDrag();
			suppressPlacementUntilRelease = false;
		}
	}

	private static bool Starts(string label, params string[] values)
	{
		return values.Any((string v) => label.StartsWith(v, StringComparison.OrdinalIgnoreCase));
	}

	private static Entry MakeEntry(Unit u, Vector3 pos, Quaternion rotation)
	{
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: 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_00b9: Unknown result type (might be due to invalid IL or missing references)
		string obj = ((Object)u.unitBlueprint.UnitBase).name ?? "";
		string label = BlueprintName(u.unitBlueprint);
		bool flag = obj.IndexOf("Leg_Tank", StringComparison.OrdinalIgnoreCase) >= 0;
		bool flag2 = flag || Starts(label, "Skyfall Sd.Kfz. 251", "Skyfall Yak-3", "Skyfall Bf 109", "Skyfall Fw 190", "Skyfall Me 262", "Skyfall Spitfire", "Skyfall Dive Bomber");
		return new Entry
		{
			Blueprint = u.unitBlueprint,
			Position = pos,
			Rotation = rotation,
			IsSkyfallTank = flag,
			Foot = !flag2,
			Side = u.Team
		};
	}

	private void Prepare(BaseGameMode mode)
	{
		//IL_003a: 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)
		//IL_0191: 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_01e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_0217: 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_0388: Unknown result type (might be due to invalid IL or missing references)
		//IL_038e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0393: Unknown result type (might be due to invalid IL or missing references)
		ResetRound();
		string text = Conflict();
		if (text != null)
		{
			throw new InvalidOperationException("Disable " + text + " before Siege.");
		}
		TryInstallTankVisualObserver();
		Reconcile();
		roundAttack = Attack;
		roundCount = WaveCount;
		roundWait = waitUntilClear.Value;
		for (int i = 0; i < roundCount; i++)
		{
			if (savedAttackers[i].Count != groups[i].Count)
			{
				throw new InvalidOperationException("Attacker wave " + (i + 1) + " has missing placement units. Re-place those units or clear/reselect that wave.");
			}
			if (defenderReinforcements.Value && savedDefenders[i].Count != defenderGroups[i].Count)
			{
				throw new InvalidOperationException("Defender wave " + (i + 1) + " has missing placement units. Re-place those units or clear/reselect that wave.");
			}
		}
		roundFirst = Mathf.Clamp(firstDelay.Value, 0f, 180f);
		roundInterval = Mathf.Clamp(waveInterval.Value, 1f, 300f);
		RuntimeReferenceService service = ServiceLocator.GetService<RuntimeReferenceService>();
		if ((Object)(object)service == (Object)null || mode.TeamLayouts == null)
		{
			throw new InvalidOperationException("Placement references unavailable");
		}
		Dictionary<Unit, Entry> dictionary = new Dictionary<Unit, Entry>();
		HashSet<Unit> hashSet = new HashSet<Unit>();
		Team[] array = (Team[])(object)new Team[2]
		{
			default(Team),
			(Team)1
		};
		foreach (Team val in array)
		{
			List<TABSLayoutUnit> teamLayout = mode.TeamLayouts.GetTeamLayout(val);
			if (teamLayout == null)
			{
				continue;
			}
			foreach (TABSLayoutUnit item in teamLayout)
			{
				if (item == null || item.RuntimeReference == null)
				{
					continue;
				}
				Unit referenceTarget = service.GetReferenceTarget<Unit>((RuntimeReference)(object)item.RuntimeReference);
				if (!((Object)(object)referenceTarget == (Object)null) && referenceTarget.Team == val)
				{
					if (val != roundAttack)
					{
						hashSet.Add(referenceTarget);
					}
					if (ValidWaveBlueprint(referenceTarget.unitBlueprint))
					{
						dictionary[referenceTarget] = MakeEntry(referenceTarget, item.m_position, item.GetRotation());
					}
				}
			}
		}
		if (hashSet.Count == 0)
		{
			throw new InvalidOperationException("Place at least one defending unit.");
		}
		HashSet<Unit> templates = new HashSet<Unit>();
		for (int k = 0; k < roundCount; k++)
		{
			foreach (Unit item2 in groups[k])
			{
				if ((Object)(object)item2 != (Object)null && dictionary.TryGetValue(item2, out var value) && value.Side == roundAttack)
				{
					roundGroups[k].Add(value);
					templates.Add(item2);
				}
			}
			if (roundGroups[k].Count == 0)
			{
				throw new InvalidOperationException("Wave " + (k + 1) + " has no units. Fill it or reduce wave count.");
			}
		}
		if (defenderReinforcements.Value)
		{
			for (int l = 0; l < roundCount; l++)
			{
				foreach (Unit item3 in defenderGroups[l])
				{
					if ((Object)(object)item3 != (Object)null && dictionary.TryGetValue(item3, out var value2) && value2.Side == Other(roundAttack))
					{
						roundDefenderGroups[l].Add(value2);
						templates.Add(item3);
					}
				}
			}
		}
		if (!hashSet.Any((Unit u) => !templates.Contains(u)))
		{
			throw new InvalidOperationException("Leave at least one defender unmarked to start the battle.");
		}
		hiddenDeploymentTemplates.AddRange(templates);
		armed = true;
		status = "Siege prepared: " + ((object)Unsafe.As<Team, Team>(ref roundAttack)/*cast due to .constrained prefix*/).ToString() + " attacks, " + roundCount + " waves. Selected wave units will deploy only on their assigned waves.";
		((BaseUnityPlugin)this).Logger.LogInfo((object)("[Siege] " + status + " Templates=" + templates.Count + " Wave sizes=" + string.Join(",", (from g in roundGroups.Take(roundCount)
			select g.Count.ToString()).ToArray()) + " Defender wave sizes=" + string.Join(",", (from g in roundDefenderGroups.Take(roundCount)
			select g.Count.ToString()).ToArray())));
	}

	private static void BeforeState(GameState __0)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Expected I4, but got Unknown
		Plugin plugin = instance;
		if ((Object)(object)plugin == (Object)null || !plugin.ready)
		{
			return;
		}
		try
		{
			int num = (int)__0;
			if (num != Phase())
			{
				if (num == PlacementPhase)
				{
					plugin.ResetRound();
					plugin.previousPhase = PlacementPhase;
				}
				else if (num == BattlePhase && Mode() is SandboxGameMode && plugin.enabledMode.Value && !plugin.armed)
				{
					plugin.Prepare(Mode());
					plugin.ClearGlows();
				}
			}
		}
		catch (Exception e)
		{
			plugin.Fail(e);
		}
	}

	private static void AfterState(GameState __0)
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Invalid comparison between Unknown and I4
		Plugin plugin = instance;
		if ((Object)(object)plugin == (Object)null || !plugin.ready || !plugin.armed || plugin.running || (int)__0 != BattlePhase || Phase() != BattlePhase)
		{
			return;
		}
		try
		{
			plugin.StartRound();
		}
		catch (Exception e)
		{
			plugin.Fail(e);
		}
	}

	private static bool BeforeWinner(BaseGameMode __instance)
	{
		Plugin plugin = instance;
		if (!((Object)(object)plugin == (Object)null) && plugin.ready && !plugin.nativeFinish && plugin.armed && !plugin.finished)
		{
			return !(__instance is SandboxGameMode);
		}
		return true;
	}

	private void StartRound()
	{
		Conceal();
		running = true;
		nextWave = Time.time + roundFirst;
		nextTick = Time.time + 0.5f;
		status = "Siege running | Selected wave templates hidden until their assigned wave.";
		((BaseUnityPlugin)this).Logger.LogInfo((object)("[Siege] Battle started; first wave after " + roundFirst + " seconds."));
	}

	private void Conceal()
	{
		for (int num = hiddenDeploymentTemplates.Count - 1; num >= 0; num--)
		{
			Unit val = hiddenDeploymentTemplates[num];
			if ((Object)(object)val == (Object)null)
			{
				hiddenDeploymentTemplates.RemoveAt(num);
			}
			else if (spawned.Contains(val))
			{
				hiddenDeploymentTemplates.RemoveAt(num);
				RestoreTankCosmetic(val);
			}
			else
			{
				ConcealTankCosmetic(val);
				if (((Component)val).gameObject.activeSelf)
				{
					((Component)val).gameObject.SetActive(false);
				}
			}
		}
	}

	private void Restore()
	{
		foreach (Unit hiddenDeploymentTemplate in hiddenDeploymentTemplates)
		{
			if (!((Object)(object)hiddenDeploymentTemplate == (Object)null))
			{
				if (!((Component)hiddenDeploymentTemplate).gameObject.activeSelf)
				{
					((Component)hiddenDeploymentTemplate).gameObject.SetActive(true);
				}
				RestoreTankCosmetic(hiddenDeploymentTemplate);
			}
		}
		KeyValuePair<Unit, HashSet<GameObject>>[] array = concealedTankVisuals.ToArray();
		foreach (KeyValuePair<Unit, HashSet<GameObject>> keyValuePair in array)
		{
			RestoreTankCosmetic(keyValuePair.Key);
		}
		concealedTankVisuals.Clear();
		hiddenDeploymentTemplates.Clear();
	}

	private void ResetRound()
	{
		Restore();
		armed = (running = (finished = (nativeFinish = (clearing = (dispatching = false)))));
		pending.Clear();
		activating.Clear();
		spawned.Clear();
		List<Entry>[] array = roundGroups;
		for (int i = 0; i < array.Length; i++)
		{
			array[i].Clear();
		}
		array = roundDefenderGroups;
		for (int i = 0; i < array.Length; i++)
		{
			array[i].Clear();
		}
		wavesSent = (waveMembers = (unitsSent = (defenderUnitsSent = 0)));
		nextWave = (nextTick = 0f);
		status = "Enable Siege for the next sandbox battle. Selected wave units will disappear at battle start and only spawn on their assigned waves.";
	}

	private void Fail(Exception e)
	{
		((BaseUnityPlugin)this).Logger.LogError((object)("[Siege] " + e));
		armed = (running = false);
		finished = true;
		pending.Clear();
		activating.Clear();
		Restore();
		status = "Siege stopped: " + e.Message + " | Native victory restored.";
	}

	private static Vector3 SpawnPoint(Entry e)
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: 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_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: 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_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: 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_005f: 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)
		//IL_0065: 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_007e: Unknown result type (might be due to invalid IL or missing references)
		if (!e.Foot)
		{
			return e.Position;
		}
		Vector3[] array = (Vector3[])(object)new Vector3[5]
		{
			Vector3.zero,
			Vector3.right,
			Vector3.left,
			Vector3.forward,
			Vector3.back
		};
		foreach (Vector3 val in array)
		{
			if (TrySupportedInfantryPoint(e.Position + val, e.Position.y, out var safe))
			{
				return safe;
			}
		}
		return e.Position;
	}

	private void SpawnOne(Entry e)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		GameObject[] array = e.Blueprint.Spawn(SpawnPoint(e), e.Rotation, e.Side, 1f, (UnitPoolInfo?)null);
		Unit val = null;
		if (array != null)
		{
			GameObject[] array2 = array;
			foreach (GameObject val2 in array2)
			{
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				Unit[] componentsInChildren = val2.GetComponentsInChildren<Unit>(true);
				foreach (Unit val3 in componentsInChildren)
				{
					if ((Object)(object)val3 != (Object)null && (Object)(object)val3.unitBlueprint == (Object)(object)e.Blueprint && val3.Team == e.Side)
					{
						val = val3;
						break;
					}
				}
				if ((Object)(object)val != (Object)null)
				{
					break;
				}
			}
		}
		if ((Object)(object)val == (Object)null)
		{
			throw new InvalidOperationException("Spawn returned no matching unit: " + BlueprintName(e.Blueprint));
		}
		hiddenDeploymentTemplates.Remove(val);
		RestoreTankCosmetic(val);
		spawned.Add(val);
		TagTank(e, val);
		if (e.Foot)
		{
			StabilizeNewInfantry(val);
		}
		if (Alive(val))
		{
			CountSpawn(e.Side);
			return;
		}
		activating.Add(new Activation
		{
			Unit = val,
			Deadline = Time.time + 2f,
			Side = e.Side
		});
	}

	private void CountSpawn(Team team)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		if (team == roundAttack)
		{
			unitsSent++;
		}
		else
		{
			defenderUnitsSent++;
		}
	}

	private unsafe void Finish(BaseGameMode mode, Team winner)
	{
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		status = ((object)(*(Team*)(&winner))/*cast due to .constrained prefix*/).ToString() + " wins Siege! Waves deployed: " + wavesSent + "/" + roundCount;
		((BaseUnityPlugin)this).Logger.LogInfo((object)("[Siege] " + status));
		nativeFinish = true;
		armed = (running = false);
		finished = true;
		try
		{
			decide.Invoke(mode, new object[2] { winner, "Siege" });
		}
		finally
		{
			nativeFinish = false;
		}
	}

	private void Tick(BaseGameMode mode)
	{
		//IL_006e: 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_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: 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_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_021d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0222: Unknown result type (might be due to invalid IL or missing references)
		Conceal();
		int num = 0;
		int num2 = 0;
		Unit[] array = Object.FindObjectsOfType<Unit>();
		foreach (Unit val in array)
		{
			if (Alive(val) && !hiddenDeploymentTemplates.Contains(val))
			{
				if (val.Team == roundAttack)
				{
					num++;
				}
				else if (val.Team == Other(roundAttack))
				{
					num2++;
				}
			}
		}
		if (num2 == 0)
		{
			Finish(mode, roundAttack);
			return;
		}
		for (int num3 = activating.Count - 1; num3 >= 0; num3--)
		{
			Activation activation = activating[num3];
			if (Alive(activation.Unit))
			{
				CountSpawn(activation.Side);
				activating.RemoveAt(num3);
			}
			else if (Time.time >= activation.Deadline)
			{
				throw new InvalidOperationException("Wave unit did not activate.");
			}
		}
		if (dispatching)
		{
			int num4 = Mathf.Clamp(spawnBudget.Value, 1, 16);
			while (pending.Count > 0 && num4-- > 0)
			{
				SpawnOne(pending.Dequeue());
			}
			if (pending.Count <= 0 && activating.Count <= 0)
			{
				dispatching = false;
				wavesSent++;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("[Siege] Wave " + wavesSent + "/" + roundCount + " deployed, group size=" + waveMembers + " attackers deployed total=" + unitsSent + " defenders deployed total=" + defenderUnitsSent));
				clearing = roundWait;
				nextWave = Time.time + roundInterval;
			}
			return;
		}
		if (wavesSent >= roundCount)
		{
			if (num == 0)
			{
				Finish(mode, Other(roundAttack));
			}
			return;
		}
		if (clearing)
		{
			if (num > 0)
			{
				return;
			}
			clearing = false;
			nextWave = Time.time + roundInterval;
		}
		if (Time.time < nextWave)
		{
			return;
		}
		foreach (Entry item in roundDefenderGroups[wavesSent])
		{
			pending.Enqueue(item);
		}
		foreach (Entry item2 in roundGroups[wavesSent])
		{
			pending.Enqueue(item2);
		}
		waveMembers = pending.Count;
		dispatching = true;
		((BaseUnityPlugin)this).Logger.LogInfo((object)("[Siege] Dispatching wave " + (wavesSent + 1) + " with " + roundGroups[wavesSent].Count + " attackers and " + roundDefenderGroups[wavesSent].Count + " defenders."));
	}

	private void Update()
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		if (!ready)
		{
			return;
		}
		try
		{
			Scene activeScene = SceneManager.GetActiveScene();
			int handle = ((Scene)(ref activeScene)).handle;
			if (handle != sceneHandle)
			{
				EndSelectionDrag();
				if (sceneHandle != -1)
				{
					ResetRound();
					UnbindPicksForSceneReload();
				}
				sceneHandle = handle;
				nextValidation = 0f;
			}
			BaseGameMode val = Mode();
			int num = Phase();
			if (!(val is SandboxGameMode))
			{
				EndSelectionDrag();
				if (armed || finished)
				{
					ResetRound();
				}
				UnbindPicksForSceneReload();
				previousPhase = num;
				return;
			}
			bool flag = AltHeld();
			BlockNativePlacement();
			if (flag && Input.GetKeyDown((KeyCode)115))
			{
				panel = !panel;
				EndSelectionDrag();
			}
			if (num == PlacementPhase)
			{
				if (previousPhase != PlacementPhase)
				{
					EndSelectionDrag();
					ResetRound();
					nextValidation = 0f;
				}
				previousPhase = num;
				if (!enabledMode.Value)
				{
					EndSelectionDrag();
					ClearGlows();
					return;
				}
				if (Time.unscaledTime >= nextValidation)
				{
					nextValidation = Time.unscaledTime + 0.5f;
					Reconcile();
				}
				UpdateSelectionDrag(flag);
				RefreshGlows();
				return;
			}
			EndSelectionDrag();
			previousPhase = num;
			ClearGlows();
			if (num == BattlePhase && armed && !finished)
			{
				if (!running)
				{
					StartRound();
				}
				Conceal();
				if (Time.timeScale > 0f && Time.time >= nextTick)
				{
					nextTick = Time.time + 0.2f;
					Tick(val);
				}
			}
		}
		catch (Exception e)
		{
			Fail(e);
		}
	}

	private void LateUpdate()
	{
		if (!ready || !armed || !running || finished || Phase() != BattlePhase)
		{
			return;
		}
		try
		{
			Conceal();
		}
		catch (Exception e)
		{
			Fail(e);
		}
	}

	private void Seconds(string name, ConfigEntry<float> value, float min, float max)
	{
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		GUILayout.Label(name + ": " + value.Value.ToString("F0") + "s", Array.Empty<GUILayoutOption>());
		if (GUILayout.Button("-5", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(45f) }))
		{
			value.Value = Mathf.Clamp(value.Value - 5f, min, max);
		}
		if (GUILayout.Button("+5", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(45f) }))
		{
			value.Value = Mathf.Clamp(value.Value + 5f, min, max);
		}
		GUILayout.EndHorizontal();
	}

	private void OnGUI()
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0860: Unknown result type (might be due to invalid IL or missing references)
		//IL_0865: Unknown result type (might be due to invalid IL or missing references)
		//IL_086a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0338: Unknown result type (might be due to invalid IL or missing references)
		//IL_033d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0342: Unknown result type (might be due to invalid IL or missing references)
		if (!ready || !panel || !(Mode() is SandboxGameMode))
		{
			return;
		}
		int num = Phase();
		if (num != PlacementPhase && !armed && !finished)
		{
			return;
		}
		GUILayout.BeginArea(PanelRect(), GUI.skin.box);
		try
		{
			GUILayout.Label("SIEGE MOD 0.1.6 | Alt+S", Array.Empty<GUILayoutOption>());
			if (num == PlacementPhase)
			{
				enabledMode.Value = GUILayout.Toggle(enabledMode.Value, "Enable Siege", Array.Empty<GUILayoutOption>());
				if (!enabledMode.Value)
				{
					return;
				}
				scroll = GUILayout.BeginScrollView(scroll, Array.Empty<GUILayoutOption>());
				try
				{
					string text = Conflict();
					if (text != null)
					{
						GUILayout.Label("Disable " + text + " first.", Array.Empty<GUILayoutOption>());
					}
					GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
					GUILayout.Label("Attackers: " + ((object)Attack/*cast due to .constrained prefix*/).ToString(), Array.Empty<GUILayoutOption>());
					if (GUILayout.Button("Switch sides", Array.Empty<GUILayoutOption>()))
					{
						redAttacks.Value = !redAttacks.Value;
						ClearGroups();
						selectionMessage = "Attacker changed; groups cleared.";
					}
					GUILayout.EndHorizontal();
					GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
					GUILayout.Label("Waves: " + WaveCount, Array.Empty<GUILayoutOption>());
					if (GUILayout.Button("-", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) }))
					{
						waveCount.Value = Mathf.Max(1, WaveCount - 1);
						editWave = Mathf.Min(editWave, WaveCount - 1);
					}
					if (GUILayout.Button("+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) }))
					{
						waveCount.Value = Mathf.Min(20, WaveCount + 1);
					}
					GUILayout.EndHorizontal();
					Seconds("First delay", firstDelay, 0f, 180f);
					Seconds("Wave delay", waveInterval, 1f, 300f);
					waitUntilClear.Value = GUILayout.Toggle(waitUntilClear.Value, "Wait for attackers to be eliminated", Array.Empty<GUILayoutOption>());
					editWave = Mathf.Clamp(editWave, 0, WaveCount - 1);
					defenderReinforcements.Value = GUILayout.Toggle(defenderReinforcements.Value, "Enable defender reinforcements", Array.Empty<GUILayoutOption>());
					if (!defenderReinforcements.Value)
					{
						editDefenders = false;
					}
					if (defenderReinforcements.Value)
					{
						GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
						if (GUILayout.Button(((!editDefenders) ? "> " : "") + "Attackers (" + ((object)Attack/*cast due to .constrained prefix*/).ToString() + ")", Array.Empty<GUILayoutOption>()))
						{
							editDefenders = false;
						}
						if (GUILayout.Button((editDefenders ? "> " : "") + "Defenders (" + ((object)Other(Attack)/*cast due to .constrained prefix*/).ToString() + ")", Array.Empty<GUILayoutOption>()))
						{
							editDefenders = true;
						}
						GUILayout.EndHorizontal();
					}
					string text2 = MissingWaveSummary(savedAttackers, defenders: false);
					string text3 = MissingWaveSummary(savedDefenders, defenders: true);
					bool flag = text2.Length > 0 || text3.Length > 0;
					if (flag)
					{
						GUILayout.Label("WARNING: Missing wave units", Array.Empty<GUILayoutOption>());
						if (text2.Length > 0)
						{
							GUILayout.Label("Attacker waves: " + text2, Array.Empty<GUILayoutOption>());
						}
						if (text3.Length > 0)
						{
							GUILayout.Label("Defender waves: " + text3, Array.Empty<GUILayoutOption>());
						}
						GUILayout.Label("Re-place missing units or clear/reselect the listed waves.", Array.Empty<GUILayoutOption>());
					}
					List<WavePick>[] editPicks = EditPicks;
					GUILayout.Label("Select " + (EditingDefenders ? "defender" : "attacker") + " wave (number: saved unit count)", Array.Empty<GUILayoutOption>());
					for (int i = 0; i < WaveCount; i += 4)
					{
						GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
						for (int j = i; j < Mathf.Min(i + 4, WaveCount); j++)
						{
							if (GUILayout.Button(((j == editWave) ? ">" : "") + (j + 1) + ": " + editPicks[j].Count, Array.Empty<GUILayoutOption>()))
							{
								editWave = j;
							}
						}
						GUILayout.EndHorizontal();
					}
					GUILayout.Label("Editing " + (EditingDefenders ? "defender" : "attacker") + " wave " + (editWave + 1), Array.Empty<GUILayoutOption>());
					GUILayout.Label("Alt+left-click or hold and drag across units.", Array.Empty<GUILayoutOption>());
					GUILayout.Label("Start on a selected unit to remove units instead.", Array.Empty<GUILayoutOption>());
					GUILayout.Label("Holding Alt prevents normal unit placement.", Array.Empty<GUILayoutOption>());
					GUILayout.Label(selectionMessage, Array.Empty<GUILayoutOption>());
					foreach (IGrouping<string, WavePick> item in from p in editPicks[editWave]
						group p by p.BlueprintName)
					{
						GUILayout.Label(item.Count() + " x " + item.Key, Array.Empty<GUILayoutOption>());
					}
					GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
					if (GUILayout.Button("Clear wave", Array.Empty<GUILayoutOption>()))
					{
						EndSelectionDrag();
						editPicks[editWave].Clear();
						Reconcile();
					}
					if (editWave > 0 && GUILayout.Button("Copy previous", Array.Empty<GUILayoutOption>()))
					{
						EndSelectionDrag();
						CopyWave(editPicks[editWave - 1], editPicks[editWave]);
						Reconcile();
					}
					GUILayout.EndHorizontal();
					if (GUILayout.Button("Copy this group to all waves", Array.Empty<GUILayoutOption>()))
					{
						EndSelectionDrag();
						for (int num2 = 0; num2 < WaveCount; num2++)
						{
							if (num2 != editWave)
							{
								CopyWave(editPicks[editWave], editPicks[num2]);
							}
						}
						Reconcile();
					}
					bool flag2 = Time.unscaledTime < confirmClearUntil;
					if (GUILayout.Button(flag2 ? "CONFIRM CLEAR ALL WAVES" : "Clear all wave selections...", Array.Empty<GUILayoutOption>()))
					{
						if (flag2)
						{
							ClearGroups();
							selectionMessage = "All attacker and defender selections cleared.";
							confirmClearUntil = 0f;
						}
						else
						{
							confirmClearUntil = Time.unscaledTime + 5f;
							selectionMessage = "Click CONFIRM CLEAR ALL WAVES within 5 seconds to erase both teams' saved selections.";
						}
					}
					GUILayout.Label("Empty attacker waves: " + savedAttackers.Take(WaveCount).Count((List<WavePick> g) => g.Count == 0), Array.Empty<GUILayoutOption>());
					if (defenderReinforcements.Value)
					{
						GUILayout.Label("Defender waves with units: " + savedDefenders.Take(WaveCount).Count((List<WavePick> g) => g.Count > 0), Array.Empty<GUILayoutOption>());
					}
					if (!flag && (savedAttackers.Any((List<WavePick> g) => g.Count > 0) || savedDefenders.Any((List<WavePick> g) => g.Count > 0)))
					{
						GUILayout.Label("Wave selections retained when returning to placement or reloading this layout.", Array.Empty<GUILayoutOption>());
					}
					GUILayout.Label("Both sides deploy on the same wave countdown. Empty defender waves are allowed. Marked units are hidden until their wave. Leave at least one defender unmarked. No casualty respawns.", Array.Empty<GUILayoutOption>());
					return;
				}
				finally
				{
					GUILayout.EndScrollView();
				}
			}
			GUILayout.Label(status, Array.Empty<GUILayoutOption>());
			GUILayout.Label(((object)Unsafe.As<Team, Team>(ref roundAttack)/*cast due to .constrained prefix*/).ToString() + " attacks | " + ((object)Other(roundAttack)/*cast due to .constrained prefix*/).ToString() + " defends", Array.Empty<GUILayoutOption>());
			GUILayout.Label("Waves deployed: " + wavesSent + " / " + roundCount + " | A: " + unitsSent + " D: " + defenderUnitsSent, Array.Empty<GUILayoutOption>());
			if (armed)
			{
				GUILayout.Label(dispatching ? ("Deploying wave " + (wavesSent + 1) + " (" + (pending.Count + activating.Count) + " pending)") : ((wavesSent >= roundCount) ? "Final wave: defeat remaining attackers" : (clearing ? "Waiting for attacking units to be eliminated" : ("Next wave: " + Mathf.Max(0f, nextWave - Time.time).ToString("F0") + "s"))), Array.Empty<GUILayoutOption>());
			}
		}
		finally
		{
			GUILayout.EndArea();
		}
	}

	private void OnDestroy()
	{
		ready = false;
		Restore();
		ClearGroups();
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		if ((Object)(object)instance == (Object)(object)this)
		{
			instance = null;
		}
	}

	private static bool IsHQ(Unit unit)
	{
		if ((Object)(object)unit == (Object)null || (Object)(object)unit.unitBlueprint == (Object)null || unit.unitBlueprint.Entity == null)
		{
			return false;
		}
		string a = (unit.unitBlueprint.Entity.Name ?? "").Trim();
		if (!string.Equals(a, "Headquarters", StringComparison.OrdinalIgnoreCase))
		{
			return string.Equals(a, "Skyfall Headquarters", StringComparison.OrdinalIgnoreCase);
		}
		return true;
	}

	private static string BlueprintName(UnitBlueprint bp)
	{
		if (!((Object)(object)bp == (Object)null) && bp.Entity != null)
		{
			return (bp.Entity.Name ?? "?").Trim();
		}
		return "?";
	}

	private static bool ValidWaveBlueprint(UnitBlueprint bp)
	{
		if ((Object)(object)bp != (Object)null && (Object)(object)bp.UnitBase != (Object)null && bp.Entity != null && !string.IsNullOrEmpty(bp.Entity.Name) && !string.Equals(bp.Entity.Name.Trim(), "Headquarters", StringComparison.OrdinalIgnoreCase) && !string.Equals(bp.Entity.Name.Trim(), "Skyfall Headquarters", StringComparison.OrdinalIgnoreCase))
		{
			return !bp.Entity.Name.StartsWith("Tank Spawner - ", StringComparison.OrdinalIgnoreCase);
		}
		return false;
	}

	private static Camera PlacementCamera()
	{
		Camera val = Camera.main;
		if ((Object)(object)val == (Object)null)
		{
			val = ((IEnumerable<Camera>)Camera.allCameras).FirstOrDefault((Func<Camera, bool>)((Camera x) => (Object)(object)x != (Object)null && ((Behaviour)x).enabled));
		}
		return val;
	}

	private HashSet<Unit> PlacedUnits()
	{
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: 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)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		HashSet<Unit> hashSet = new HashSet<Unit>();
		BaseGameMode val = Mode();
		RuntimeReferenceService service = ServiceLocator.GetService<RuntimeReferenceService>();
		if (val == null || val.TeamLayouts == null || (Object)(object)service == (Object)null)
		{
			return hashSet;
		}
		Team[] array = (Team[])(object)new Team[2]
		{
			default(Team),
			(Team)1
		};
		foreach (Team val2 in array)
		{
			List<TABSLayoutUnit> teamLayout = val.TeamLayouts.GetTeamLayout(val2);
			if (teamLayout == null)
			{
				continue;
			}
			foreach (TABSLayoutUnit item in teamLayout)
			{
				if (item != null && item.RuntimeReference != null)
				{
					Unit referenceTarget = service.GetReferenceTarget<Unit>((RuntimeReference)(object)item.RuntimeReference);
					if ((Object)(object)referenceTarget != (Object)null && referenceTarget.Team == val2 && !IsHQ(referenceTarget) && ValidWaveBlueprint(referenceTarget.unitBlueprint))
					{
						hashSet.Add(referenceTarget);
					}
				}
			}
		}
		return hashSet;
	}

	private static void MakeGlow(Unit unit, GameObject marker)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: 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_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_0135: 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_014d: 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_016e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ea: Expected O, but got Unknown
		//IL_00ec: 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: Unknown result type (might be due to invalid IL or missing references)
		Color val = (((int)unit.Team == 0) ? new Color(1f, 0.69f, 0.16f) : new Color(0.23f, 0.74f, 1f));
		GameObject obj = GameObject.CreatePrimitive((PrimitiveType)2);
		((Object)obj).name = "Reinforcement selection ring";
		obj.transform.SetParent(marker.transform, false);
		obj.transform.localPosition = new Vector3(0f, 0.12f, 0f);
		obj.transform.localScale = new Vector3(1.65f, 0.025f, 1.65f);
		Collider component = obj.GetComponent<Collider>();
		if ((Object)(object)component != (Object)null)
		{
			component.enabled = false;
		}
		Renderer component2 = obj.GetComponent<Renderer>();
		if ((Object)(object)component2 != (Object)null)
		{
			Shader val2 = Shader.Find("Standard");
			if ((Object)(object)val2 == (Object)null)
			{
				val2 = Shader.Find("Unlit/Color");
			}
			if ((Object)(object)val2 != (Object)null)
			{
				Material val3 = new Material(val2);
				val3.color = val;
				if (val3.HasProperty("_EmissionColor"))
				{
					val3.EnableKeyword("_EMISSION");
					val3.SetColor("_EmissionColor", val * 2f);
				}
				component2.material = val3;
			}
		}
		GameObject val4 = new GameObject("Reinforcement glow light");
		val4.transform.SetParent(marker.transform, false);
		val4.transform.localPosition = Vector3.up * 1.2f;
		Light obj2 = val4.AddComponent<Light>();
		obj2.type = (LightType)2;
		obj2.color = val;
		obj2.intensity = 1.4f;
		obj2.range = 3f;
		obj2.shadows = (LightShadows)0;
	}

	private void TryInstallTankVisualObserver()
	{
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Expected O, but got Unknown
		if (tankVisualStartPatched || harmony == null)
		{
			return;
		}
		try
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				Type type = assemblies[i].GetType("ModdingForDummies.WW2TankVisual", throwOnError: false);
				if (!(type == null))
				{
					MethodInfo methodInfo = AccessTools.Method(type, "Start", Type.EmptyTypes, (Type[])null);
					if (!(methodInfo == null) && !(methodInfo.ReturnType != typeof(void)))
					{
						harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "AfterTankVisualStart", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						tankVisualStartPatched = true;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"[Siege] Optional tank visual creation observer installed.");
						break;
					}
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("[Siege] Tank visual observer unavailable; frame checks remain active: " + ex.Message));
		}
	}

	private static void AfterTankVisualStart(MonoBehaviour __instance)
	{
		Plugin plugin = instance;
		if ((Object)(object)plugin == (Object)null || !plugin.ready || !plugin.armed || plugin.finished || (Object)(object)__instance == (Object)null || Phase() != BattlePhase)
		{
			return;
		}
		Unit component = ((Component)__instance).GetComponent<Unit>();
		if ((Object)(object)component == (Object)null || !plugin.hiddenDeploymentTemplates.Contains(component) || plugin.spawned.Contains(component))
		{
			return;
		}
		try
		{
			plugin.HideTankVisualRoot(component, ReadTankVisualRoot(__instance));
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)plugin).Logger.LogWarning((object)("[Siege] Deferred tank model concealment: " + ex.Message));
		}
	}

	private static GameObject ReadTankVisualRoot(MonoBehaviour component)
	{
		if ((Object)(object)component == (Object)null || ((object)component).GetType().Name != "WW2TankVisual")
		{
			return null;
		}
		try
		{
			Type type = ((object)component).GetType();
			BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
			PropertyInfo property = type.GetProperty("ColliderDebugVisualRoot069", bindingAttr);
			Transform val = (Transform)((property != null) ? /*isinst with value type is only supported in some contexts*/: null);
			if ((Object)(object)val != (Object)null)
			{
				return ((Component)val).gameObject;
			}
			FieldInfo field = type.GetField("model", bindingAttr);
			return (GameObject)((field != null) ? /*isinst with value type is only supported in some contexts*/: null);
		}
		catch (Exception)
		{
			return null;
		}
	}

	private static GameObject TankCosmeticRoot(Unit unit)
	{
		if ((Object)(object)unit == (Object)null)
		{
			return null;
		}
		MonoBehaviour[] components = ((Component)unit).GetComponents<MonoBehaviour>();
		for (int i = 0; i < components.Length; i++)
		{
			GameObject val = ReadTankVisualRoot(components[i]);
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
		}
		return null;
	}

	private void HideTankVisualRoot(Unit unit, GameObject root)
	{
		if ((Object)(object)unit == (Object)null || (Object)(object)root == (Object)null || (Object)(object)root == (Object)(object)((Component)unit).gameObject)
		{
			return;
		}
		if (!concealedTankVisuals.TryGetValue(unit, out var value))
		{
			value = new HashSet<GameObject>();
			concealedTankVisuals.Add(unit, value);
		}
		if (root.activeSelf)
		{
			if (value.Add(root))
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("[Siege] Held tank visual: " + ((Object)root).name + " owner=" + ((Object)unit).GetInstanceID()));
			}
			root.SetActive(false);
		}
	}

	private void ConcealTankCosmetic(Unit unit)
	{
		if ((Object)(object)unit == (Object)null)
		{
			return;
		}
		HideTankVisualRoot(unit, TankCosmeticRoot(unit));
		if (!concealedTankVisuals.TryGetValue(unit, out var value))
		{
			return;
		}
		value.RemoveWhere((GameObject root) => (Object)(object)root == (Object)null);
		foreach (GameObject item in value)
		{
			if ((Object)(object)item != (Object)null && item.activeSelf)
			{
				item.SetActive(false);
			}
		}
	}

	private void RestoreTankCosmetic(Unit unit)
	{
		if (!((Object)(object)unit == (Object)null) && concealedTankVisuals.TryGetValue(unit, out var value))
		{
			concealedTankVisuals.Remove(unit);
			GameObject val = TankCosmeticRoot(unit);
			if ((Object)(object)val != (Object)null && value.Contains(val) && !val.activeSelf)
			{
				val.SetActive(true);
			}
		}
	}

	private static bool TryStableFloor(Vector3 at, float originalHeight, out float height)
	{
		//IL_0003: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: 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)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: 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_00e6: Unknown result type (might be due to invalid IL or missing references)
		height = originalHeight;
		RaycastHit[] array = Physics.RaycastAll(new Vector3(at.x, originalHeight + 4.5f, at.z), Vector3.down, 8.5f, -5, (QueryTriggerInteraction)1);
		float num = float.PositiveInfinity;
		bool result = false;
		RaycastHit[] array2 = array;
		for (int i = 0; i < array2.Length; i++)
		{
			RaycastHit val = array2[i];
			Collider collider = ((RaycastHit)(ref val)).collider;
			if ((Object)(object)collider == (Object)null || ((Object)collider).name == "CursorCollisionCheck" || (Object)(object)((Component)collider).GetComponentInParent<Unit>() != (Object)null || ((RaycastHit)(ref val)).normal.y < 0.78f)
			{
				continue;
			}
			Rigidbody attachedRigidbody = collider.attachedRigidbody;
			if ((Object)(object)attachedRigidbody != (Object)null && !attachedRigidbody.isKinematic)
			{
				continue;
			}
			float num2 = ((RaycastHit)(ref val)).point.y - originalHeight;
			if (!(num2 > 1f) && !(num2 < -2f))
			{
				float num3 = Mathf.Abs(num2);
				if (!(num3 >= num))
				{
					num = num3;
					height = ((RaycastHit)(ref val)).point.y;
					result = true;
				}
			}
		}
		return result;
	}

	private static bool TrySupportedInfantryPoint(Vector3 candidate, float referenceHeight, out Vector3 safe)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: 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_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: 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_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: 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_008a: 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_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: 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_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		safe = candidate;
		if (!TryStableFloor(candidate, referenceHeight, out var height))
		{
			return false;
		}
		float num = 0.55f;
		Vector3[] array = (Vector3[])(object)new Vector3[4]
		{
			new Vector3(num, 0f, 0f),
			new Vector3(0f - num, 0f, 0f),
			new Vector3(0f, 0f, num),
			new Vector3(0f, 0f, 0f - num)
		};
		foreach (Vector3 val in array)
		{
			if (!TryStableFloor(candidate + val, referenceHeight, out var height2) || Mathf.Abs(height2 - height) > 0.6f)
			{
				return false;
			}
		}
		safe = new Vector3(candidate.x, height + 0.18f, candidate.z);
		return true;
	}

	private static void StabilizeNewInfantry(Unit unit)
	{
		//IL_002c: 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)
		if ((Object)(object)unit == (Object)null)
		{
			return;
		}
		Rigidbody[] componentsInChildren = ((Component)unit).GetComponentsInChildren<Rigidbody>(true);
		foreach (Rigidbody val in componentsInChildren)
		{
			if (!((Object)(object)val == (Object)null) && !val.isKinematic)
			{
				val.velocity = Vector3.zero;
				val.angularVelocity = Vector3.zero;
			}
		}
	}

	private void TagTank(Entry s, Unit spawned)
	{
		if (!s.IsSkyfallTank || (Object)(object)spawned == (Object)null)
		{
			return;
		}
		try
		{
			if (!tankMarkerResolved)
			{
				tankMarkerResolved = true;
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				for (int i = 0; i < assemblies.Length; i++)
				{
					Type type = assemblies[i].GetType("ModdingForDummies.SkyfallSpawnerCreatedTank174", throwOnError: false);
					if (type != null && typeof(MonoBehaviour).IsAssignableFrom(type))
					{
						tankMarker = type;
						break;
					}
				}
				if (tankMarker == null)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"[Siege] Optional tank visual alignment marker unavailable.");
				}
			}
			if (tankMarker != null && (Object)(object)((Component)spawned).gameObject.GetComponent(tankMarker) == (Object)null)
			{
				((Component)spawned).gameObject.AddComponent(tankMarker);
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("[Siege] Optional tank visual alignment failed: " + ex.Message));
		}
	}
}