Decompiled source of TABSAutoChessMode v0.0.6

TABSAutoChessMode.dll

Decompiled 15 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Logging;
using DM;
using GamepadUI.StateManager.Core;
using HarmonyLib;
using Landfall.TABC;
using Landfall.TABS;
using Landfall.TABS.Budget;
using Landfall.TABS.GameMode;
using Landfall.TABS.GameState;
using Landfall.TABS.UnitEditor;
using Landfall.TABS.UnitPlacement;
using Landfall.TABS.WinConditions;
using Landfall.TABS.Workshop;
using Newtonsoft.Json;
using TFBGames;
using TMPro;
using UIStateManager;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("TABS自走棋模式")]
[assembly: AssemblyProduct("Tabs Teamfight Tactics")]
[assembly: AssemblyCompany("AbyssalEye")]
[assembly: AssemblyDescription("Native UI playable preview for Totally Accurate Battle Simulator")]
[assembly: AssemblyFileVersion("0.1.55.0")]
[assembly: ComVisible(false)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.55.0")]
[module: UnverifiableCode]
namespace TabsTeamfightTactics.Next;

public class AugmentDef
{
	public string Id;

	public string Name;

	public string Description;

	public string Tier;

	public string Faction;

	public string EmblemTrait;

	public int EmblemCount;
}
public static class AugmentCatalog
{
	public static readonly string[] HeartFactions = new string[14]
	{
		"tribal", "farmer", "medieval", "ancient", "viking", "dynasty", "renaissance", "pirate", "spooky", "wildwest",
		"secret", "good", "evil", "monarch"
	};

	public static readonly List<AugmentDef> All = Build();

	private static List<AugmentDef> Build()
	{
		List<AugmentDef> list = new List<AugmentDef>();
		string[] heartFactions = HeartFactions;
		string[] array = new string[14]
		{
			"部落", "农夫", "中世纪", "古代", "维京", "王朝", "文艺复兴", "海盗", "亡灵", "西部",
			"神秘", "善", "恶", "君主"
		};
		for (int i = 0; i < heartFactions.Length; i++)
		{
			list.Add(new AugmentDef
			{
				Id = "heart_" + heartFactions[i],
				Name = array[i] + "之心",
				Description = array[i] + "阵营计数 +1",
				Tier = "silver",
				Faction = heartFactions[i]
			});
		}
		Add(list, "hearts_gold", "阵营之心 II", "随机获得两个不同阵营之心。", "gold");
		Add(list, "hearts_prismatic", "阵营之心 III", "随机获得五个阵营或职业之心;可重复。", "prismatic");
		string[] keys = ClassRules.Keys;
		foreach (string text in keys)
		{
			list.Add(new AugmentDef
			{
				Id = "heart_" + text,
				Name = ClassCatalog.Name(text) + "之心",
				Description = ClassCatalog.Name(text) + "羁绊 +1",
				Tier = "gold",
				Faction = text
			});
		}
		Add(list, "tiny_titans", "小小巨人", "最大生命与当前生命 +20。", "silver");
		Add(list, "spoon", "银汤匙", "立即获得 10 经验。", "silver");
		Add(list, "wise_spending", "明智消费", "每次主动刷新普通商店获得 2 经验,免费刷新也生效。", "prismatic");
		Add(list, "level_up", "升级咯", "每次购买经验额外获得 3 经验。", "prismatic");
		Add(list, "cursed_crown", "诅咒冠冕", "部署上限 +4;失败伤害翻倍。", "prismatic");
		Add(list, "trade_sector", "贸易区", "每个新回合获得一次免费刷新。", "gold");
		Add(list, "rich_get_richer", "利滚利", "立即获得 10 金币;利息上限提高至 7。", "gold");
		Add(list, "windfall_silver", "意外之财 I", "立即获得 20 金币。", "silver");
		Add(list, "windfall_gold", "意外之财 II", "立即获得 30 金币。", "gold");
		Add(list, "windfall_prismatic", "意外之财 III", "立即获得 40 金币。", "prismatic");
		Add(list, "threes_company", "三三三", "随机获得三张 2 星 3 费单位卡。", "gold");
		Add(list, "five_cost_two_star", "2星五费", "随机获得一张 2 星 5 费单位卡。", "prismatic");
		Add(list, "gold_twenty_one", "获得21金币", "立即获得 21 金币。", "gold");
		Add(list, "dont_miss", "别再错过", "每种 1 费兵种各获得一张 1 星单位卡。", "prismatic");
		Add(list, "second_wind", "复苏之风", "战斗开始 10 秒后,回复已损失生命的 50%。", "gold");
		Add(list, "cybernetic", "源计划植入", "携带装备的单位生命 +300,伤害 +20%。", "gold");
		Add(list, "grab_bag", "百宝袋", "立即获得两个随机基础装备。", "silver");
		Add(list, "salvage_bin", "打捞桶", "战斗结束后将普通成装拆回原来的两个组件;光明装备保留。", "gold");
		Add(list, "prismatic_ticket", "棱彩门票", "每次刷新普通商店有 50% 概率获得一次免费刷新。", "prismatic");
		Add(list, "sword_overflow", "大剑溢流", "立即获得 4 把暴风大剑。", "prismatic");
		Add(list, "belt_overflow", "腰带溢流", "立即获得 4 条巨人腰带。", "prismatic");
		Add(list, "glove_overflow", "拳套溢流", "立即获得 4 个拳套。", "prismatic");
		Add(list, "bow_overflow", "弓溢流", "立即获得 4 件弓散件。", "prismatic");
		Add(list, "scythe_overflow", "镰刀溢流", "立即获得 4 件镰刀散件。", "prismatic");
		Add(list, "staff_overflow", "木棍溢流", "立即获得 4 件木棍散件。", "prismatic");
		Add(list, "pistol_overflow", "手枪溢流", "立即获得 4 件手枪散件。", "prismatic");
		Add(list, "high_end_shopping", "高端购物", "商店按照比当前等级高 1 级的概率刷新,最高按 40 级计算。", "prismatic");
		Add(list, "cruel_pact", "恶魔契约", "每次购买经验花费 6 点生命获得 6 经验;生命不高于 6 时无法购买。每次战斗结算存活后回复 2 点生命。", "prismatic");
		Add(list, "quality_over_quantity", "重质不重量", "立即将当前所有普通合成装备升级为对应光明装备,包括已穿戴装备;没有可升级的装备时,随机获得一件光明装备。", "prismatic");
		Add(list, "at_what_cost", "不计代价", "等级至少提升到 6 级,并获得 4 经验。之后的海克斯强化将随机自动选择。", "prismatic");
		Add(list, "radiant_relics", "光明圣物", "立即免费获得两件随机光明装备。", "prismatic");
		Add(list, "explosive_growth", "爆炸性增长", "接下来 6 个新关卡开始时各获得 10 经验,总计 60 经验;失败重试不重复发放。", "gold");
		Add(list, "four_cost_reinforcements", "4费增援", "随机获得一张 2 星 4 费单位卡。", "prismatic");
		Add(list, "intentional_loss", "存心失利", "每次战败并存活后获得 5 金币和一次免费刷新。", "gold");
		Add(list, "vampiric_habits", "吸血习性", "登场单位获得 20% 吸血。", "gold");
		Add(list, "dd_block", "DD街区", "立即获得 4 金币;每个新回合获得一次免费刷新。", "gold");
		Add(list, "one_two_two_three", "1223", "分别获得一张随机 1、2、2、3 费的 1 星单位卡。", "silver");
		Add(list, "star_up_luck", "升星之运", "每次卡牌实际合星升级获得一次免费刷新;连续合星分别计数。", "silver");
		Add(list, "roll_for_days", "D个痛快", "立即获得 15 次免费刷新。", "silver");
		Add(list, "recombobulator", "变形重组器", "将当前所有单位卡随机变为高 1 费的兵种,保留星级;没有对应费用时保留原卡。已部署单位收回,装备保留在库存。", "silver");
		Add(list, "double_trouble_silver", "好事成双 I", "恰好登场两名相同兵种时,这两名单位获得 10% 生命和伤害。", "silver");
		Add(list, "double_trouble_gold", "好事成双 II", "恰好登场两名相同兵种时,这两名单位获得 20% 生命和伤害。", "gold");
		Add(list, "double_trouble_prismatic", "好事成双 III", "恰好登场两名相同兵种时,这两名单位获得 30% 生命和伤害。", "prismatic");
		keys = EmblemRules.Keys;
		foreach (string text2 in keys)
		{
			string text3 = EmblemRules.Name(text2) + "转职";
			list.Add(new AugmentDef
			{
				Id = "emblem_single_" + text2,
				Name = text3,
				Tier = ((text2 == "legacy") ? "prismatic" : (ClassRules.IsClass(text2) ? "gold" : "silver")),
				EmblemTrait = text2,
				EmblemCount = 1,
				Description = "获得 1 个" + text3 + "装备。"
			});
			if (text2 != "legacy")
			{
				list.Add(new AugmentDef
				{
					Id = "emblem_pair_" + text2,
					Name = text3 + " II",
					Tier = "prismatic",
					EmblemTrait = text2,
					EmblemCount = 2,
					Description = "获得 2 个" + text3 + "装备。"
				});
			}
		}
		list.Add(new AugmentDef
		{
			Id = "emblems_random_5",
			Name = "随机转职 V",
			Tier = "prismatic",
			EmblemCount = 5,
			Description = "获得 5 个不同的随机羁绊转职装备。"
		});
		return list;
	}

	private static void Add(List<AugmentDef> list, string id, string name, string description, string tier)
	{
		list.Add(new AugmentDef
		{
			Id = id,
			Name = name,
			Description = description,
			Tier = tier
		});
	}

	public static string CanonicalId(string id)
	{
		if (!(id == "emblem_pair_legacy"))
		{
			return id;
		}
		return "emblem_single_legacy";
	}

	public static AugmentDef Find(string id)
	{
		string key = CanonicalId(id);
		return All.Find((AugmentDef x) => x.Id == key);
	}

	public static string[] RollHearts(Random random, bool prismatic, IEnumerable<string> availableFactions)
	{
		if (prismatic)
		{
			string[] pool = HeartFactions.Concat(ClassRules.Keys).ToArray();
			return (from _ in Enumerable.Range(0, 5)
				select pool[random.Next(pool.Length)]).ToArray();
		}
		return (from _ in (availableFactions ?? HeartFactions).Where(((IEnumerable<string>)HeartFactions).Contains<string>).Distinct()
			orderby random.Next()
			select _).Take(2).ToArray();
	}

	public static List<AugmentDef> Eligible(IEnumerable<string> acquired, ICollection<string> factions, string tier = null, ICollection<string> excluded = null)
	{
		HashSet<string> held = new HashSet<string>((acquired ?? Enumerable.Empty<string>()).Select(CanonicalId));
		HashSet<string> hidden = new HashSet<string>((excluded ?? Array.Empty<string>()).Select(CanonicalId));
		return All.Where((AugmentDef a) => !held.Contains(a.Id) && (a.Faction == null || ClassRules.IsClass(a.Faction) || factions == null || factions.Contains(a.Faction)) && (tier == null || a.Tier == tier) && !hidden.Contains(a.Id)).ToList();
	}

	public static List<string> RollSameTier(Random random, IEnumerable<string> acquired, ICollection<string> factions, ICollection<string> excluded = null)
	{
		List<List<AugmentDef>> list = (from a in Eligible(acquired, factions, null, excluded)
			group a by a.Tier into g
			select g.ToList()).ToList();
		if (list.Count == 0)
		{
			return new List<string>();
		}
		List<List<AugmentDef>> list2 = list.Where((List<AugmentDef> g) => g.Count >= 4).ToList();
		if (list2.Count == 0)
		{
			list2 = list.Where((List<AugmentDef> g) => g.Count >= 3).ToList();
		}
		if (list2.Count == 0)
		{
			list2 = list;
		}
		List<AugmentDef> list3 = list2[random.Next(list2.Count)].ToList();
		for (int num = list3.Count - 1; num > 0; num--)
		{
			int index = random.Next(num + 1);
			AugmentDef value = list3[num];
			list3[num] = list3[index];
			list3[index] = value;
		}
		return (from a in list3.Take(3)
			select a.Id).ToList();
	}
}
public static class AugmentCombatRules
{
	public static float DoubleTrouble(ICollection<string> augments, int copies)
	{
		if (augments == null || copies != 2)
		{
			return 0f;
		}
		if (!augments.Contains("double_trouble_prismatic"))
		{
			if (!augments.Contains("double_trouble_gold"))
			{
				if (!augments.Contains("double_trouble_silver"))
				{
					return 0f;
				}
				return 0.1f;
			}
			return 0.2f;
		}
		return 0.3f;
	}
}
public static class AugmentRerollRules
{
	public static int Remaining(int used)
	{
		return 2 - Math.Max(0, Math.Min(2, used));
	}

	public static List<int> Restore(IList<int> counts, IList<bool> legacy, int slots)
	{
		List<int> list = new List<int>();
		for (int i = 0; i < slots; i++)
		{
			list.Add((counts != null && i < counts.Count) ? Math.Max(0, Math.Min(2, counts[i])) : ((legacy != null && i < legacy.Count && legacy[i]) ? 1 : 0));
		}
		return list;
	}
}
public static class AugmentRules
{
	public const double TicketProbability = 0.5;

	public static int ShopLevel(int level, bool highEnd)
	{
		return Math.Min(40, level + (highEnd ? 1 : 0));
	}

	public static bool CanBuyExperience(int gold, int health, bool pact)
	{
		if (!pact)
		{
			return gold >= 4;
		}
		return health > 6;
	}

	public static int PurchasedExperience(bool pact, bool levelUp)
	{
		return (pact ? 6 : 4) + (levelUp ? 3 : 0);
	}

	public static int HealAfterSettlement(int health, int maxHealth, bool pact)
	{
		if (!(health > 0 && pact))
		{
			return health;
		}
		return Math.Min(maxHealth, health + 2);
	}

	public static bool TicketAward(double roll)
	{
		return roll < 0.5;
	}

	public static bool IsNewRound(int serial, int lastSerial)
	{
		return serial > lastSerial;
	}

	public static int RoundFreeRoll(int serial, ref int lastPaidSerial)
	{
		if (!IsNewRound(serial, lastPaidSerial))
		{
			return 0;
		}
		lastPaidSerial = serial;
		return 1;
	}

	public static int GrowthExperience(int serial, ref int remaining, ref int lastPaidSerial)
	{
		if (remaining <= 0 || !IsNewRound(serial, lastPaidSerial))
		{
			return 0;
		}
		lastPaidSerial = serial;
		remaining--;
		return 10;
	}
}
internal sealed class AuthoredSpot
{
	internal readonly double X;

	internal readonly double Y;

	internal readonly double Z;

	internal AuthoredSpot(double x, double y, double z)
	{
		X = x;
		Y = y;
		Z = z;
	}
}
internal static class AuthoredPlacementRules
{
	private static long Cell(int x, int z)
	{
		return ((long)x << 32) ^ (uint)z;
	}

	internal static int[] Assign(double[] radii, AuthoredSpot[] spots, int[] roles = null)
	{
		if (radii.Length == 0)
		{
			return Array.Empty<int>();
		}
		if (spots.Length < radii.Length)
		{
			return null;
		}
		if (radii.Any((double r) => double.IsNaN(r) || double.IsInfinity(r) || r <= 0.0))
		{
			return null;
		}
		roles = roles ?? new int[radii.Length];
		if (roles.Length != radii.Length || roles.Any((int r) => r < 0 || r > 2))
		{
			throw new ArgumentException("Invalid combat roles.");
		}
		int[] array = (from i in Enumerable.Range(0, radii.Length)
			orderby (roles[i] != 2) ? roles[i] : (-1), radii[i] descending, i
			select i).ToArray();
		int[] array2 = (from i in Enumerable.Range(0, spots.Length)
			orderby spots[i].X, spots[i].Z
			select i).ToArray();
		int[] array3 = (from i in Enumerable.Range(0, spots.Length)
			orderby spots[i].X descending, spots[i].Z
			select i).ToArray();
		double num = radii.Max() * 2.0 + 2.0;
		for (int num2 = 0; num2 < 4; num2++)
		{
			int[] array4 = Enumerable.Repeat(-1, radii.Length).ToArray();
			bool[] array5 = new bool[spots.Length];
			Dictionary<long, List<int>> dictionary = new Dictionary<long, List<int>>();
			bool flag = true;
			double[] array6 = new double[3]
			{
				double.PositiveInfinity,
				double.PositiveInfinity,
				double.PositiveInfinity
			};
			double[] array7 = new double[3]
			{
				double.NegativeInfinity,
				double.NegativeInfinity,
				double.NegativeInfinity
			};
			int[] array8 = array;
			foreach (int num4 in array8)
			{
				bool flag2 = false;
				for (int num5 = 0; num5 < spots.Length; num5++)
				{
					int num6 = (num5 + num2 * spots.Length / 4) % spots.Length;
					int num7 = ((roles[num4] == 0) ? array2 : array3)[num6];
					if (array5[num7] || spots[num7].X < radii[num4])
					{
						continue;
					}
					AuthoredSpot authoredSpot = spots[num7];
					bool flag3 = false;
					for (int num8 = 0; num8 < 3; num8++)
					{
						if (num8 < roles[num4] && authoredSpot.X - radii[num4] < array7[num8] + 2.0)
						{
							flag3 = true;
						}
						if (num8 > roles[num4] && authoredSpot.X + radii[num4] > array6[num8] - 2.0)
						{
							flag3 = true;
						}
					}
					if (flag3)
					{
						continue;
					}
					int num9 = (int)Math.Floor(authoredSpot.X / num);
					int num10 = (int)Math.Floor(authoredSpot.Z / num);
					bool flag4 = false;
					for (int num11 = num9 - 1; num11 <= num9 + 1; num11++)
					{
						if (flag4)
						{
							break;
						}
						for (int num12 = num10 - 1; num12 <= num10 + 1; num12++)
						{
							if (flag4)
							{
								break;
							}
							if (!dictionary.TryGetValue(Cell(num11, num12), out var value))
							{
								continue;
							}
							foreach (int item in value)
							{
								AuthoredSpot authoredSpot2 = spots[array4[item]];
								double num13 = radii[num4] + radii[item] + 2.0;
								if (Math.Abs(authoredSpot.X - authoredSpot2.X) < num13 && Math.Abs(authoredSpot.Z - authoredSpot2.Z) < num13)
								{
									flag4 = true;
									break;
								}
							}
						}
					}
					if (!flag4)
					{
						array4[num4] = num7;
						array5[num7] = true;
						array6[roles[num4]] = Math.Min(array6[roles[num4]], authoredSpot.X - radii[num4]);
						array7[roles[num4]] = Math.Max(array7[roles[num4]], authoredSpot.X + radii[num4]);
						long key = Cell(num9, num10);
						if (!dictionary.TryGetValue(key, out var value2))
						{
							value2 = new List<int>();
							dictionary.Add(key, value2);
						}
						value2.Add(num4);
						flag2 = true;
						break;
					}
				}
				if (!flag2)
				{
					flag = false;
					break;
				}
			}
			if (flag)
			{
				return array4;
			}
		}
		return null;
	}

	internal static string[] MapOrder(string[] maps, IEnumerable<string> recent, int seed, string persisted)
	{
		if (maps.Length == 0)
		{
			return maps;
		}
		string[] history = (recent ?? Enumerable.Empty<string>()).ToArray();
		int start = (int)((uint)seed % (uint)maps.Length);
		return (from i in Enumerable.Range(0, maps.Length)
			select maps[(start + i) % maps.Length] into id
			orderby (!(id == persisted)) ? ((Array.IndexOf(history, id) >= 0) ? 1 : 0) : (-1)
			select id).ToArray();
	}
}
public class UnitState : MonoBehaviour
{
	public Unit Unit;

	public NativeUnit Definition;

	public int Stars = 1;

	public bool Player;

	public string InstanceKey;

	public readonly List<GearInstance> Equipped = new List<GearInstance>();

	public float BaseHealth;

	internal bool CrownScaled;

	public float BaseDamage = 1f;

	public float BaseHaste = 1f;

	public float BaseSpeed = 1f;

	public bool Captured;

	public bool Summoned;

	internal bool ReinforcementsCalled;

	internal bool DeathTriggered;

	internal readonly List<BattleEffects.NativeStat> NativeStats = new List<BattleEffects.NativeStat>();

	internal Dictionary<string, int> Traits = new Dictionary<string, int>();

	internal float Lifesteal;

	internal float Regeneration;

	internal readonly Dictionary<string, GameObject> GearAbilities = new Dictionary<string, GameObject>();

	internal GameObject EquipmentLabels;

	internal GameObject CrownLabels;

	internal Image CrownImage;

	internal TABCUnitUI NativeHealthBar;

	internal float NextCrownProbe;

	internal readonly Vector3[] CrownCorners = (Vector3[])(object)new Vector3[4];

	public string[] EffectiveTraits => EmblemRules.EffectiveTraits(Definition?.TraitKeys, Equipped.ConvertAll((GearInstance g) => g?.DefId));

	public bool HasTrait(string key)
	{
		if (string.IsNullOrEmpty(key))
		{
			return false;
		}
		if (Definition != null && Definition.HasFaction(key))
		{
			return true;
		}
		foreach (GearInstance item in Equipped)
		{
			if (GearCatalog.Find(item?.DefId)?.EmblemTrait == key)
			{
				return true;
			}
		}
		return false;
	}

	private void LateUpdate()
	{
		BattleEffects.UpdateCrown(this);
		BattleEffects.UpdateEquipment(this);
	}

	private void OnDisable()
	{
		NativeClassAbilities.ClearGear(this);
		BattleEffects.ClearCrown(this);
		if ((Object)(object)EquipmentLabels != (Object)null)
		{
			EquipmentLabels.SetActive(false);
		}
	}

	private void OnDestroy()
	{
		BattleEffects.ClearIcons(this);
	}
}
public static class BattleEffects
{
	internal sealed class NativeStat
	{
		public Component Target;

		public FieldInfo Field;

		public float Initial;

		public bool Movement;

		public bool Ranged;

		public bool Melee;

		public bool Range;
	}

	private sealed class CrownBonus
	{
		public float Health;

		public float HealthPercent;

		public float Damage;

		public int Tier;
	}

	private static readonly Dictionary<Unit, UnitState> Tracked = new Dictionary<Unit, UnitState>();

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

	private static readonly HashSet<Unit> SecondWind = new HashSet<Unit>();

	private static readonly HashSet<Unit> PirateKills = new HashSet<Unit>();

	private static readonly List<UnitState> Deployed = new List<UnitState>();

	private static readonly HashSet<Unit> DeployedUnits = new HashSet<Unit>();

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

	private static readonly Dictionary<Unit, CrownBonus> Crowns = new Dictionary<Unit, CrownBonus>();

	private static readonly Dictionary<bool, bool> MonarchTeams = new Dictionary<bool, bool>();

	private static readonly Dictionary<bool, int> Arts = new Dictionary<bool, int>();

	private static readonly Random LootRandom = new Random();

	private static float FarmerClock;

	private static bool Prepared;

	private static NativeUnit CrownKing;

	private static readonly FieldInfo NativeHealthBarField = typeof(Unit).GetField("m_unitUI", BindingFlags.Instance | BindingFlags.NonPublic);

	private static int Count(Dictionary<string, int> traits, string key)
	{
		if (traits == null || !traits.TryGetValue(key, out var value))
		{
			return 0;
		}
		return value;
	}

	private static bool Has(RunData run, string id)
	{
		if (run != null && run.Augments != null)
		{
			return run.Augments.Contains(id);
		}
		return false;
	}

	private static bool Alive(UnitState state)
	{
		if ((Object)(object)state != (Object)null && (Object)(object)state.Unit != (Object)null && (Object)(object)state.Unit.data != (Object)null && !state.Unit.data.Dead)
		{
			return state.Unit.data.health > 0f;
		}
		return false;
	}

	private static bool HasFaction(UnitState state, string faction)
	{
		if ((Object)(object)state != (Object)null)
		{
			return state.HasTrait(faction);
		}
		return false;
	}

	internal static int BattleTraitCount(UnitState state, string faction)
	{
		Dictionary<string, int> value;
		return Count(TeamTraits.TryGetValue(state.Player, out value) ? value : state.Traits, faction);
	}

	private static bool MonarchTeamEnabled(bool player)
	{
		if (MonarchTeams.TryGetValue(player, out var value))
		{
			return value;
		}
		GameController current = GameController.Current;
		if (current != null && current.Bridge != null)
		{
			return current.Bridge.MonarchEnabled(player);
		}
		return false;
	}

	public static void Apply(UnitState state, RunData run, Dictionary<string, int> traits, bool startingBattle = false)
	{
		if (!((Object)(object)state == (Object)null) && !((Object)(object)state.Unit == (Object)null) && !((Object)(object)state.Unit.data == (Object)null))
		{
			if (!state.Captured)
			{
				Capture(state);
			}
			bool flag = Prepared && DeployedUnits.Contains(state.Unit) && !state.Summoned;
			state.Traits = ((flag && TeamTraits.TryGetValue(state.Player, out var value)) ? new Dictionary<string, int>(value) : ((traits == null) ? new Dictionary<string, int>() : new Dictionary<string, int>(traits)));
			Tracked[state.Unit] = state;
			if (startingBattle && !state.Summoned && !Prepared)
			{
				TeamTraits[state.Player] = new Dictionary<string, int>(state.Traits);
			}
			ApplyStats(state, run, startingBattle || flag);
			StarOutline.Apply(state.Unit, state.Stars);
			AddIcons(state);
		}
	}

	private static void Capture(UnitState state)
	{
		Unit unit = state.Unit;
		state.BaseHealth = Mathf.Max(1f, (unit.data.maxHealth > 0f) ? unit.data.maxHealth : unit.data.health);
		state.BaseHaste = unit.attackSpeedMultiplier;
		Component[] componentsInChildren = ((Component)unit).GetComponentsInChildren<Component>(true);
		foreach (Component val in componentsInChildren)
		{
			if ((Object)(object)val == (Object)null || (Object)(object)val.GetComponentInParent<Unit>() != (Object)(object)unit)
			{
				continue;
			}
			Type type = ((object)val).GetType();
			bool flag = type.Name == "MovementHandler" || type.Name == "WheelMovementHandler";
			bool flag2 = val is Weapon || type.Name == "Level";
			if (!flag && !flag2)
			{
				continue;
			}
			FieldInfo field = type.GetField(flag ? "multiplier" : "levelMultiplier", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field == null || field.FieldType != typeof(float))
			{
				continue;
			}
			Weapon component = val.GetComponent<Weapon>();
			state.NativeStats.Add(new NativeStat
			{
				Target = val,
				Field = field,
				Initial = (float)field.GetValue(val),
				Movement = flag,
				Ranged = (component is RangeWeapon),
				Melee = (component is MeleeWeapon)
			});
			if (val is RangeWeapon)
			{
				FieldInfo field2 = type.GetField("maxRange", BindingFlags.Instance | BindingFlags.Public);
				if (field2 != null && field2.FieldType == typeof(float))
				{
					state.NativeStats.Add(new NativeStat
					{
						Target = val,
						Field = field2,
						Initial = (float)field2.GetValue(val),
						Range = true,
						Ranged = true
					});
				}
			}
		}
		state.Captured = true;
	}

	private static void ApplyStats(UnitState state, RunData run, bool combat)
	{
		//IL_086a: Unknown result type (might be due to invalid IL or missing references)
		//IL_087f: Unknown result type (might be due to invalid IL or missing references)
		Unit unit = state.Unit;
		DataHandler data = unit.data;
		Dictionary<string, int> traits = state.Traits;
		if (!TeamTraits.TryGetValue(!state.Player, out var value))
		{
			value = null;
		}
		float hp = StarRules.Health(state.BaseHealth, state.Stars, (state.Definition == null) ? 1 : state.Definition.Cost);
		float num = StarRules.DamageMultiplier(state.Stars);
		float num2 = StarRules.AttackSpeedMultiplier(state.Stars);
		float speed = StarRules.MovementMultiplier(state.Stars);
		float damage = 0f;
		float haste = 0f;
		float flatHp = 0f;
		float num3 = 0f;
		float num4 = 0f;
		float num5 = 0f;
		float num6 = 0f;
		float num7 = 0f;
		float num8 = 0f;
		float num9 = 0f;
		state.Lifesteal = 0f;
		state.Regeneration = 0f;
		if (state.Player && run != null && run.Bonuses != null && state.Definition != null)
		{
			foreach (string item in new HashSet<string>(state.EffectiveTraits))
			{
				hp *= 1f + 0.2f * (float)Count(run.Bonuses, item + ":health");
				damage += 0.1f * (float)Count(run.Bonuses, item + ":damage");
				haste += 0.2f * (float)Count(run.Bonuses, item + ":haste");
			}
		}
		foreach (GearInstance item2 in state.Equipped)
		{
			GearDef gearDef = ((item2 == null) ? null : GearCatalog.Find(item2.DefId));
			if (gearDef != null)
			{
				flatHp += gearDef.HealthFlat;
				damage += gearDef.DamagePercent;
				haste += gearDef.HastePercent;
				speed *= 1f + gearDef.MovePercent;
				num4 += gearDef.RangePercent;
				num5 += gearDef.RangeFlat;
				num6 += gearDef.HealthPercent;
				state.Lifesteal += gearDef.Lifesteal;
			}
		}
		NativeClassAbilities.SyncGear(state);
		if (state.Player && state.Equipped.Count > 0 && Has(run, "cybernetic"))
		{
			flatHp += 300f;
			damage += 0.2f;
		}
		if (combat)
		{
			if (state.Player && !state.Summoned && DeployedUnits.Contains(unit))
			{
				if (Has(run, "vampiric_habits"))
				{
					state.Lifesteal += 0.2f;
				}
				if (state.Definition != null && DeployedCopies.TryGetValue(state.Player, out var value2) && value2.TryGetValue(state.Definition.Id, out var value3))
				{
					num8 = AugmentCombatRules.DoubleTrouble(run?.Augments, value3);
				}
				damage += num8;
			}
			if (HasFaction(state, "tribal"))
			{
				int count = Count(traits, "tribal");
				hp *= 1f + TraitRules.TribalHealth(count);
				speed *= 1f + TraitRules.TribalSpeed(count);
				num *= 1f + TraitRules.TribalDamage(count);
			}
			if (HasFaction(state, "ancient"))
			{
				int count2 = Count(traits, "ancient");
				damage += TraitRules.AncientDamage(count2);
				haste += TraitRules.AncientHaste(count2);
				hp *= 1f + TraitRules.AncientHealth(count2);
			}
			if (HasFaction(state, "dynasty"))
			{
				state.Lifesteal += TraitRules.DynastyLifesteal(Count(traits, "dynasty"));
			}
			haste += TraitRules.FarmerHaste(Count(traits, "farmer"));
			haste += TraitRules.EvilHaste(Count(traits, "evil")) * (float)((!HasFaction(state, "evil")) ? 1 : 2);
			if (HasFaction(state, "good"))
			{
				float num10 = 1f + TraitRules.GoodBonus(Count(traits, "good"));
				hp *= num10;
				num *= num10;
				num2 *= num10;
				speed *= num10;
			}
			if (HasFaction(state, "legacy"))
			{
				int num11 = Count(traits, "legacy");
				flatHp += TraitRules.LegacyFlatHealth(num11);
				float num12 = ((state.Definition == null || state.Definition.Cost > 2) ? 1 : 2);
				if (num11 == 1)
				{
					hp *= 1f + 2f * num12;
					num *= 1f + 0.5f * num12;
					num2 *= 1f + num12;
					speed *= 1f + 0.5f * num12;
				}
				if (num11 == TraitRules.Maximum("legacy"))
				{
					float num13 = 1f + 16f * num12;
					hp *= num13;
					num *= num13;
					num2 *= num13;
					speed *= num13;
				}
			}
			Arts.TryGetValue(state.Player, out var value4);
			float num14 = ((!HasFaction(state, "renaissance")) ? 1 : 2);
			if ((value4 & 1) != 0)
			{
				damage += 0.05f * num14;
			}
			if ((value4 & 2) != 0)
			{
				num3 += 0.07f * num14;
			}
			if ((value4 & 4) != 0)
			{
				haste += 0.3f * num14;
			}
			if ((value4 & 8) != 0)
			{
				num4 += 0.1f * num14;
			}
			if ((value4 & 0x10) != 0)
			{
				damage += 0.06f * num14;
			}
			if ((value4 & 0x20) != 0)
			{
				speed *= 1f + 0.3f * num14;
			}
			if ((value4 & 0x40) != 0)
			{
				hp *= 1f + 0.08f * num14;
			}
			if ((value4 & 0x80) != 0)
			{
				flatHp += 50f * num14;
			}
			if ((value4 & 0x100) != 0)
			{
				num7 += 0.05f * num14;
			}
			if ((value4 & 0x200) != 0)
			{
				state.Lifesteal += 0.02f * num14;
			}
			if ((value4 & 0x400) != 0)
			{
				damage += 0.15f * num14;
			}
			int num15 = Count(traits, "secret");
			if (num15 >= 7 && state.Definition != null && state.Definition.Cost <= 3)
			{
				hp *= 1.08f;
				num *= 1.08f;
				num2 *= 1.08f;
				speed *= 1.08f;
			}
			if (HasFaction(state, "secret"))
			{
				if (num15 >= 3)
				{
					speed *= 1.2f;
				}
				if (num15 >= 15)
				{
					num3 += 0.25f;
				}
				if (num15 >= 18)
				{
					flatHp += 100f;
					haste += 0.2f;
				}
				if (num15 >= 27)
				{
					damage += 0.25f;
				}
				if (num15 >= 36)
				{
					haste += 2f;
					speed += 1f;
				}
				if (TraitRules.Maxed("secret", num15))
				{
					hp *= 41f;
					num *= 41f;
					num2 *= 41f;
					speed *= 41f;
				}
			}
			if (Count(value, "secret") >= 3)
			{
				speed *= 0.8f;
			}
			if (Count(value, "secret") >= 12)
			{
				num *= 0.8f;
			}
			if (!state.Summoned && DeployedUnits.Contains(unit) && Crowns.TryGetValue(unit, out var value5))
			{
				flatHp += value5.Health;
				damage += value5.Damage;
				num9 = value5.HealthPercent;
			}
			if (HasFaction(state, "monarch") && MonarchTeamEnabled(state.Player))
			{
				int count3 = Count(traits, "monarch");
				hp = (hp + flatHp + MonarchRules.FlatHealth(count3)) * (1f + MonarchRules.Health(count3));
				flatHp = 0f;
				haste += MonarchRules.Haste(count3);
				speed *= 1f + MonarchRules.Speed(count3);
			}
			ClassEffects.ApplyStats(state, traits, ref hp, ref flatHp, ref damage, ref haste, ref speed);
		}
		bool flag = combat && Crowns.ContainsKey(unit);
		if (flag != state.CrownScaled)
		{
			Transform transform = ((Component)unit).transform;
			transform.localScale *= (flag ? 1.1f : 0.9090909f);
			state.CrownScaled = flag;
		}
		hp = Mathf.Max(1f, (hp + flatHp) * (1f + num8) * (1f + num6) * (1f + num9));
		float num16 = ((data.maxHealth > 0f) ? Mathf.Clamp01(data.health / data.maxHealth) : 1f);
		bool flag2 = data.Dead || data.health <= 0f;
		data.maxHealth = hp;
		data.health = (flag2 ? 0f : (hp * num16));
		if (combat)
		{
			haste = ClassEffects.CaptureHaste(state, state.BaseHaste * num2, haste);
		}
		num *= 1f + damage;
		num2 *= 1f + haste;
		foreach (NativeStat nativeStat in state.NativeStats)
		{
			if ((Object)(object)nativeStat.Target != (Object)null)
			{
				nativeStat.Field.SetValue(nativeStat.Target, nativeStat.Range ? Mathf.Max(0f, (nativeStat.Initial + num5) * (1f + num4)) : (nativeStat.Initial * (nativeStat.Movement ? (speed * state.BaseSpeed) : (num * state.BaseDamage * (nativeStat.Melee ? (1f + num3) : (nativeStat.Ranged ? (1f + num7) : 1f))))));
			}
		}
		float num17 = Mathf.Max(0.01f, state.BaseHaste * num2);
		unit.AddAttackSpeed(num17 - unit.attackSpeedMultiplier);
	}

	public static UnitState RegisterTransformation(UnitState original, Unit replacement)
	{
		if ((Object)(object)original == (Object)null || (Object)(object)original.Unit == (Object)null || (Object)(object)replacement == (Object)null || (Object)(object)replacement.data == (Object)null || !Prepared || !DeployedUnits.Contains(original.Unit))
		{
			return null;
		}
		if ((Object)(object)replacement == (Object)(object)original.Unit)
		{
			return original;
		}
		UnitState unitState = ((Component)replacement).GetComponent<UnitState>() ?? ((Component)replacement).gameObject.AddComponent<UnitState>();
		unitState.Unit = replacement;
		unitState.Definition = original.Definition;
		unitState.Stars = original.Stars;
		unitState.Player = original.Player;
		unitState.InstanceKey = original.InstanceKey;
		unitState.Summoned = false;
		unitState.DeathTriggered = original.DeathTriggered;
		unitState.Equipped.Clear();
		unitState.Equipped.AddRange(original.Equipped);
		unitState.Traits = new Dictionary<string, int>(original.Traits);
		replacement.data.maxHealth = replacement.data.health;
		unitState.BaseHealth = Mathf.Max(1f, replacement.data.health);
		if (!unitState.Captured)
		{
			Capture(unitState);
		}
		Tracked.Remove(original.Unit);
		Tracked[replacement] = unitState;
		DeployedUnits.Remove(original.Unit);
		DeployedUnits.Add(replacement);
		int num = Deployed.IndexOf(original);
		if (num >= 0)
		{
			Deployed[num] = unitState;
		}
		if (Crowns.TryGetValue(original.Unit, out var value))
		{
			Crowns.Remove(original.Unit);
			Crowns[replacement] = value;
		}
		ClearIcons(original);
		StarOutline.Clear(original.Unit);
		ClassEffects.Transform(original, unitState);
		GearEffects.Transform(original, unitState);
		ApplyStats(unitState, (GameController.Current == null) ? null : GameController.Current.Run, combat: true);
		StarOutline.Apply(replacement, unitState.Stars);
		AddIcons(unitState);
		return unitState;
	}

	public static void PrepareBattle(IList<UnitState> units, RunData run)
	{
		if (Prepared || units == null)
		{
			return;
		}
		Prepared = true;
		Arts.Clear();
		Deployed.Clear();
		DeployedUnits.Clear();
		Crowns.Clear();
		DeployedCopies.Clear();
		for (int i = 0; i < units.Count; i++)
		{
			UnitState unitState = units[i];
			if (!((Object)(object)unitState == (Object)null) && !unitState.Summoned && unitState.Definition != null && !((Object)(object)unitState.Unit == (Object)null) && DeployedUnits.Add(unitState.Unit))
			{
				Deployed.Add(unitState);
				unitState.DeathTriggered = false;
				if (!DeployedCopies.TryGetValue(unitState.Player, out var value))
				{
					value = new Dictionary<string, int>();
					DeployedCopies[unitState.Player] = value;
				}
				value.TryGetValue(unitState.Definition.Id, out var value2);
				value[unitState.Definition.Id] = value2 + 1;
				if (HasFaction(unitState, "renaissance"))
				{
					Arts.TryGetValue(unitState.Player, out var value3);
					Arts[unitState.Player] = value3 | ArtBit(unitState.Definition);
				}
			}
		}
		bool[] array = new bool[2] { false, true };
		foreach (bool flag in array)
		{
			int num = 0;
			int num2 = 0;
			foreach (UnitState item in Deployed)
			{
				if (item.Player == flag)
				{
					num++;
					if (item.HasTrait("monarch"))
					{
						num2++;
					}
				}
			}
			MonarchTeams[flag] = MonarchRules.Enabled(num, num2);
		}
		ClassEffects.Prepare(Deployed);
		for (int k = 0; k < units.Count; k++)
		{
			if (Alive(units[k]) && units[k].Captured)
			{
				ApplyStats(units[k], run, combat: true);
			}
		}
		for (int l = 0; l < 2; l++)
		{
			bool flag2 = l == 1;
			if (!TeamTraits.TryGetValue(flag2, out var value4))
			{
				continue;
			}
			int count = Count(value4, "medieval");
			if (TraitRules.MedievalTier(count) == 0)
			{
				continue;
			}
			UnitState unitState2 = null;
			float num3 = float.NegativeInfinity;
			List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>();
			foreach (UnitState item2 in Deployed)
			{
				if (item2.Player == flag2 && HasFaction(item2, "medieval"))
				{
					list.Add(new KeyValuePair<string, int>(item2.Definition.Id, item2.Stars));
					if (Alive(item2) && item2.Captured && item2.Unit.data.maxHealth > num3)
					{
						unitState2 = item2;
						num3 = item2.Unit.data.maxHealth;
					}
				}
			}
			if (!((Object)(object)unitState2 == (Object)null))
			{
				int extraStars = TraitRules.HighestExtraStars(list);
				Crowns[unitState2.Unit] = new CrownBonus
				{
					Health = TraitRules.CrownHealth(count, extraStars),
					HealthPercent = TraitRules.CrownHealthPercent(count),
					Damage = TraitRules.CrownDamage(count, extraStars),
					Tier = TraitRules.MedievalTier(count)
				};
				ApplyStats(unitState2, run, combat: true);
				UpdateCrown(unitState2);
			}
		}
		StartFrost(units);
		ClassEffects.StartAbilities();
	}

	public static void Tick(IList<UnitState> units, RunData run, float elapsed, float delta)
	{
		if (units == null)
		{
			return;
		}
		PrepareBattle(units, run);
		ClassEffects.Tick();
		float num = ((float.IsNaN(delta) || float.IsInfinity(delta)) ? 0f : Mathf.Max(0f, delta));
		FarmerClock += num;
		int num2 = (int)(FarmerClock / 3f);
		if (num2 > 0)
		{
			FarmerClock -= num2 * 3;
		}
		List<UnitState> list = new List<UnitState>(Tracked.Values);
		GearEffects.Tick(list, num);
		WesternEffects.Tick(list, num);
		for (int i = 0; i < list.Count; i++)
		{
			UnitState unitState = list[i];
			if ((Object)(object)unitState == (Object)null || (Object)(object)unitState.Unit == (Object)null || (Object)(object)unitState.Unit.data == (Object)null)
			{
				continue;
			}
			if (!Alive(unitState))
			{
				OnDeath(unitState, elapsed);
				continue;
			}
			DataHandler data = unitState.Unit.data;
			float num3 = data.maxHealth * unitState.Regeneration * num;
			if (TeamTraits.TryGetValue(unitState.Player, out var value))
			{
				num3 += data.maxHealth * TraitRules.FarmerHeal(Count(value, "farmer")) * (float)num2;
			}
			if (unitState.Player && elapsed >= 10f && Has(run, "second_wind") && SecondWind.Add(unitState.Unit))
			{
				num3 += (data.maxHealth - data.health) * 0.5f;
			}
			if (num3 > 0f)
			{
				data.health = Mathf.Min(data.maxHealth, data.health + num3);
			}
		}
	}

	public static void DamageDealt(Unit source, float actualDamage, RunData run)
	{
		if (!((Object)(object)source == (Object)null) && !float.IsNaN(actualDamage) && !float.IsInfinity(actualDamage) && !(actualDamage <= 0f) && Tracked.TryGetValue(source, out var value) && Alive(value) && !(value.Lifesteal <= 0f))
		{
			source.data.health = Mathf.Min(source.data.maxHealth, source.data.health + actualDamage * value.Lifesteal);
		}
	}

	public static void DamageDealt(Unit source, Unit victim, float actualDamage, RunData run)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: 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_0078: Unknown result type (might be due to invalid IL or missing references)
		DamageDealt(source, actualDamage, run);
		if ((Object)(object)source != (Object)null && (Object)(object)victim != (Object)null && source.Team != victim.Team && Tracked.TryGetValue(source, out var value))
		{
			GearEffects.Damage(value, actualDamage, Tracked.Values);
		}
		if (!((Object)(object)source == (Object)null) && !((Object)(object)victim == (Object)null) && !((Object)(object)victim.data == (Object)null) && source.Team != victim.Team && !(actualDamage <= 0f) && !float.IsNaN(actualDamage) && !float.IsInfinity(actualDamage) && (!(victim.data.health > 0f) || victim.data.Dead) && Tracked.TryGetValue(source, out var value2) && !((Object)(object)value2 == (Object)null) && !value2.Summoned && DeployedUnits.Contains(source) && value2.Player && HasFaction(value2, "pirate") && PirateKills.Add(victim))
		{
			PirateReward(value2);
		}
	}

	private static string NameKey(NativeUnit unit)
	{
		return ((((Object)(object)unit.Blueprint != (Object)null && unit.Blueprint.Entity != null) ? unit.Blueprint.Entity.Name : unit.Name) ?? "").Replace("_", "").Replace(" ", "").ToUpperInvariant();
	}

	private static int ArtBit(NativeUnit unit)
	{
		return UnitFactionRules.RenaissanceEffectMask(unit.Faction, NameKey(unit));
	}

	private static void Summon(UnitState source, string kind, int count, int stars)
	{
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: 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_0138: 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_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_015b: Unknown result type (might be due to invalid IL or missing references)
		NativeUnit nativeUnit = null;
		foreach (NativeUnit unit in GameDatabase.Units)
		{
			string text = NameKey(unit);
			if (text.Contains(kind) && (!(kind == "KNIGHT") || unit.HasFaction("medieval")) && (!(kind == "SKELETON") || (!text.Contains("ARCHER") && !text.Contains("GIANT"))) && (nativeUnit == null || unit.NativeCost < nativeUnit.NativeCost))
			{
				nativeUnit = unit;
			}
		}
		if (nativeUnit == null || (Object)(object)nativeUnit.Blueprint == (Object)null)
		{
			MainPlugin.Log.LogWarning((object)("Native summon unavailable: " + kind));
			return;
		}
		Vector3 val = (((Object)(object)source.Unit.data.mainRig != (Object)null) ? source.Unit.data.mainRig.position : ((Component)source.Unit).transform.position);
		for (int i = 0; i < count; i++)
		{
			float num = ((float)i + 0.5f) * (float)Math.PI * 2f / (float)Mathf.Max(1, count);
			Unit val2 = GameBridge.SpawnExtra(nativeUnit.Blueprint, source.Unit.Team, val + new Vector3(Mathf.Cos(num), 0f, Mathf.Sin(num)) * 1.4f, Math.Max(1, Math.Min(5, stars)));
			if (!((Object)(object)val2 == (Object)null))
			{
				UnitState obj = ((Component)val2).GetComponent<UnitState>() ?? ((Component)val2).gameObject.AddComponent<UnitState>();
				obj.Unit = val2;
				obj.Definition = nativeUnit;
				obj.Player = source.Player;
				obj.Stars = Math.Max(1, Math.Min(5, stars));
				obj.Summoned = true;
				Apply(obj, (GameController.Current == null) ? null : GameController.Current.Run, source.Traits);
				ApplyStats(obj, (GameController.Current == null) ? null : GameController.Current.Run, combat: true);
			}
		}
	}

	private static void OnDeath(UnitState state, float elapsed)
	{
		if (state.DeathTriggered || state.Summoned || state.Definition == null || (Object)(object)state.Unit == (Object)null || !DeployedUnits.Contains(state.Unit))
		{
			return;
		}
		ClearCrown(state);
		state.DeathTriggered = true;
		if (HasFaction(state, "pirate"))
		{
			PirateReward(state);
		}
		if (HasFaction(state, "spooky"))
		{
			int count = BattleTraitCount(state, "spooky");
			if (TraitRules.SpookyCount(count) != 0)
			{
				Summon(state, "SKELETON", TraitRules.SpookyCount(count), TraitRules.SpookyStars(count));
			}
		}
	}

	private static void PirateReward(UnitState state)
	{
		if (state.Player && GameController.Current != null)
		{
			int num = TraitRules.PirateGold(BattleTraitCount(state, "pirate"), LootRandom.NextDouble());
			if (num > 0)
			{
				GameController.Current.AddGold(num);
			}
		}
	}

	public static void ObserveDeath(Unit unit)
	{
		if (!((Object)(object)unit == (Object)null) && !((Object)(object)unit.data == (Object)null) && unit.data.Dead && Tracked.TryGetValue(unit, out var value))
		{
			OnDeath(value, (GameController.Current == null) ? 0f : GameController.Current.Bridge.BattleTime);
		}
	}

	private static void StartFrost(IList<UnitState> units)
	{
		for (int i = 0; i < 2; i++)
		{
			if (!TeamTraits.TryGetValue(i == 1, out var value))
			{
				continue;
			}
			int count = Count(value, "viking");
			int num = TraitRules.VikingStacks(count);
			if (num == 0)
			{
				continue;
			}
			UnitState unitState = null;
			foreach (UnitState unit in units)
			{
				if (Alive(unit) && unit.Player == (i == 1))
				{
					unitState = unit;
					break;
				}
			}
			if ((Object)(object)unitState == (Object)null)
			{
				continue;
			}
			string kind = (TraitRules.VikingUsesUllr(count) ? "ullr" : "ice");
			foreach (UnitState unit2 in units)
			{
				if (Alive(unit2) && unit2.Player != (i == 1))
				{
					for (int j = 0; j < num; j++)
					{
						NativeGearResources.ApplyHitEffect(unitState.Unit, unit2.Unit, kind);
					}
				}
			}
		}
	}

	public static void AddIcons(UnitState state)
	{
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Expected O, but got Unknown
		//IL_0080: 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_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Unknown result type (might be due to invalid IL or missing references)
		//IL_0118: Expected O, but got Unknown
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0171: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_0220: Unknown result type (might be due to invalid IL or missing references)
		//IL_0225: Unknown result type (might be due to invalid IL or missing references)
		//IL_0238: Unknown result type (might be due to invalid IL or missing references)
		//IL_0248: Unknown result type (might be due to invalid IL or missing references)
		ClearEquipmentIcons(state);
		UpdateCrown(state);
		if ((Object)(object)state == (Object)null || (Object)(object)state.Unit == (Object)null || state.Equipped.Count == 0)
		{
			return;
		}
		GameObject val = new GameObject("Tactics equipment", new Type[2]
		{
			typeof(RectTransform),
			typeof(Canvas)
		});
		Canvas component = val.GetComponent<Canvas>();
		component.renderMode = (RenderMode)2;
		component.sortingOrder = 20;
		val.GetComponent<RectTransform>().sizeDelta = new Vector2(210f, 110f);
		val.transform.localScale = Vector3.one * 0.007f;
		int num = Math.Min(3, state.Equipped.Count);
		for (int i = 0; i < num; i++)
		{
			GearDef gearDef = ((state.Equipped[i] == null) ? null : GearCatalog.Find(state.Equipped[i].DefId));
			if (gearDef != null)
			{
				GameObject val2 = new GameObject(gearDef.Name, new Type[2]
				{
					typeof(RectTransform),
					typeof(Image)
				});
				val2.transform.SetParent(val.transform, false);
				RectTransform component2 = val2.GetComponent<RectTransform>();
				component2.sizeDelta = new Vector2(54f, 54f);
				component2.anchoredPosition = new Vector2(((float)i - (float)(num - 1) / 2f) * 60f, 0f);
				Image component3 = val2.GetComponent<Image>();
				((Graphic)component3).color = Color.black;
				((Graphic)component3).raycastTarget = false;
				GameObject val3 = new GameObject("Native equipment icon", new Type[2]
				{
					typeof(RectTransform),
					typeof(Image)
				});
				val3.transform.SetParent(val2.transform, false);
				val3.GetComponent<RectTransform>().sizeDelta = new Vector2(48f, 48f);
				Image component4 = val3.GetComponent<Image>();
				component4.sprite = GameDatabase.GearIcon(gearDef.Id);
				component4.preserveAspect = true;
				((Graphic)component4).raycastTarget = false;
				GameObject val4 = new GameObject("Equipment frame", new Type[2]
				{
					typeof(RectTransform),
					typeof(Image)
				});
				val4.transform.SetParent(val2.transform, false);
				val4.GetComponent<RectTransform>().sizeDelta = new Vector2(54f, 54f);
				Image component5 = val4.GetComponent<Image>();
				UiAssets.Background(component5, UiAssets.EquipmentFrame(gearDef.Radiant, gearDef.Component));
				((Graphic)component5).raycastTarget = false;
			}
		}
		state.EquipmentLabels = val;
		UpdateEquipment(state);
	}

	private static Sprite KingIcon()
	{
		if (CrownKing == null)
		{
			foreach (NativeUnit unit in GameDatabase.Units)
			{
				if (unit != null && !(unit.Faction != "medieval") && !((Object)(object)unit.Blueprint == (Object)null) && unit.Blueprint.Entity != null && (unit.Blueprint.Entity.Name ?? "").ToUpperInvariant().Contains("KING") && (CrownKing == null || unit.NativeCost < CrownKing.NativeCost))
				{
					CrownKing = unit;
				}
			}
		}
		if (CrownKing != null)
		{
			return CrownKing.Icon;
		}
		return null;
	}

	internal static void UpdateCrown(UnitState state)
	{
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Expected O, but got Unknown
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: 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_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)
		//IL_0158: Unknown result type (might be due to invalid IL or missing references)
		//IL_0168: Unknown result type (might be due to invalid IL or missing references)
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0254: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0273: Unknown result type (might be due to invalid IL or missing references)
		//IL_0278: Unknown result type (might be due to invalid IL or missing references)
		//IL_027d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0289: 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)
		if ((Object)(object)state == (Object)null)
		{
			return;
		}
		if (!Prepared || !((Behaviour)state).isActiveAndEnabled || state.Summoned || (Object)(object)state.Unit == (Object)null || !((Component)state.Unit).gameObject.activeInHierarchy || !DeployedUnits.Contains(state.Unit) || !Crowns.TryGetValue(state.Unit, out var value) || !Alive(state))
		{
			ClearCrown(state);
			return;
		}
		if (GameBridge.NativeUiHidden)
		{
			if ((Object)(object)state.CrownLabels != (Object)null)
			{
				state.CrownLabels.SetActive(false);
			}
			return;
		}
		if ((Object)(object)state.CrownLabels == (Object)null)
		{
			GameObject val = new GameObject("Tactics medieval crown", new Type[2]
			{
				typeof(RectTransform),
				typeof(Canvas)
			});
			Canvas component = val.GetComponent<Canvas>();
			component.renderMode = (RenderMode)2;
			component.sortingOrder = 21;
			val.GetComponent<RectTransform>().sizeDelta = new Vector2(52f, 44f);
			val.transform.localScale = Vector3.one * 0.007f;
			GameObject val2 = new GameObject("Native King crown", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val2.transform.SetParent(val.transform, false);
			val2.GetComponent<RectTransform>().sizeDelta = new Vector2(52f, 44f);
			Image component2 = val2.GetComponent<Image>();
			component2.preserveAspect = true;
			((Graphic)component2).raycastTarget = false;
			((Behaviour)component2).enabled = false;
			((Graphic)component2).color = (Color)((value.Tier >= 3) ? new Color(1f, 0.79f, 0.12f) : ((value.Tier == 2) ? Color.white : new Color(0.55f, 0.55f, 0.55f)));
			state.CrownLabels = val;
			state.CrownImage = component2;
			state.NextCrownProbe = 0f;
		}
		if ((Object)(object)state.CrownImage != (Object)null && (Object)(object)state.CrownImage.sprite == (Object)null)
		{
			state.CrownImage.sprite = KingIcon();
			((Behaviour)state.CrownImage).enabled = (Object)(object)state.CrownImage.sprite != (Object)null;
		}
		state.CrownLabels.SetActive(true);
		Vector3 position = IconAnchor(state) + Vector3.up * ((state.Equipped.Count > 0) ? 0.55f : 0.12f);
		state.CrownLabels.transform.position = position;
		Camera main = Camera.main;
		if ((Object)(object)main != (Object)null)
		{
			state.CrownLabels.transform.rotation = ((Component)main).transform.rotation;
		}
	}

	private static Vector3 IconAnchor(UnitState state)
	{
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_010c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0141: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Unknown result type (might be due to invalid IL or missing references)
		//IL_018a: Unknown result type (might be due to invalid IL or missing references)
		//IL_018f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0193: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)state.NativeHealthBar == (Object)null && Time.unscaledTime >= state.NextCrownProbe)
		{
			state.NextCrownProbe = Time.unscaledTime + 0.25f;
			if (NativeHealthBarField != null)
			{
				ref TABCUnitUI nativeHealthBar = ref state.NativeHealthBar;
				object? value = NativeHealthBarField.GetValue(state.Unit);
				nativeHealthBar = (TABCUnitUI)((value is TABCUnitUI) ? value : null);
			}
		}
		TABCUnitUI nativeHealthBar2 = state.NativeHealthBar;
		if ((Object)(object)nativeHealthBar2 != (Object)null && ((Component)nativeHealthBar2).gameObject.activeInHierarchy && (Object)(object)nativeHealthBar2.m_HealthBar != (Object)null)
		{
			((Graphic)nativeHealthBar2.m_HealthBar).rectTransform.GetWorldCorners(state.CrownCorners);
			return (state.CrownCorners[1] + state.CrownCorners[2]) * 0.5f + Vector3.up * 0.3f;
		}
		Transform val = (((Object)(object)state.Unit.data == (Object)null) ? null : state.Unit.data.head);
		Vector3 val2 = (((Object)(object)val != (Object)null) ? val.position : (((Component)state.Unit).transform.position + Vector3.up * 2.5f)) + Vector3.up * 1.6f;
		SkinnedMeshRenderer[] componentsInChildren = ((Component)state.Unit).GetComponentsInChildren<SkinnedMeshRenderer>();
		foreach (SkinnedMeshRenderer val3 in componentsInChildren)
		{
			if ((Object)(object)val3 != (Object)null && ((Renderer)val3).enabled && (Object)(object)((Component)val3).GetComponentInParent<Unit>() == (Object)(object)state.Unit)
			{
				float y = val2.y;
				Bounds bounds = ((Renderer)val3).bounds;
				val2.y = Mathf.Max(y, ((Bounds)(ref bounds)).max.y + 0.5f);
			}
		}
		return val2;
	}

	internal static void UpdateEquipment(UnitState state)
	{
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)state == (Object)null || (Object)(object)state.EquipmentLabels == (Object)null || (Object)(object)state.Unit == (Object)null)
		{
			return;
		}
		bool flag = Alive(state) && ((Behaviour)state).isActiveAndEnabled && !GameBridge.NativeUiHidden;
		state.EquipmentLabels.SetActive(flag);
		if (flag)
		{
			state.EquipmentLabels.transform.position = IconAnchor(state);
			Camera main = Camera.main;
			if ((Object)(object)main != (Object)null)
			{
				state.EquipmentLabels.transform.rotation = ((Component)main).transform.rotation;
			}
		}
	}

	internal static void ClearCrown(UnitState state)
	{
		if (!((Object)(object)state == (Object)null))
		{
			if ((Object)(object)state.CrownLabels != (Object)null)
			{
				state.CrownLabels.SetActive(false);
				Object.Destroy((Object)(object)state.CrownLabels);
			}
			state.CrownLabels = null;
			state.CrownImage = null;
		}
	}

	private static void ClearEquipmentIcons(UnitState state)
	{
		if ((Object)(object)state != (Object)null && (Object)(object)state.EquipmentLabels != (Object)null)
		{
			Object.Destroy((Object)(object)state.EquipmentLabels);
			state.EquipmentLabels = null;
		}
	}

	public static void ClearIcons(UnitState state)
	{
		ClearEquipmentIcons(state);
		ClearCrown(state);
	}

	public static void ResetBattle()
	{
		MonarchTeams.Clear();
		ClassEffects.Reset();
		GearEffects.Reset();
		foreach (UnitState value in Tracked.Values)
		{
			NativeClassAbilities.ClearGear(value);
		}
		foreach (UnitState item in Deployed)
		{
			ClearCrown(item);
		}
		Tracked.Clear();
		TeamTraits.Clear();
		Arts.Clear();
		SecondWind.Clear();
		PirateKills.Clear();
		Deployed.Clear();
		DeployedUnits.Clear();
		Crowns.Clear();
		WesternEffects.Reset();
		DeployedCopies.Clear();
		FarmerClock = 0f;
		Prepared = false;
	}
}
public sealed class BossSlot
{
	public int Index;

	public int Stars;

	public decimal Value;
}
public static class BossRules
{
	public const int MaximumUnits = 5;

	public static int Budget(int stage)
	{
		return Rules.CampaignBudgetTarget(stage, 7);
	}

	public static decimal Value(int nativeCost, int stars)
	{
		return CampaignRules.EnemyPrice(nativeCost, stars);
	}

	public static BossSlot[] Plan(int[] costs, int budget)
	{
		return Plan(costs, budget, null);
	}

	public static BossSlot[] Plan(int[] costs, int budget, bool[] preferred)
	{
		if (costs == null || budget <= 0)
		{
			return Array.Empty<BossSlot>();
		}
		List<BossSlot> list = new List<BossSlot>();
		int num = ((budget > 60000) ? 5 : ((budget > 15000) ? 4 : 3));
		for (int i = 0; i < costs.Length; i++)
		{
			if (costs[i] <= 0 || costs[i] >= 999999)
			{
				continue;
			}
			for (int j = 1; j <= num; j++)
			{
				decimal num2 = Value(costs[i], j);
				if (num2 <= (decimal)budget)
				{
					list.Add(new BossSlot
					{
						Index = i,
						Stars = j,
						Value = num2
					});
				}
			}
		}
		if (list.Count == 0)
		{
			int num3 = (from num4 in Enumerable.Range(0, costs.Length)
				where costs[num4] > 0 && costs[num4] < 999999
				orderby costs[num4]
				select num4).DefaultIfEmpty(-1).First();
			if (num3 >= 0)
			{
				return new BossSlot[1]
				{
					new BossSlot
					{
						Index = num3,
						Stars = 1,
						Value = Value(costs[num3], 1)
					}
				};
			}
			return Array.Empty<BossSlot>();
		}
		Func<BossSlot, int> count = (BossSlot c) => (int)Math.Min(5m, (decimal)budget / c.Value);
		List<BossSlot> list2 = list.Where((BossSlot c) => (decimal)count(c) * c.Value * 5m >= (decimal)((long)budget * 4L)).ToList();
		List<BossSlot> list3 = list2.Where((BossSlot c) => preferred == null || (c.Index < preferred.Length && preferred[c.Index])).ToList();
		List<BossSlot> list4 = ((list3.Count > 0) ? list3 : list2);
		BossSlot selected;
		if (list4.Count > 0)
		{
			selected = list4.OrderBy(count).ThenByDescending((BossSlot c) => (decimal)count(c) * c.Value).ThenByDescending((BossSlot c) => costs[c.Index])
				.ThenBy((BossSlot c) => c.Index)
				.First();
		}
		else
		{
			selected = list.OrderByDescending((BossSlot c) => (decimal)count(c) * c.Value).ThenBy(count).ThenByDescending((BossSlot c) => costs[c.Index])
				.ThenBy((BossSlot c) => c.Index)
				.First();
		}
		return (from num4 in Enumerable.Range(0, count(selected))
			select new BossSlot
			{
				Index = selected.Index,
				Stars = selected.Stars,
				Value = selected.Value
			}).ToArray();
	}
}
public static class BudgetProvenanceRules
{
	public static long ShopValue(CardStack card, long price)
	{
		if (card == null || card.Count <= 0 || price <= 0)
		{
			return 0L;
		}
		long num = Inventory.BaseCopies(card.Stars) * card.Count;
		long num2 = Math.Max(0L, Math.Min(num, card.BudgetExemptCopies));
		long num3 = num - num2;
		long num4 = price / Inventory.BaseCopies(card.Stars);
		long num5 = price % Inventory.BaseCopies(card.Stars);
		if (num4 > 0 && num3 > long.MaxValue / num4)
		{
			return long.MaxValue;
		}
		long num6 = num4 * num3;
		long num7 = (num5 * num3 + Inventory.BaseCopies(card.Stars) - 1) / Inventory.BaseCopies(card.Stars);
		if (num6 <= long.MaxValue - num7)
		{
			return num6 + num7;
		}
		return long.MaxValue;
	}
}
internal sealed class EncounterSelection
{
	public int CoreIndex;

	public TABSCampaignLevelAsset Template;

	public NativeUnit[] Units;

	public int[] Stars;

	public string Variant;

	public decimal Value;

	public bool Generated;
}
internal static class CampaignEncounterBuilder
{
	private static int[] AvailableThresholds(RunData run, string key)
	{
		int value = 0;
		run.FactionEncounterTiers?.TryGetValue(key, out value);
		int[] thresholds = TraitRules.Thresholds(key);
		if (run.Stage > 10 && key != "legacy" && key != "monarch")
		{
			value = Math.Max(value, 6);
		}
		int[] array = EncounterProgressionRules.AllowedThresholds(thresholds, value);
		if (run.Stage > 10 && key != "legacy" && key != "monarch")
		{
			array = (from n in array.Concat(new int[1] { 7 }).Distinct()
				orderby n
				select n).ToArray();
		}
		return array;
	}

	internal static bool Allowed(RunData run, NativeUnit[] units, int[] stars)
	{
		if (run == null || units == null || stars == null || units.Length != stars.Length || units.Any((NativeUnit u) => u == null))
		{
			return false;
		}
		foreach (IGrouping<string, string> item in from k in (from u in units
				group u by u.Id into g
				select g.First()).SelectMany((NativeUnit u) => u.FactionKeys)
			where !string.IsNullOrEmpty(k) && !GameDatabase.IsModFaction(k)
			group k by k)
		{
			int[] array = AvailableThresholds(run, item.Key);
			if (array.Length != 0 && item.Count() > array.Last())
			{
				return false;
			}
		}
		return true;
	}

	internal static void RecordWin(RunData run)
	{
		run.FactionEncounterTiers = run.FactionEncounterTiers ?? new Dictionary<string, int>();
		foreach (IGrouping<string, string> item in from k in (from u in (run.EncounterUnitIds ?? new List<string>()).Select(GameDatabase.Find)
				where u != null
				group u by u.Id into g
				select g.First()).SelectMany((NativeUnit u) => u.FactionKeys)
			where !string.IsNullOrEmpty(k) && !GameDatabase.IsModFaction(k)
			group k by k)
		{
			run.FactionEncounterTiers.TryGetValue(item.Key, out var value);
			run.FactionEncounterTiers[item.Key] = Math.Max(value, item.Count());
		}
	}

	internal static bool NormalPopulationAllowed(RunData run, NativeUnit[] units, int[] stars, int coreIndex = -1)
	{
		CorePopulationRange corePopulationRange = CoreCarryRules.PopulationMinMax(run.Stage);
		if (units.Length < corePopulationRange.Min || units.Length > corePopulationRange.Max || (units.Length < 5 && stars.Any((int star) => star >= 3)) || (from u in units
			group u by u.Id).Any((IGrouping<string, NativeUnit> g) => g.Count() > 3))
		{
			return false;
		}
		IEnumerable<IGrouping<string, string>> source = from k in (from u in units
				group u by u.Id into g
				select g.First()).SelectMany((NativeUnit u) => u.ClassKeys)
			group k by k;
		if (run.Stage > 15 && !source.Any((IGrouping<string, string> g) => ClassRules.Thresholds(g.Key).Length != 0 && g.Count() >= ClassRules.Thresholds(g.Key)[0]))
		{
			return false;
		}
		int num = ((coreIndex >= 0 && coreIndex < units.Length) ? coreIndex : (from i in Enumerable.Range(0, units.Length)
			where CoreCarryRules.Recommended(units[i].Blueprint.Entity.Name)
			orderby stars[i] descending, units[i].NativeCost descending
			select i).DefaultIfEmpty(-1).First());
		if (run.Stage > 10 && (num < 0 || !units[num].HasFaction("legacy")))
		{
			string[] primary = ((num < 0) ? Array.Empty<string>() : units[num].FactionKeys.Where((string k) => k != "secret" && k != "monarch").ToArray());
			if (primary.Length == 0 && num >= 0)
			{
				primary = units[num].FactionKeys;
			}
			if (!(from v in units.SelectMany((NativeUnit u, int i) => from k in u.FactionKeys
					where primary.Contains(k)
					select new
					{
						Key = k,
						Id = u.Id,
						Star = stars[i]
					})
				group v by v.Key).Any(g => g.Select(v => v.Id).Distinct().Count() >= 7 && (run.Stage < 30 || (from v in g
				where v.Star == 5
				select v.Id).Distinct().Count() >= 7)))
			{
				return false;
			}
		}
		return true;
	}

	internal static EncounterSelection Select(RunData run, int target)
	{
		//IL_021a: Unknown result type (might be due to invalid IL or missing references)
		Stopwatch stopwatch = Stopwatch.StartNew();
		Dictionary<string, NativeUnit> lookup = GameDatabase.Units.Where((NativeUnit u) => !u.Modded).ToDictionary((NativeUnit u) => u.Id);
		Dictionary<TABSCampaignLevelAsset, NativeUnit[]> definitions = GameDatabase.Levels.ToDictionary((TABSCampaignLevelAsset l) => l, (TABSCampaignLevelAsset l) => (from id in (from slot in l.BlueUnits
				where slot != null && (Object)(object)slot.m_unitBlueprint != (Object)null
				select GameDatabase.Id(slot.m_unitBlueprint.Entity.GUID)).Where(lookup.ContainsKey)
			select lookup[id]).ToArray());
		NativeUnit[] eligible = lookup.Values.Where((NativeUnit u) => u.ShopEligible).ToArray();
		CoreArmyMember[] pool = eligible.Select((NativeUnit u) => new CoreArmyMember
		{
			Id = u.Id,
			Cost = u.Cost,
			Role = NativeCombatRole.Role(u),
			Factions = u.FactionKeys,
			Classes = u.ClassKeys,
			Cheer = (u.Blueprint.Entity.Name == "UNIT_SECRET_CHEERLEADER"),
			StayFlag = (u.Blueprint.Entity.Name == "UNIT_LEGACY_LEG_BANNER_BEARER_STAY"),
			Stationary = CoreCarryRules.UsesStationarySupport(u.Blueprint.Entity.Name)
		}).ToArray();
		Dictionary<string, int[]> classThresholds = ClassRules.Keys.ToDictionary((string k) => k, (string k) => ClassRules.Thresholds(k));
		decimal globalThree = CampaignRules.MaximumThreeEnemyValue(definitions.Values.Select((NativeUnit[] source) => source.Select((NativeUnit u) => u.Cost).ToArray()).ToArray());
		EncounterSelection best = null;
		decimal distance = decimal.MaxValue;
		int num = 0;
		foreach (TABSCampaignLevelAsset level in GameDatabase.Levels)
		{
			NativeUnit[] units = definitions[level];
			if (units.Length == 0 || !units.Any((NativeUnit u) => CoreCarryRules.Recommended(u.Blueprint.Entity.Name)) || !FactionEncounterRules.IsAvailable(GameDatabase.Id(level.Entity.GUID), run.Stage, custom: false, run.EncounterLastStages, run.EncounterLastCustom))
			{
				continue;
			}
			int carry = (from i in Enumerable.Range(0, units.Length)
				where CoreCarryRules.Recommended(units[i].Blueprint.Entity.Name)
				orderby units[i].NativeCost descending
				select i).First();
			if (units[carry].HasFaction("legacy") && units.Any((NativeUnit u) => u.Id != units[carry].Id && u.HasFaction("legacy")))
			{
				continue;
			}
			CoreCarryPlan coreCarryPlan = CoreCarryRules.AllocateStars(units.Select((NativeUnit u) => u.Cost).ToArray(), carry, target, allowThree: true);
			if (coreCarryPlan != null)
			{
				PromoteLate(units.Select((NativeUnit u) => u.Cost).ToArray(), carry, coreCarryPlan, target, globalThree);
				if (NormalPopulationAllowed(run, units, coreCarryPlan.Stars, carry) && Allowed(run, units, coreCarryPlan.Stars) && FactionEncounterRules.AllowsNative(run.Stage, coreCarryPlan.Stars) && !FactionEncounterRules.ShouldReplace(run.Stage, coreCarryPlan.Stars))
				{
					Consider(new EncounterSelection
					{
						Template = level,
						Units = units,
						Stars = coreCarryPlan.Stars,
						CoreIndex = carry,
						Variant = "native",
						Value = coreCarryPlan.Value
					}, target, run.RecentEncounterMaps, ref best, ref distance);
				}
			}
		}
		foreach (NativeUnit item in eligible.Where((NativeUnit u) => CoreCarryRules.Recommended(u.Blueprint.Entity.Name)))
		{
			string[] array = item.FactionKeys.Where((string k) => k != "secret" && k != "monarch").ToArray();
			if (array.Length == 0)
			{
				array = item.FactionKeys;
			}
			string[] array2 = array;
			foreach (string faction in array2)
			{
				TABSCampaignLevelAsset[] array3 = GameDatabase.Levels.Where((TABSCampaignLevelAsset l) => definitions[l].Any((NativeUnit u) => u.HasFaction(faction)) && FactionEncounterRules.IsAvailable(GameDatabase.Id(l.Entity.GUID), run.Stage, custom: true, run.EncounterLastStages, run.EncounterLastCustom)).ToArray();
				if (array3.Length == 0)
				{
					continue;
				}
				TABSCampaignLevelAsset template = array3[(uint)run.Serial % (uint)array3.Length];
				foreach (int item2 in from n in AvailableThresholds(run, faction)
					where run.Stage <= 10 || faction == "legacy" || n >= Math.Min(7, eligible.Count((NativeUnit u) => u.HasFaction(faction)))
					select n)
				{
					CoreArmyPlan coreArmyPlan = CoreArmyRules.Build(pool, item.Id, faction, item2, run.Stage, target, classThresholds, (string[] ids) => Allowed(run, ids.Select((string id) => lookup[id]).ToArray(), Enumerable.Repeat(1, ids.Length).ToArray()));
					num++;
					if (coreArmyPlan != null)
					{
						NativeUnit[] array4 = coreArmyPlan.Ids.Select((string id) => lookup[id]).ToArray();
						CoreCarryPlan coreCarryPlan2 = new CoreCarryPlan
						{
							Stars = coreArmyPlan.Stars,
							Value = coreArmyPlan.Value
						};
						PromoteLate(array4.Select((NativeUnit u) => u.Cost).ToArray(), 0, coreCarryPlan2, target, globalThree);
						if (NormalPopulationAllowed(run, array4, coreCarryPlan2.Stars, 0) && FactionEncounterRules.IsAvailable(CompositionKey(coreArmyPlan.Ids, coreCarryPlan2.Stars), run.Stage, custom: true, run.EncounterLastStages, run.EncounterLastCustom))
						{
							Consider(new EncounterSelection
							{
								Template = template,
								Units = array4,
								Stars = coreCarryPlan2.Stars,
								Variant = "custom:" + faction,
								Value = coreCarryPlan2.Value,
								Generated = true
							}, target, run.RecentEncounterMaps, ref best, ref distance);
						}
					}
				}
			}
		}
		NineFivePlan nineFivePlan = NineFiveRules.Plan((from u in eligible
			where u.Cost == 5
			select u.Id).ToArray(), target, (string[] ids) => Allowed(run, ids.Select((string id) => lookup[id]).ToArray(), Enumerable.Repeat(1, ids.Length).ToArray()));
		if (nineFivePlan != null)
		{
			NativeUnit[] units2 = nineFivePlan.UnitIds.Select((string id) => lookup[id]).ToArray();
			int num3 = (from i in Enumerable.Range(0, units2.Length)
				where CoreCarryRules.Recommended(units2[i].Blueprint.Entity.Name) && (!units2[i].HasFaction("legacy") || units2.All((NativeUnit u) => u.Id == units2[i].Id || !u.HasFaction("legacy")))
				orderby units2[i].NativeCost descending
				select i).DefaultIfEmpty(-1).First();
			CoreCarryPlan coreCarryPlan3 = ((num3 < 0) ? null : CoreCarryRules.AllocateStars(units2.Select((NativeUnit u) => u.Cost).ToArray(), num3, target, allowThree: true));
			TABSCampaignLevelAsset val = ((IEnumerable<TABSCampaignLevelAsset>)GameDatabase.Levels).FirstOrDefault((Func<TABSCampaignLevelAsset, bool>)((TABSCampaignLevelAsset l) => (Object)(object)l != (Object)(object)GameDatabase.War() && FactionEncounterRules.IsAvailable(GameDatabase.Id(l.Entity.GUID), run.Stage, custom: true, run.EncounterLastStages, run.EncounterLastCustom)));
			if ((Object)(object)val != (Object)null && coreCarryPlan3 != null && NormalPopulationAllowed(run, units2, coreCarryPlan3.Stars, num3) && FactionEncounterRules.IsAvailable(CompositionKey(nineFivePlan.UnitIds, coreCarryPlan3.Stars), run.Stage, custom: true, run.EncounterLastStages, run.EncounterLastCustom))
			{
				Consider(new EncounterSelection
				{
					Template = val,
					Units = units2,
					Stars = coreCarryPlan3.Stars,
					CoreIndex = num3,
					Variant = "custom:ninefive",
					Value = coreCarryPlan3.Value,
					Generated = true
				}, target, run.RecentEncounterMaps, ref best, ref distance);
			}
		}
		MainPlugin.Log.LogInfo((object)("Core encounter planning ms=" + stopwatch.ElapsedMilliseconds + " plans=" + num + " population=" + ((best != null) ? best.Units.Length : 0) + " carry=" + ((best == null) ? "none" : best.Units[best.CoreIndex].Blueprint.Entity.Name)));
		return best;
	}

	private static void PromoteLate(int[] costs, int carry, CoreCarryPlan plan, int target, decimal globalThree)
	{
		if (plan.Stars.Any((int s) => s < 3) || (decimal)target <= globalThree)
		{
			return;
		}
		int[] array = new int[1] { carry }.Concat(from i in Enumerable.Range(0, costs.Length)
			where i != carry
			select i).ToArray();
		for (int num = 4; num <= 5 && (num != 5 || (!((decimal)target <= globalThree * 3m) && !plan.Stars.Any((int s) => s < 4))); num++)
		{
			int[] array2 = array;
			foreach (int num3 in array2)
			{
				if (plan.Stars[num3] < num)
				{
					decimal num4 = CampaignRules.EnemyPrice(costs[num3], num) - CampaignRules.EnemyPrice(costs[num3], num - 1);
					if (plan.Value + num4 > (decimal)target)
					{
						return;
					}
					plan.Stars[num3] = num;
					plan.Value += num4;
				}
			}
		}
	}

	internal static string CompositionKey(string[] ids, int[] stars)
	{
		return "army:" + string.Join(";", ids.Select((string id, int i) => id + "@" + stars[i]).OrderBy<string, string>((string v) => v, StringComparer.Ordinal));
	}

	internal static NativeUnit[] Definitions(TABSCampaignLevelAsset level)
	{
		return (from u in level.BlueUnits
			where u != null && (Object)(object)u.m_unitBlueprint != (Object)null
			select GameDatabase.Find(GameDatabase.Id(u.m_unitBlueprint.Entity.GUID)) into u
			where u != null && !u.Modded
			select u).ToArray();
	}

	private static void Consider(EncounterSelection candidate, int target, IList<string> recentMaps, ref EncounterSelection best, ref decimal distance)
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		decimal num = Math.Abs(candidate.Value - (decimal)target);
		bool flag = candidate.Value <= (decimal)target;
		bool flag2 = !candidate.Generated && recentMaps != null && recentMaps.Contains(GameDatabase.Id(candidate.Template.MapAsset.Entity.GUID));
		bool flag3 = best != null && !best.Generated && recentMaps != null && recentMaps.Contains(GameDatabase.Id(best.Template.MapAsset.Entity.GUID));
		if (best == null || (flag && best.Value > (decimal)target) || (flag == best.Value <= (decimal)target && ((!flag2 && flag3) || (flag2 == flag3 && num < distance))))
		{
			best = candidate;
			distance = num;
		}
	}
}
public sealed class CampaignPlan
{
	public int LevelIndex = -1;

	public int[] Stars;

	public decimal Value;
}
public static class CampaignRules
{
	public static bool FiniteBudget(int budget)
	{
		if (budget > 0)
		{
			return budget < 999999;
		}
		return false;
	}

	public static bool Upgraded(int stage, int round)
	{
		if (stage >= 4 && round >= 1 && round <= 6)
		{
			return round % 2 == 1;
		}
		return false;
	}

	public static long Price(int cost, int stars)
	{
		int num = Math.Max(1, Math.Min(5, stars));
		long num2 = 1L;
		for (int i = 1; i < num; i++)
		{
			num2 *= 3;
		}
		return Math.Max(1L, cost) * num2;
	}

	public static decimal EnemyPrice(int cost, int stars)
	{
		return (decimal)Price(cost, stars) * 1.5m;
	}

	public static decimal MaximumThreeEnemyValue(int[][] formations)
	{
		return (from c in formations ?? Array.Empty<int[]>()
			where c != null && c.Length != 0
			select c.Sum((int v) => EnemyPrice(v, 3))).DefaultIfEmpty(0m).Max();
	}

	public static long MaximumThreeValue(int[][] formations)
	{
		return (from c in formations ?? Array.Empty<int[]>()
			where c != null && c.Length != 0
			select c.Sum((int v) => Price(v, 3))).DefaultIfEmpty(0L).Max();
	}

	public static CampaignPlan Plan(int[] costs, int target, bool upgraded, decimal maximumThreeValue)
	{
		return PlanCore(costs, target, upgraded, maximumThreeValue, shopCurrency: false);
	}

	public static CampaignPlan PlanShop(int[] costs, int target, bool upgraded, decimal maximumThreeValue)
	{
		return PlanCore(costs, target, upgraded, maximumThreeValue, shopCurrency: true);
	}

	private static CampaignPlan PlanCore(int[] costs, int target, bool upgraded, decimal maximumThreeValue, bool shopCurrency)
	{
		if (costs == null || costs.Length == 0)
		{
			return null;
		}
		int[] array = Enumerable.Repeat(1, costs.Length).ToArray();
		Func<int, int, decimal> quote = (int cost, int star) => (!shopCurrency) ? ((decimal)Price(cost, star)) : EnemyPrice(cost, star);
		decimal value = costs.Sum((int c) => quote(c, 1));
		if (upgraded || (maximumThreeValue > 0m && (decimal)((long)target * 9L) > maximumThreeValue))
		{
			int[] array2 = (from i in Enumerable.Range(0, costs.Length)
				orderby Math.Max(1, costs[i]), i
				select i).ToArray();
			int num = array2[0];
			value += quote(costs[num], 3) - quote(costs[num], 1);
			array[num] = 3;
			foreach (int item in array2.Skip(1))
			{
				decimal num2 = quote(costs[item], 3) - quote(costs[item], 1);
				if (value + num2 > (decimal)target)
				{
					break;
				}
				value += num2;
				array[item] = 3;
			}
			if ((decimal)target > maximumThreeValue && (shopCurrency || target > 15000) && array.All((int s) => s == 3))
			{
				Promote(costs, array2, array, 4, target, quote, ref value);
			}
			if ((shopCurrency ? ((decimal)(long)target > maximumThreeValue * 3m) : (target > 60000)) && array.All((int s) => s == 4))
			{
				Promote(costs, array2, array, 5, target, quote, ref value);
			}
		}
		return new CampaignPlan
		{
			Stars = array,
			Value = value
		};
	}

	private static void Promote(int[] costs, int[] ordered, int[] stars, int tier, int target, Func<int, int, decimal> quote, ref decimal value)
	{
		foreach (int num in ordered)
		{
			decimal num2 = quote(costs[num], tier) - quote(costs[num], tier - 1);
			if (!(value + num2 > (decimal)target))
			{
				value += num2;
				stars[num] = tier;
				continue;
			}
			break;
		}
	}

	public static CampaignPlan Choose(string[] ids, int[][] formations, IEnumerable<string> usedIds, int target, bool upgraded)
	{
		return ChooseCore(ids, formations, usedIds, target, upgraded, shopCurrency: false);
	}

	public static CampaignPlan ChooseShop(string[] ids, int[][] formations, IEnumerable<string> usedIds, int target, bool upgraded)
	{
		return ChooseCore(ids, formations, usedIds, target, upgraded, shopCurrency: true);
	}

	private static CampaignPlan ChooseCore(string[] ids, int[][] formations, IEnumerable<string> usedIds, int target, bool upgraded, bool shopCurrency)
	{
		if (ids == null || formations == null || ids.Length != formations.Length)
		{
			return null;
		}
		HashSet<string> hashSet = new HashSet<string>(usedIds ?? Enumerable.Empty<string>(), StringComparer.Ordinal);
		decimal maximumThreeValue = (shopCurrency ? MaximumThreeEnemyValue(formations) : ((decimal)MaximumThreeValue(formations)));
		CampaignPlan campaignPlan = null;
		decimal num = decimal.MaxValue;
		for (int i = 0; i < ids.Length; i++)
		{
			if (string.IsNullOrEmpty(ids[i]) || hashSet.Contains(ids[i]))
			{
				continue;
			}
			CampaignPlan campaignPlan2 = PlanCore(formations[i], target, upgraded, maximumThreeValue, shopCurrency);
			if (campaignPlan2 != null)
			{
				bool flag = campaignPlan2.Value <= (decimal)target;
				bool flag2 = campaignPlan != null && campaignPlan.Value <= (decimal)target;
				decimal num2 = Math.Abs(campaignPlan2.Value - (decimal)target);
				if (campaignPlan == null || (flag && !flag2) || (flag == flag2 && num2 < num))
				{
					campaignPlan = campaignPlan2;
					campaignPlan.LevelIndex = i;
					num = num2;
				}
			}
		}
		return campaignPlan;
	}
}
public sealed class CardHoverMotion : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
{
	private RectTransform card;

	private Vector2 restingPosition;

	private Vector3 restingScale;

	private int restingSibling;

	private bool hovering;

	private bool captured;

	private float progress;

	private void OnEnable()
	{
		//IL_0022: 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_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		card = ((Component)this).GetComponent<RectTransform>();
		if (!((Object)(object)card == (Object)null))
		{
			restingPosition = card.anchoredPosition;
			restingScale = ((Transform)card).localScale;
			captured = true;
		}
	}

	public void OnPointerEnter(PointerEventData data)
	{
		if (captured && !hovering)
		{
			restingSibling = ((Transform)card).GetSiblingIndex();
			hovering = true;
			((Transform)card).SetAsLastSibling();
		}
	}

	public void OnPointerExit(PointerEventData data)
	{
		if (hovering)
		{
			hovering = false;
			RestoreSibling();
		}
	}

	private void Update()
	{
		//IL_0039: 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_0061: 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)
		if (captured)
		{
			progress = Mathf.MoveTowards(progress, (float)(hovering ? 1 : 0), Time.unscaledDeltaTime * 9f);
			((Transform)card).localScale = restingScale * (1f + 0.04f * progress);
			card.anchoredPosition = restingPosition + new Vector2(0f, 4f * progress);
		}
	}

	private void RestoreSibling()
	{
		if ((Object)(object)card != (Object)null && (Object)(object)((Transform)card).parent != (Object)null)
		{
			((Transform)card).SetSiblingIndex(Mathf.Clamp(restingSibling, 0, ((Transform)card).parent.childCount - 1));
		}
	}

	private void OnDisable()
	{
		//IL_0030: 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)
		if (captured)
		{
			if (hovering)
			{
				RestoreSibling();
			}
			hovering = false;
			progress = 0f;
			card.anchoredPosition = restingPosition;
			((Transform)card).localScale = restingScale;
			captured = false;
		}
	}
}
public static class ClassCatalog
{
	private static readonly Dictionary<string, string> Names = new Dictionary<string, string>
	{
		{ "assassin", "刺客" },
		{ "rapidfire", "迅捷射手" },
		{ "brawler", "斗士" },
		{ "arcanist", "法师" },
		{ "guardian", "护卫" },
		{ "gunner", "枪手" },
		{ "vanguard", "重装战士" },
		{ "cavalier", "重骑兵" },
		{ "colossus", "巨像" },
		{ "shapeshifter", "变形师" }
	};

	private static readonly Dictionary<string, string[]> Descriptions = new Dictionary<string, string[]>
	{
		{
			"assassin",
			new string[4] { "刺客单位获得移速和吸血加成。", "移速 +10%,吸血 +10%", "移速 +20%,吸血 +20%", "移速 +30%,吸血 +25%,杀手隐身" }
		},
		{
			"rapidfire",
			new string[4] { "迅捷射手每次攻击获得可叠加的攻速。", "每次攻击攻速 +10%,最多 10 层", "每次攻击攻速 +15%,最多 12 层", "每次攻击攻速 +20%,最多 15 层" }
		},
		{
			"brawler",
			new string[6] { "斗士单位获得生命加成。", "生命 +20%", "生命 +40%", "生命 +100%", "生命 +200%", "生命 +350%" }
		},
		{
			"arcanist",
			new string[8] { "所有友军获得伤害加成,法师额外获得伤害加成。", "全队伤害 +2%,法师额外伤害 +20%", "全队伤害 +3%,法师额外伤害 +30%", "全队伤害 +5%,法师额外伤害 +40%", "全队伤害 +7%,法师额外伤害 +60%", "全队伤害 +9%,法师额外伤害 +80%", "全队伤害 +11%,法师额外伤害 +100%", "全队伤害 +16%,法师额外伤害 +150%" }
		},
		{
			"guardian",
			new string[6] { "护卫生命降至 50% 时获得神盾,每场战斗触发一次。", "半血时获得神盾,每场一次", "开战生命 +100,半血时获得神盾,每场一次", "开战生命 +300,半血时获得神盾,每场一次", "开战生命 +10%,半血时获得神盾,每场一次", "开战生命 +20%,半血时获得神盾,每场一次,开战时获得神盾" }
		},
		{
			"gunner",
			new string[5] { "枪手获得伤害加成,并在多次攻击后造成额外伤害。", "伤害 +6%,每 4 次攻击额外造成 70 伤害", "伤害 +9%,每 4 次攻击额外造成 100 伤害", "伤害 +11%,每 3 次攻击额外造成 150 伤害", "伤害 +15%,每 2 次攻击额外造成 250 伤害" }
		},
		{
			"vanguard",
			new string[6] { "重装战士在战斗开始时获得生命与伤害加成。", "开战生命 +400,伤害 +10%", "开战生命 +600,伤害 +20%", "开战生命 +800,伤害 +30%", "开战生命 +1000,伤害 +40%", "开战生命 +1500,伤害 +60%,攻速 +50%" }
		},
		{
			"cavalier",
			new string[4] { "重骑兵单位获得移速、生命与伤害加成。", "移速 +20%,生命 +10%,伤害 +0%", "移速 +40%,生命 +25%,伤害 +10%", "移速 +60%,生命 +70%,伤害 +20%" }
		},
		{
			"colossus",
			new string[7] { "巨像单位获得生命与抛射物格挡能力。", "占用 2 个队伍栏位,生命 +50%,抛射物格挡", "占用 2 个队伍栏位,生命 +80%,伤害 +10%,抛射物格挡,人口上限 +1", "占用 2 个队伍栏位,生命 +100%,伤害 +20%,抛射物格挡,人口上限 +1", "占用 2 个队伍栏位,生命 +120%,伤害 +30%,抛射物格挡,人口上限 +2", "占用 2 个队伍栏位,生命 +140%,伤害 +40%,抛射物格挡,人口上限 +2", "占用 2 个队伍栏位,生命 +200%,伤害 +50%,神级抛射物格挡,人口上限 +2" }
		},
		{
			"shapeshifter",
			new string[5] { "变形师在变身后获得生命与攻速加成。", "生命 +30%,攻速 +20%", "生命 +50%,攻速 +50%", "生命 +100,生命 +70%,攻速 +75%", "生命 +200,生命 +120%,攻速 +120%" }
		}
	};

	private static readonly Dictionary<string, string[]> IconSources = new Dictionary<string, string[]>
	{
		{
			"assassin",
			new string[2] { "UNIT_FANTASYEVIL_FANTASYASSASSIN", "Shadow Walker" }
		},
		{
			"rapidfire",
			new string[2] { "UNIT_LEGACY_POACHER", "Poacher" }
		},
		{
			"brawler",
			new string[2] { "UNIT_LEGACY_LEG_BOXER", "Boxer" }
		},
		{
			"arcanist",
			new string[2] { "UNIT_LEGACY_LEG_WIZARD", "Wizard" }
		},
		{
			"guardian",
			new string[2] { "UNIT_MEDIEVAL_KNIGHT", "Knight" }
		},
		{
			"gunner",
			new string[3] { "UNIT_RENAISSANCE_MUSKET", "UNIT_RENAISSANCE_MUSKETEER", "Musketeer" }
		},
		{
			"vanguard",
			new string[2] { "UNIT_FANTASYGOOD_GOOD_CLERIC", "Righteous Paladin" }
		},
		{
			"cavalier",
			new string[2] { "UNIT_RENAISSANCE_JOUSTERONHORSE", "Jouster" }
		},
		{
			"colossus",
			new string[2] { "UNIT_SECRET_SKELETONGIANT", "Skeleton Giant" }
		},
		{
			"shapeshifter",
			new string[2] { "UNIT_FANTASYGOOD_TIMENINJA", "Chronomancer" }
		}
	};

	public static string Name(string key)
	{
		string text;
		if (key == null || !Names.TryGetValue(key, out var value))
		{
			text = key;
			if (text == null)
			{
				return "";
			}
		}
		else
		{
			text = value;
		}
		return text;
	}

	public static string Description(string key, int count)
	{
		if (key == null || !Descriptions.TryGetValue(key, out var value))
		{
			return "";
		}
		StringBuilder stringBuilder = new StringBuilder(value[0]);
		int[] array = ClassRules.Thresholds(key);
		for (int i = 0; i < array.Length; i++)
		{
			stringBuilder.Append("\n<color=").Append((count >= array[i]) ? "#FFFFFF" : "#858B96").Append(">(")
				.Append(array[i])
				.Append(") ")
				.Append(value[i + 1])
				.Append("</color>");
		}
		return stringBuilder.ToString();
	}

	private static string Normalize(string value)
	{
		return new string((value ?? "(none)").Where(char.IsLetterOrDigit).Select(char.ToUpperInvariant).ToArray());
	}

	public static bool IsIconSource(string key, string entityName)
	{
		if (!IconSources.TryGetValue(key, out var value))
		{
			return false;
		}
		string normalized = Normalize(entityName);
		return value.Any((string source) => Normalize(source) == normalized);
	}
}
internal sealed class NativeAttackTag : MonoBehaviour
{
	internal ClassEffects.AttackToken Token;

	private void OnDisable()
	{
		Token = null;
	}
}
internal static class ClassEffects
{
	internal sealed class AttackToken
	{
		internal Unit Source;

		internal int Epoch;

		internal float Extra;

		internal bool Consumed;

		internal bool Reserved;

		internal bool SuppressProcs;

		internal GearEffects.HitStamp Gear;
	}

	internal sealed class ShotBinding
	{
		internal RangeWeapon Weapon;

		internal AttackToken Token;

		internal bool Fired;
	}

	internal struct HitContext
	{
		internal AttackToken Token;

		internal ShotBinding Shot;
	}

	internal sealed class Runtime
	{
		internal UnitState State;

		internal int Attacks;

		internal bool Transformed;

		internal bool GuardianHalf;

		internal bool GuardianStart;

		internal bool PoofGiven;

		internal float HasteFactor;

		internal float HasteBonus;

		internal readonly Dictionary<string, int> Counts = new Dictionary<string, int>();

		internal readonly List<GameObject> Added = new List<GameObject>();

		internal readonly HashSet<string> NativeAbilities = new HashSet<string>();

		internal readonly List<KeyValuePair<MeleeWeapon, Action>> Swings = new List<KeyValuePair<MeleeWeapon, Action>>();

		internal readonly List<Weapon> BoundWeapons = new List<Weapon>();

		internal readonly List<KeyValuePair<RangeWeapon, UnityAction>> Shoots = new List<KeyValuePair<RangeWeapon, UnityAction>>();

		internal readonly List<KeyValuePair<UnitSpawner, Action<GameObject>>> Transforms = new List<KeyValuePair<UnitSpawner, Action<GameObject>>>();

		internal GameObject Guardian;

		internal int Count(string key)
		{
			if (!Counts.TryGetValue(key, out var value))
			{
				return 0;
			}
			return value;
		}
	}

	private static readonly Dictionary<Unit, Runtime> Units = new Dictionary<Unit, Runtime>();

	private static readonly Dictionary<Weapon, Runtime> Weapons = new Dictionary<Weapon, Runtime>();

	private static readonly Dictionary<CollisionWeapon, AttackToken> MeleeHits = new Dictionary<CollisionWeapon, AttackToken>();

	private static ConditionalWeakTable<object, ShotBinding> Shots = new ConditionalWeakTable<object, ShotBinding>();

	[ThreadStatic]
	internal static AttackToken Current;

	[ThreadStatic]
	internal static ShotBinding CurrentShot;

	private static int epoch;

	private static bool Has(UnitState state, string key)
	{
		if ((Object)(object)state != (Object)null)
		{
			return state.HasTrait(key);
		}
		return false;
	}

	private static bool Alive(UnitState state)
	{
		if ((Object)(object)state != (Object)null && (Object)(object)state.Unit != (Object)null && (Object)(object)state.Unit.data != (Object)null && !state.Unit.data.Dead)
		{
			return state.Unit.data.health > 0f;
		}
		return false;
	}

	internal static void Prepare(IList<UnitState> deployed)
	{
		foreach (UnitState item in deployed)
		{
			Register(item, null);
		}
	}

	private static Runtime Register(UnitState state, Runtime previous)
	{
		//IL_025b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0262: Expected O, but got Unknown
		Runtime runtime = new Runtime
		{
			State = state,
			Transformed = (previous != null),
			HasteFactor = state.BaseHaste
		};
		string[] keys = ClassRules.Keys;
		foreach (string key in keys)
		{
			runtime.Counts[key] = previous?.Count(key) ?? (state.Traits.TryGetValue(key, out var value) ? value : 0);
		}
		if (previous != null)
		{
			runtime.Attacks = previous.Attacks;
			runtime.GuardianHalf = previous.GuardianHalf;
			runtime.GuardianStart = previous.GuardianStart;
			runtime.PoofGiven = previous.PoofGiven;
		}
		Units[state.Unit] = runtime;
		Component[] componentsInChildren = ((Component)state.Unit).GetComponentsInChildren<Component>(true);
		foreach (Component val in componentsInChildren)
		{
			if ((Object)(object)val == (Object)null || (Object)(object)val.GetComponentInParent<Unit>() != (Object)(object)state.Unit)
			{
				continue;
			}
			SpecialAbility val2 = (SpecialAbility)(object)((val is SpecialAbility) ? val : null);
			if ((Object)(object)val2 != (Object)null && ((CharacterItem)val2).Entity != null)
			{
				runtime.NativeAbilities.Add(((CharacterItem)val2).Entity.Name);
			}
			Weapon val3 = (Weapon)(object)((val is Weapon) ? val : null);
			if ((Object)(object)val3 != (Object)null)
			{
				Weapons[val3] = runtime;
				runtime.BoundWeapons.Add(val3);
				MeleeWeapon melee = (MeleeWeapon)(object)((val3 is MeleeWeapon) ? val3 : null);
				if ((Object)(object)melee != (Object)null)
				{
					CollisionWeapon collision = ((Component)melee).GetComponent<CollisionWeapon>();
					Action action = delegate
					{
						AttackToken attackToken = Attack((Weapon)(object)melee);
						if ((Object)(object)collision != (Object)null)
						{
							if (attackToken != null)
							{
								MeleeHits[collision] = attackToken;
							}
							else
							{
								MeleeHits.Remove(collision);
							}
						}
					};
					MeleeWeapon obj = melee;
					obj.swingAction = (Action)Delegate.Combine(obj.swingAction, action);
					runtime.Swings.Add(new KeyValuePair<MeleeWeapon, Action>(melee, action));
				}
				RangeWeapon ranged = (RangeWeapon)(object)((val3 is RangeWeapon) ? val3 : null);
				if ((Object)(object)ranged != (Object)null && ranged.shootEvent != null)
				{
					UnityAction val4 = (UnityAction)delegate
					{
						Shoot(ranged);
					};
					ranged.shootEvent.AddListener(val4);
					runtime.Shoots.Add(new KeyValuePair<RangeWeapon, UnityAction>(ranged, val4));
				}
			}
			UnitSpawner val5 = (UnitSpawner)(object)((val is UnitSpawner) ? val : null);
			if (!((Object)(object)val5 != (Object)null) || !NativeClassAbilities.IsTransformation(val5))
			{
				continue;
			}
			Action<GameObject> action2 = delegate(GameObject body)
			{
				if (!((Object)(object)body == (Object)null) && Scope.Active && Scope.C.InBattle)
				{
					Unit component = body.GetComponent<Unit>();
					if ((Object)(object)component != (Object)null)
					{
						Scope.C.Bridge.RegisterTransformation(runtime.State, component);
					}
				}
			};
			val5.spawnUnitAction = (Action<GameObject>)Delegate.Combine(val5.spawnUnitAction, action2);
			runtime.Transforms.Add(new KeyValuePair<UnitSpawner, Action<GameObject>>(val5, action2));
		}
		return runtime;
	}

	internal static void ApplyStats(UnitState state, Dictionary<string, int> own, ref float hp, ref float flatHp, ref float damage, ref float haste, ref float speed)
	{
		own.TryGetValue("arcanist", out var value);
		damage += ClassRules.ArcanistTeamDamage(value);
		if (Units.TryGetValue(state.Unit, out var value2))
		{
			float num = 0f;
			float num2 = 0f;
			if (Has(state, "assassin"))
			{
				num2 += ClassRules.AssassinSpeed(value2.Count("assassin"));
				state.Lifesteal += ClassRules.AssassinLifesteal(value2.Count("assassin"));
			}
			if (Has(state, "brawler"))
			{
				num += ClassRules.BrawlerHealth(value2.Count("brawler"));
			}
			if (Has(state, "arcanist"))
			{
				damage += ClassRules.ArcanistSelfDamage(value2.Count("arcanist"));
			}
			if (Has(state, "guardian"))
			{
				num += ClassRules.GuardianHealth(value2.Count("guardian"));
				flatHp += ClassRules.GuardianFlatHealth(value2.Count("guardian"));
			}
			if (Has(state, "gunner"))
			{
				damage += ClassRules.GunnerDamage(value2.Count("gunner"));
			}
			if (Has(state, "vanguard"))
			{
				flatHp += ClassRules.VanguardFlatHealth(value2.Count("vanguard"));
				damage += ClassRules.VanguardDamage(value2.Count("vanguard"));
				haste += ClassRules.VanguardHaste(value2.Count("vanguard"));
			}
			if (Has(state, "cavalier"))
			{
				num += ClassRules.CavalierHealth(value2.Count("cavalier"));
				num2 += ClassRules.CavalierSpeed(value2.Count("cavalier"));
				damage += ClassRules.CavalierDamage(value2.Count("cavalier"));
			}
			if (Has(state, "colossus"))
			{
				num += ClassRules.ColossusHealth(value2.Count("colossus"));
				damage += ClassRules.ColossusDamage(value2.Count("colossus"));
			}
			if (value2.Transformed && Has(state, "shapeshifter"))
			{
				flatHp += ClassRules.ShapeshifterFlatHealth(value2.Count("shapeshifter"));
				num += ClassRules.ShapeshifterHealth(value2.Count("shapeshifter"));
				haste += ClassRules.ShapeshifterHaste(value2.Count("shapeshifter"));
			}
			hp = (hp + flatHp) * (1f + num);
			flatHp = 0f;
			speed *= 1f + num2;
		}
	}

	internal static float CaptureHaste(UnitState state, float factor, float bonus)
	{
		if (!Units.TryGetValue(state.Unit, out var value))
		{
			return bonus;
		}
		value.HasteFactor = factor;
		value.HasteBonus = bonus;
		return bonus + (Has(state, "rapidfire") ? ClassRules.RapidfireHaste(value.Count("rapidfire"), value.Attacks) : 0f) + GearEffects.AttackHaste(state, value.Attacks);
	}

	internal static AttackToken Attack(Weapon weapon)
	{
		if (!Scope.Active || !Scope.C.InBattle || (Object)(object)weapon == (Object)null || !Weapons.TryGetValue(weapon, out var value) || !Alive(value.State))
		{
			return null;
		}
		if (Current != null && Current.SuppressProcs)
		{
			return null;
		}
		if (value.Attacks < int.MaxValue)
		{
			value.Attacks++;
		}
		GearEffects.HitStamp gear = GearEffects.Attack(value.State, value.Attacks);
		float num = (Has(value.State, "rapidfire") ? ClassRules.RapidfireHaste(value.Count("rapidfire"), value.Attacks) : 0f);
		float num2 = Mathf.Max(0.01f, value.HasteFactor * (1f + value.HasteBonus + num + GearEffects.AttackHaste(value.State, value.Attacks)));
		value.State.Unit.AddAttackSpeed(num2 - value.State.Unit.attackSpeedMultiplier);
		int count = value.Count("gunner");
		float extra = ((Has(value.State, "gunner") && ClassRules.IsGunnerProc(count, value.Attacks)) ? ClassRules.GunnerExtraDamage(count) : 0f);
		return new AttackToken
		{
			Source = value.State.Unit,
			Epoch = epoch,
			Extra = extra,
			Gear = gear
		};
	}

	internal static AttackToken Suppressed(Unit source)
	{
		return new AttackToken
		{
			Source = source,
			Epoch = epoch,
			SuppressProcs = true
		};
	}

	internal static bool Valid(AttackToken token)
	{
		if (token != null)
		{
			return token.Epoch == epoch;
		}
		return false;
	}

	internal static void BindShot(RangeWeapon weapon, object iterator)
	{
		if (Scope.Active && Scope.C.InBattle && Weapons.ContainsKey((Weapon)(object)weapon))
		{
			Shots.Remove(iterator);
			Shots.Add(iterator, new ShotBinding
			{
				Weapon = weapon
			});
		}
	}

	private static void Shoot(RangeWeapon weapon)
	{
		ShotBinding currentShot = CurrentShot;
		if (currentShot != null && !((Object)(object)currentShot.Weapon != (Object)(object)weapon) && !currentShot.Fired)
		{
			currentShot.Fired = true;
			currentShot.Token = Attack((Weapon)(object)weapon);
			Current = currentShot.Token;
		}
	}

	internal static void BindIterator(object iterator, AttackToken token)
	{
		if (token != null)
		{
			Shots.Remove(iterator);
			Shots.Add(iterator, new ShotBinding
			{
				Token = token,
				Fired = true
			});
		}
	}

	internal static ShotBinding Shot(object iterator)
	{
		if (!Shots.TryGetValue(iterator, out var value))
		{
			return null;
		}
		return value;
	}

	internal static AttackToken Melee(CollisionWeapon weapon)
	{
		if (!MeleeHits.TryGetValue(weapon, out var value))
		{
			return null;
		}
		return value;
	}

	internal static void Tag(GameObject body, AttackToken token)
	{
		if ((Object)(object)body == (Object)null)
		{
			return;
		}
		NativeAttackTag nativeAttackTag = body.GetComponent<NativeAttackTag>();
		if (token == null || token.Epoch != epoch)
		{
			if ((Object)(object)nativeAttackTag != (Object)null)
			{