Decompiled source of New Game Deluxe v0.4.1

Retheme.Core.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Retheme.Core")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+609bf44172567216185c1ebf7d8a2c167bebee52")]
[assembly: AssemblyProduct("Retheme.Core")]
[assembly: AssemblyTitle("Retheme.Core")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Retheme.Core
{
	public static class AttunementMath
	{
		public static float Factor(MageConfig cfg, int ranks)
		{
			return 1f + Math.Max(0f, cfg.AttunementPerRank) * (float)Math.Max(0, Math.Min(7, ranks));
		}
	}
	public enum WeaponClass
	{
		Other,
		OneHanded,
		TwoHanded,
		Unarmed
	}
	public sealed class BerserkerBuild
	{
		public int Level { get; }

		public int Rank { get; }

		public string Emphasis { get; }

		public string Specialization { get; }

		public string Active10 { get; }

		public string Refinement { get; }

		public string Capstone { get; }

		public string Tier30 { get; }

		public string Tier40 { get; }

		public string Ultimate { get; }

		public int BrutalityRanks { get; }

		public int SecondWindRanks { get; }

		public int BloodlustRanks { get; }

		public int ThickHideRanks { get; }

		public BerserkerBuild(int level, int rank, IReadOnlyDictionary<int, string> choices, IReadOnlyDictionary<string, int> spent)
		{
			BerserkerBuild berserkerBuild = this;
			Level = Math.Max(1, level);
			Rank = Math.Max(0, rank);
			Emphasis = Pick(1, 0);
			Specialization = Pick(5, 0);
			Active10 = Pick(10, 1);
			Refinement = Pick(15, 1);
			Capstone = Pick(20, 2);
			Tier30 = Pick(30, 3);
			Tier40 = Pick(40, 4);
			Ultimate = Pick(50, 0);
			SecondWindRanks = R("second_wind");
			BloodlustRanks = R("bloodlust");
			ThickHideRanks = R("thick_hide");
			BrutalityRanks = ((Rank >= 4) ? R("brutality") : 0);
			string Pick(int tier, int needRank)
			{
				if (Rank < needRank || Level < tier || !choices.TryGetValue(tier, out string value))
				{
					return "";
				}
				return value;
			}
			int R(string id)
			{
				if (!spent.TryGetValue(id, out var value))
				{
					return 0;
				}
				return Math.Max(0, Math.Min(7, value));
			}
		}

		public static BerserkerBuild? From(CharacterState s)
		{
			if (s.ActiveClassId != "berserker")
			{
				return null;
			}
			ClassState activeState = s.ActiveState;
			return new BerserkerBuild(s.Level, activeState.Rank, activeState.Choices, activeState.Spent);
		}
	}
	public static class BerserkerCatalog
	{
		public const string Id = "berserker";

		public const string BloodbathId = "bloodbath";

		public const string LastStandId = "last_stand";

		public static readonly IReadOnlyList<TalentTier> Tiers = new TalentTier[8]
		{
			new TalentTier(1, 0, "relentless", "crushing", "hardened"),
			new TalentTier(5, 0, "ravager", "giantbreaker", "bloodfury"),
			new TalentTier(10, 0, "whirlwind", "crushing_blow"),
			new TalentTier(15, 0, "wrath", "endurance", "bloodied"),
			new TalentTier(20, 0, "titan_slam", "unchained"),
			new TalentTier(30, 0, "rampage", "unbroken", "sundering"),
			new TalentTier(40, 0, "bloodtithe", "momentum", "overcharge"),
			new TalentTier(50, 0, "bloodbath", "last_stand")
		};

		public static readonly IReadOnlyList<string> Upgrades = new string[4] { "second_wind", "bloodlust", "thick_hide", "brutality" };

		public static readonly ClassDefinition Definition = new ClassDefinition("berserker", "Berserker", Tiers, Upgrades, new string[6] { "Brawler", "Raider", "Berserker", "Ulfhednar", "Bloodsworn", "Einherjar" });
	}
	public sealed class BerserkerConfig
	{
		public int FuryCapLow { get; set; } = 30;

		public int FuryCapMid { get; set; } = 40;

		public int FuryCapHigh { get; set; } = 50;

		public int FuryCapMidLevel { get; set; } = 7;

		public int FuryCapHighLevel { get; set; } = 14;

		public int StaminaPerLevel { get; set; } = 1;

		public int MeleeGainMultiplier { get; set; } = 4;

		public int RavagerGainMultiplier { get; set; } = 5;

		public int GiantbreakerGainMultiplier { get; set; } = 6;

		public double MinGainInterval { get; set; } = 0.3;

		public double RavagerMinGainInterval { get; set; } = 0.15;

		public int BloodfuryKillFury { get; set; } = 20;

		public float BloodfuryKillHeal { get; set; } = 0.03f;

		public float DamagePerPoint { get; set; } = 0.004f;

		public float CrushingDamagePerPoint { get; set; } = 0.006f;

		public float StaminaSavingPerPoint { get; set; } = 0.003f;

		public float RelentlessStaminaSavingPerPoint { get; set; } = 0.005f;

		public float HardenedReductionPerPoint { get; set; } = 0.003f;

		public float UnchainedPointMultiplier { get; set; } = 2f;

		public float ClassDamageReductionCap { get; set; } = 0.3f;

		public float RelentlessDrainDelay { get; set; } = 2f;

		public float CrushingDrainDelay { get; set; } = -1f;

		public float BloodlustDrainDelayPerRank { get; set; } = 0.4f;

		public float SecondWindRegenPerRank { get; set; } = 0.05f;

		public float ThickHideReductionPerRank { get; set; } = 0.015f;

		public int FrenzyMinFury { get; set; } = 20;

		public double FrenzySeconds { get; set; } = 6.0;

		public float FrenzyDamagePerPoint { get; set; } = 0.02f;

		public float FrenzyStaminaSaving { get; set; } = 0.5f;

		public double FrenzyCooldown { get; set; } = 15.0;

		public float WhirlwindDamage { get; set; } = 1.3f;

		public float WhirlwindStagger { get; set; } = 3f;

		public float WhirlwindRadius { get; set; } = 3.5f;

		public int WhirlwindMaxTargets { get; set; } = 6;

		public int WhirlwindFurySpend { get; set; } = 15;

		public int WhirlwindFuryPerTwoTargets { get; set; } = 5;

		public int WhirlwindFuryGainCap { get; set; } = 10;

		public float WhirlwindStamina { get; set; }

		public double WhirlwindCooldown { get; set; } = 8.0;

		public float CrushingBlowDamage { get; set; } = 2.2f;

		public float CrushingBlowStagger { get; set; } = 2f;

		public int CrushingBlowFurySpend { get; set; } = 30;

		public float CrushingBlowStamina { get; set; }

		public double CrushComboSeconds { get; set; } = 6.0;

		public float CrushComboDamage { get; set; } = 0.5f;

		public double CrushingBlowCooldown { get; set; } = 6.0;

		public float WrathAbilityDamage { get; set; } = 0.15f;

		public float EnduranceFuryReduction { get; set; } = 0.2f;

		public double EnduranceFrenzyCooldownReduction { get; set; } = 5.0;

		public float BloodiedHealthThreshold { get; set; } = 0.5f;

		public float BloodiedAbilityDamage { get; set; } = 0.3f;

		public float BloodiedKillHeal { get; set; } = 0.05f;

		public float TitanSlamDamage { get; set; } = 2.5f;

		public float TitanSlamStagger { get; set; } = 4f;

		public float TitanSlamRadius { get; set; } = 5f;

		public int TitanSlamMaxTargets { get; set; } = 8;

		public int TitanSlamFurySpend { get; set; } = 20;

		public float TitanSlamStamina { get; set; }

		public double TitanSlamCooldown { get; set; } = 15.0;

		public double UnchainedSeconds { get; set; } = 10.0;

		public int UnchainedCapBonus { get; set; } = 30;

		public double UnchainedCooldown { get; set; } = 45.0;

		public double RampageSecondsPerKill { get; set; } = 1.0;

		public double RampageMaxExtraSeconds { get; set; } = 4.0;

		public float UnbrokenDamageReduction { get; set; } = 0.15f;

		public int SunderingMaxStacks { get; set; } = 3;

		public float SunderingDamagePerStack { get; set; } = 0.04f;

		public double SunderingSeconds { get; set; } = 8.0;

		public int SunderingMaxTracked { get; set; } = 64;

		public float BloodtitheHealPerPoint { get; set; } = 0.0015f;

		public double MomentumCooldownCut { get; set; } = 2.0;

		public int OverchargeCapBonus { get; set; } = 10;

		public float OverchargeDrainDelay { get; set; } = -1f;

		public float DamageTakenFuryPerPercent { get; set; } = 1f;

		public int DamageTakenFuryCap { get; set; } = 10;

		public float StructureGainShare { get; set; } = 0.5f;

		public int StructureNativeGain { get; set; } = 2;

		public int MeadFury { get; set; } = 20;

		public float BrutalityFlatPerRank { get; set; } = 2f;

		public int BloodbathCooldownSeconds { get; set; } = 15;

		public float BloodbathStrikeDamage { get; set; } = 2f;

		public float BloodbathStrikeRadius { get; set; } = 4f;

		public int BloodbathStrikeMaxTargets { get; set; } = 6;

		public float BloodbathHealFraction { get; set; } = 0.2f;

		public double BloodbathEnrageSeconds { get; set; } = 8.0;

		public float BloodbathEnrageScale { get; set; } = 1.4f;

		public float BloodbathEnrageDamage { get; set; } = 0.3f;

		public int LastStandCooldownSeconds { get; set; } = 150;

		public double LastStandImmunitySeconds { get; set; } = 10.0;

		public float LastStandMaxDamageBonus { get; set; } = 0.5f;

		public float TrinketCostFactor { get; set; } = 0.5f;

		public double TrinketMinLockoutSeconds { get; set; } = 20.0;
	}
	public sealed class AbilityResult
	{
		public bool Ok { get; }

		public Failure Reason { get; }

		public string Ability { get; }

		public int FurySpent { get; }

		public int FuryGained { get; }

		public float StaminaCost { get; }

		public float WeaponDamage { get; }

		public float DamageBonus { get; }

		public float Stagger { get; }

		public float Radius { get; }

		public int MaxTargets { get; }

		public bool TrinketProc { get; internal set; }

		public float HealFraction { get; internal set; }

		internal AbilityResult(bool ok, Failure reason, string ability, int spent = 0, int gained = 0, float stamina = 0f, float weapon = 0f, float bonus = 0f, float stagger = 1f, float radius = 0f, int maxTargets = 0)
		{
			Ok = ok;
			Reason = reason;
			Ability = ability;
			FurySpent = spent;
			FuryGained = gained;
			StaminaCost = stamina;
			WeaponDamage = weapon;
			DamageBonus = bonus;
			Stagger = stagger;
			Radius = radius;
			MaxTargets = maxTargets;
		}

		internal static AbilityResult Fail(Failure why, string ability)
		{
			return new AbilityResult(ok: false, why, ability);
		}
	}
	public sealed class BerserkerKit
	{
		private readonly BerserkerConfig _c;

		private readonly BerserkerMath _m;

		private readonly IFuryMeter _fury;

		private double _lastGain = double.NegativeInfinity;

		private double _frenzyUntil;

		private double _frenzyReady;

		private double _unchainedUntil;

		private double _unchainedReady;

		private double _tier10Ready;

		private double _titanReady;

		private double _armedUntil;

		private int _frenzyPoints;

		private float _armedBonus;

		private double _rampageExtra;

		private double _comboUntil;

		public TrinketCharge Trinket { get; }

		public RendTracker Rend { get; }

		public BerserkerKit(BerserkerConfig cfg, IFuryMeter fury, TrinketCharge? trinket = null)
		{
			_c = cfg ?? throw new ArgumentNullException("cfg");
			_fury = fury ?? throw new ArgumentNullException("fury");
			_m = new BerserkerMath(_c);
			Trinket = trinket ?? new TrinketCharge(_c);
			Rend = new RendTracker(_c);
		}

		public bool StaggerImmune(BerserkerBuild b, double now)
		{
			if (b.Tier30 == "unbroken")
			{
				return DrainSuspended(now);
			}
			return false;
		}

		public double FrenzyRemaining(double now)
		{
			return Math.Max(0.0, _frenzyUntil - now);
		}

		public int OnAbilityHit(BerserkerBuild b, int targetId, double now)
		{
			if (!(b.Tier30 == "sundering"))
			{
				return 0;
			}
			return Rend.Add(targetId, now);
		}

		public float RendFactor(BerserkerBuild b, int targetId, double now)
		{
			if (!(b.Tier30 == "sundering"))
			{
				return 1f;
			}
			return Rend.Factor(targetId, now);
		}

		private void Momentum(BerserkerBuild b, string cast, double now)
		{
			double cut;
			if (!(b.Tier40 != "momentum"))
			{
				cut = Math.Max(0.0, _c.MomentumCooldownCut);
				if (cast != "frenzy")
				{
					_frenzyReady = Cut(_frenzyReady);
				}
				if (cast != "tier10")
				{
					_tier10Ready = Cut(_tier10Ready);
				}
				if (cast != "titan")
				{
					_titanReady = Cut(_titanReady);
				}
				if (cast != "unchained")
				{
					_unchainedReady = Cut(_unchainedReady);
				}
			}
			double Cut(double ready)
			{
				if (!(ready > now))
				{
					return ready;
				}
				return Math.Max(now, ready - cut);
			}
		}

		public bool FrenzyActive(double now)
		{
			return now < _frenzyUntil;
		}

		public bool UnchainedActive(double now)
		{
			return now < _unchainedUntil;
		}

		public bool DrainSuspended(double now)
		{
			if (!FrenzyActive(now))
			{
				return UnchainedActive(now);
			}
			return true;
		}

		public bool CrushingBlowArmed(double now)
		{
			return now < _armedUntil;
		}

		public double CooldownRemaining(string ability, double now)
		{
			return Math.Max(0.0, ReadyAt(ability) - now);
		}

		private double ReadyAt(string ability)
		{
			switch (ability)
			{
			case "frenzy":
				return _frenzyReady;
			case "whirlwind":
			case "crushing_blow":
				return _tier10Ready;
			case "titan_slam":
				return _titanReady;
			case "unchained":
				return _unchainedReady;
			default:
				return 0.0;
			}
		}

		public void Sync(BerserkerBuild b, double now)
		{
			_fury.Cap = _m.FuryCap(b, UnchainedActive(now));
		}

		public int OnMeleeHit(BerserkerBuild b, WeaponClass weapon, int nativeGain, double now, float share = 1f)
		{
			Sync(b, now);
			if (FrenzyActive(now) || share <= 0f || now - _lastGain < _m.MinGainInterval(b, weapon))
			{
				return 0;
			}
			_lastGain = now;
			int num = _m.MeleeGain(b, weapon, nativeGain);
			return _fury.Add((share >= 1f) ? num : Math.Max(1, (int)Math.Round((float)num * share)));
		}

		public int OnDamageTaken(BerserkerBuild b, float damage, float maxHealth, double now)
		{
			Sync(b, now);
			if (FrenzyActive(now) || damage <= 0f || maxHealth <= 0f)
			{
				return 0;
			}
			float val = damage / maxHealth * 100f * _c.DamageTakenFuryPerPercent;
			return _fury.Add((int)Math.Round(Math.Min(_c.DamageTakenFuryCap, Math.Max(1f, val))));
		}

		public int OnStructureHit(BerserkerBuild b, WeaponClass weapon, double now)
		{
			return OnMeleeHit(b, weapon, _c.StructureNativeGain, now, _c.StructureGainShare);
		}

		public float OnKill(BerserkerBuild b, float healthFraction, double now, out int furyGained)
		{
			Sync(b, now);
			furyGained = ((!FrenzyActive(now)) ? _fury.Add(_m.KillFury(b)) : 0);
			if (b.Tier30 == "rampage" && FrenzyActive(now))
			{
				double num = Math.Max(0.0, Math.Min(_c.RampageSecondsPerKill, _c.RampageMaxExtraSeconds - _rampageExtra));
				_frenzyUntil += num;
				_rampageExtra += num;
			}
			return _m.KillHeal(b, healthFraction);
		}

		public (float Damage, float StaminaSaving) AttackModifiers(BerserkerBuild b, double now)
		{
			if (FrenzyActive(now))
			{
				return (Damage: (float)_frenzyPoints * _c.FrenzyDamagePerPoint, StaminaSaving: _c.FrenzyStaminaSaving);
			}
			bool unchained = UnchainedActive(now);
			return (Damage: _m.DamageBonus(b, _fury.Value, unchained), StaminaSaving: _m.StaminaSaving(b, _fury.Value, unchained));
		}

		public AbilityResult BloodbathStrike(BerserkerBuild b, double now, float healthFraction)
		{
			return new AbilityResult(ok: true, Failure.None, "bloodbath", 0, 0, 0f, _c.BloodbathStrikeDamage, _m.DamageBonus(b, _fury.Value, UnchainedActive(now)), 2f, _c.BloodbathStrikeRadius, _c.BloodbathStrikeMaxTargets);
		}

		public float DamageReduction(BerserkerBuild b, double now)
		{
			if (!FrenzyActive(now))
			{
				return _m.DamageReduction(b, _fury.Value, UnchainedActive(now), UnchainedActive(now));
			}
			return _m.DamageReduction(b, _frenzyPoints, UnchainedActive(now), inWindow: true);
		}

		private float AbilityBonus(BerserkerBuild b, double now, int furyAtCast, float healthFraction)
		{
			float num = _m.DamageBonus(b, furyAtCast, UnchainedActive(now));
			if (b.Refinement == "wrath")
			{
				num += _c.WrathAbilityDamage;
			}
			else if (b.Refinement == "bloodied" && healthFraction < _c.BloodiedHealthThreshold)
			{
				num += _c.BloodiedAbilityDamage;
			}
			return num;
		}

		private float Stamina(BerserkerBuild b, float baseCost)
		{
			return baseCost;
		}

		public int FuryCost(BerserkerBuild b, int spend)
		{
			if (!(b.Refinement == "endurance"))
			{
				return spend;
			}
			return (int)Math.Ceiling((float)spend * (1f - _c.EnduranceFuryReduction));
		}

		public int FuryCost(BerserkerBuild b, int spend, double now)
		{
			if (!FrenzyActive(now))
			{
				return FuryCost(b, spend);
			}
			return 0;
		}

		private int BonusFury(double now)
		{
			if (!FrenzyActive(now))
			{
				return _fury.Value;
			}
			return _frenzyPoints;
		}

		private AbilityResult Finish(AbilityResult r, double now, bool spentFury, BerserkerBuild b, string momentumKey)
		{
			if (spentFury && r.Ok)
			{
				r.TrinketProc = Trinket.Spend(r.FurySpent, now);
				r.HealFraction = _m.SpendHeal(b, r.FurySpent);
			}
			if (r.Ok)
			{
				Momentum(b, momentumKey, now);
			}
			return r;
		}

		public AbilityResult TryFrenzy(BerserkerBuild b, double now)
		{
			Sync(b, now);
			if (FrenzyActive(now))
			{
				return AbilityResult.Fail(Failure.FrenzyActive, "frenzy");
			}
			if (now < _frenzyReady)
			{
				return AbilityResult.Fail(Failure.OnCooldown, "frenzy");
			}
			if (_fury.Value < _c.FrenzyMinFury)
			{
				return AbilityResult.Fail(Failure.NotEnoughFury, "frenzy");
			}
			int value = _fury.Value;
			_fury.TrySpend(value);
			_frenzyPoints = value;
			_frenzyUntil = now + _c.FrenzySeconds;
			_frenzyReady = now + _c.FrenzyCooldown - ((b.Refinement == "endurance") ? _c.EnduranceFrenzyCooldownReduction : 0.0);
			_rampageExtra = 0.0;
			return Finish(new AbilityResult(ok: true, Failure.None, "frenzy", value), now, spentFury: true, b, "frenzy");
		}

		public AbilityResult TryActive10(BerserkerBuild b, double now, float stamina, int targets, float healthFraction)
		{
			Sync(b, now);
			string active = b.Active10;
			if (active == "")
			{
				return AbilityResult.Fail(Failure.AbilityLocked, "");
			}
			if (now < _tier10Ready)
			{
				return AbilityResult.Fail(Failure.OnCooldown, active);
			}
			if (active == "whirlwind")
			{
				float num = Stamina(b, _c.WhirlwindStamina);
				int num2 = FuryCost(b, _c.WhirlwindFurySpend, now);
				if (_fury.Value < num2)
				{
					return AbilityResult.Fail(Failure.NotEnoughFury, active);
				}
				if (stamina < num)
				{
					return AbilityResult.Fail(Failure.NotEnoughStamina, active);
				}
				float bonus = AbilityBonus(b, now, BonusFury(now), healthFraction);
				_fury.TrySpend(num2);
				int num3 = Math.Min(targets, _c.WhirlwindMaxTargets);
				int gained = ((!FrenzyActive(now)) ? _fury.Add(Math.Min(_c.WhirlwindFuryGainCap, num3 / 2 * _c.WhirlwindFuryPerTwoTargets)) : 0);
				_tier10Ready = now + _c.WhirlwindCooldown;
				return Finish(new AbilityResult(ok: true, Failure.None, active, num2, gained, num, _c.WhirlwindDamage, bonus, _c.WhirlwindStagger, _c.WhirlwindRadius, _c.WhirlwindMaxTargets), now, num2 > 0, b, "tier10");
			}
			float num4 = Stamina(b, _c.CrushingBlowStamina);
			int num5 = FuryCost(b, _c.CrushingBlowFurySpend, now);
			if (_fury.Value < num5)
			{
				return AbilityResult.Fail(Failure.NotEnoughFury, active);
			}
			if (stamina < num4)
			{
				return AbilityResult.Fail(Failure.NotEnoughStamina, active);
			}
			float num6 = AbilityBonus(b, now, BonusFury(now), healthFraction);
			_fury.TrySpend(num5);
			_armedUntil = double.PositiveInfinity;
			_armedBonus = num6;
			_tier10Ready = now + _c.CrushingBlowCooldown;
			return Finish(new AbilityResult(ok: true, Failure.None, active, num5, 0, num4, _c.CrushingBlowDamage, num6, _c.CrushingBlowStagger, 0f, 1), now, num5 > 0, b, "tier10");
		}

		public void Disarm()
		{
			_armedUntil = 0.0;
		}

		public AbilityResult? ConsumeArmedSecondary(double now)
		{
			AbilityResult? abilityResult = PeekArmedSecondary(now);
			_armedUntil = 0.0;
			if (abilityResult != null)
			{
				_comboUntil = now + _c.CrushComboSeconds;
			}
			return abilityResult;
		}

		public bool CrushComboActive(double now)
		{
			return now < _comboUntil;
		}

		public AbilityResult? PeekArmedSecondary(double now)
		{
			if (!CrushingBlowArmed(now))
			{
				return null;
			}
			return new AbilityResult(ok: true, Failure.None, "crushing_blow", 0, 0, 0f, _c.CrushingBlowDamage, _armedBonus, _c.CrushingBlowStagger, 0f, 1);
		}

		public AbilityResult TryCapstone(BerserkerBuild b, double now, float stamina, int targets, float healthFraction)
		{
			Sync(b, now);
			string capstone = b.Capstone;
			if (capstone == "")
			{
				return AbilityResult.Fail(Failure.AbilityLocked, "");
			}
			if (capstone == "unchained")
			{
				if (UnchainedActive(now))
				{
					return AbilityResult.Fail(Failure.AlreadyActive, capstone);
				}
				if (now < _unchainedReady)
				{
					return AbilityResult.Fail(Failure.OnCooldown, capstone);
				}
				_unchainedUntil = now + _c.UnchainedSeconds;
				_unchainedReady = now + _c.UnchainedCooldown;
				Sync(b, now);
				return Finish(new AbilityResult(ok: true, Failure.None, capstone), now, spentFury: false, b, "unchained");
			}
			float num = Stamina(b, _c.TitanSlamStamina);
			int num2 = FuryCost(b, _c.TitanSlamFurySpend, now);
			if (now < _titanReady)
			{
				return AbilityResult.Fail(Failure.OnCooldown, capstone);
			}
			if (targets < 1)
			{
				return AbilityResult.Fail(Failure.NoTarget, capstone);
			}
			if (_fury.Value < num2)
			{
				return AbilityResult.Fail(Failure.NotEnoughFury, capstone);
			}
			if (stamina < num)
			{
				return AbilityResult.Fail(Failure.NotEnoughStamina, capstone);
			}
			float bonus = AbilityBonus(b, now, BonusFury(now), healthFraction) + (CrushComboActive(now) ? _c.CrushComboDamage : 0f);
			_comboUntil = 0.0;
			_fury.TrySpend(num2);
			_titanReady = now + _c.TitanSlamCooldown;
			return Finish(new AbilityResult(ok: true, Failure.None, capstone, num2, 0, num, _c.TitanSlamDamage, bonus, _c.TitanSlamStagger, _c.TitanSlamRadius, _c.TitanSlamMaxTargets), now, num2 > 0, b, "titan");
		}

		public void Reset()
		{
			_fury.Clear();
			_lastGain = double.NegativeInfinity;
			_frenzyUntil = (_unchainedUntil = (_armedUntil = (_comboUntil = 0.0)));
			_frenzyPoints = 0;
			_armedBonus = 0f;
			_rampageExtra = 0.0;
			Rend.Clear();
			Trinket.Reset();
		}
	}
	public sealed class BerserkerMath
	{
		private readonly BerserkerConfig _c;

		public BerserkerMath(BerserkerConfig cfg)
		{
			_c = cfg ?? throw new ArgumentNullException("cfg");
		}

		public int BaseFuryCap(int level)
		{
			if (level < _c.FuryCapHighLevel)
			{
				if (level < _c.FuryCapMidLevel)
				{
					return _c.FuryCapLow;
				}
				return _c.FuryCapMid;
			}
			return _c.FuryCapHigh;
		}

		public int FuryCap(int level, bool unchained)
		{
			return BaseFuryCap(level) + (unchained ? _c.UnchainedCapBonus : 0);
		}

		public int FuryCap(BerserkerBuild b, bool unchained)
		{
			return FuryCap(b.Level, unchained) + ((b.Tier40 == "overcharge") ? _c.OverchargeCapBonus : 0);
		}

		public int MaxStaminaBonus(int level)
		{
			return Math.Max(0, level - 1) * _c.StaminaPerLevel;
		}

		public int GainMultiplier(BerserkerBuild b, WeaponClass w)
		{
			if (!(b.Specialization == "ravager") || (w != WeaponClass.OneHanded && w != WeaponClass.Unarmed))
			{
				if (!(b.Specialization == "giantbreaker") || w != WeaponClass.TwoHanded)
				{
					return _c.MeleeGainMultiplier;
				}
				return _c.GiantbreakerGainMultiplier;
			}
			return _c.RavagerGainMultiplier;
		}

		public double MinGainInterval(BerserkerBuild b, WeaponClass w)
		{
			if (!(b.Specialization == "ravager") || (w != WeaponClass.OneHanded && w != WeaponClass.Unarmed))
			{
				return _c.MinGainInterval;
			}
			return _c.RavagerMinGainInterval;
		}

		public int MeleeGain(BerserkerBuild b, WeaponClass w, int nativeGain)
		{
			return Math.Max(0, nativeGain) * GainMultiplier(b, w);
		}

		public float LastStandDamageBonus(BerserkerBuild b, float healthFraction)
		{
			if (b.Ultimate != "last_stand")
			{
				return 0f;
			}
			return (1f - Math.Clamp(healthFraction, 0f, 1f)) * Math.Max(0f, _c.LastStandMaxDamageBonus);
		}

		public int KillFury(BerserkerBuild b)
		{
			if (!(b.Specialization == "bloodfury"))
			{
				return 0;
			}
			return _c.BloodfuryKillFury;
		}

		public float KillHeal(BerserkerBuild b, float healthFraction)
		{
			float num = ((b.Specialization == "bloodfury") ? _c.BloodfuryKillHeal : 0f);
			if (b.Refinement == "bloodied" && healthFraction < _c.BloodiedHealthThreshold)
			{
				num += _c.BloodiedKillHeal;
			}
			return num;
		}

		private int Clamp(BerserkerBuild b, int fury, bool unchained)
		{
			return Math.Max(0, Math.Min(fury, FuryCap(b, unchained)));
		}

		public float DamageBonus(BerserkerBuild b, int fury, bool unchained = false)
		{
			float num = ((b.Emphasis == "crushing") ? _c.CrushingDamagePerPoint : _c.DamagePerPoint);
			return (float)Clamp(b, fury, unchained) * num * (unchained ? _c.UnchainedPointMultiplier : 1f);
		}

		public float StaminaSaving(BerserkerBuild b, int fury, bool unchained = false)
		{
			float num = ((b.Emphasis == "relentless") ? _c.RelentlessStaminaSavingPerPoint : _c.StaminaSavingPerPoint);
			return (float)Clamp(b, fury, unchained) * num * (unchained ? _c.UnchainedPointMultiplier : 1f);
		}

		public float DamageReduction(BerserkerBuild b, int fury, bool unchained = false, bool inWindow = false)
		{
			float num = MasteryRamp.Units(b.ThickHideRanks) * _c.ThickHideReductionPerRank;
			if (b.Tier30 == "unbroken" && inWindow)
			{
				num += _c.UnbrokenDamageReduction;
			}
			if (b.Emphasis == "hardened")
			{
				num += (float)Clamp(b, fury, unchained) * _c.HardenedReductionPerPoint;
			}
			return Math.Min(num, _c.ClassDamageReductionCap);
		}

		public float FlatDamage(BerserkerBuild b)
		{
			return (float)b.BrutalityRanks * _c.BrutalityFlatPerRank;
		}

		public float HitDamage(BerserkerBuild b, float weaponDamage, float bonus, float abilityMultiplier = 1f, float rendFactor = 1f)
		{
			return (Math.Max(0f, weaponDamage) * abilityMultiplier + FlatDamage(b)) * (1f + Math.Max(0f, bonus)) * Math.Max(1f, rendFactor);
		}

		public float SpendHeal(BerserkerBuild b, int furySpent)
		{
			if (!(b.Tier40 == "bloodtithe"))
			{
				return 0f;
			}
			return (float)Math.Max(0, furySpent) * _c.BloodtitheHealPerPoint;
		}

		public float StaminaRegenBonus(BerserkerBuild b)
		{
			return MasteryRamp.Units(b.SecondWindRanks) * _c.SecondWindRegenPerRank;
		}

		public float DrainDelayBonus(BerserkerBuild b)
		{
			float num = MasteryRamp.Units(b.BloodlustRanks) * _c.BloodlustDrainDelayPerRank;
			if (b.Tier40 == "overcharge")
			{
				num += _c.OverchargeDrainDelay;
			}
			if (b.Emphasis == "relentless")
			{
				num += _c.RelentlessDrainDelay;
			}
			else if (b.Emphasis == "crushing")
			{
				num += _c.CrushingDrainDelay;
			}
			return num;
		}
	}
	public static class BerserkerText
	{
		private static string Pc(double v)
		{
			return (v * 100.0).ToString("0.##", CultureInfo.InvariantCulture);
		}

		private static string N(double v)
		{
			return v.ToString("0.##", CultureInfo.InvariantCulture);
		}

		public static string TierName(int level)
		{
			return level switch
			{
				1 => "Rage", 
				5 => "Weapon Focus", 
				10 => "Fighting Style", 
				15 => "War Temper", 
				20 => "Warcry", 
				30 => "Battle Rites", 
				40 => "Fury", 
				50 => "Ultimate", 
				_ => $"Level {level} choice", 
			};
		}

		public static string Describe(string option, BerserkerConfig c)
		{
			return option switch
			{
				"relentless" => "Fury lasts " + N(c.RelentlessDrainDelay) + "s longer before it drains, and each Fury point saves " + Pc(c.RelentlessStaminaSavingPerPoint) + "% attack stamina instead of " + Pc(c.StaminaSavingPerPoint) + "%.", 
				"crushing" => "Each Fury point adds " + Pc(c.CrushingDamagePerPoint) + "% damage instead of " + Pc(c.DamagePerPoint) + "%, but Fury starts draining " + N(0f - c.CrushingDrainDelay) + "s sooner.", 
				"hardened" => $"Each Fury point also cuts the physical damage you take by {Pc(c.HardenedReductionPerPoint)}%, {Pc(c.HardenedReductionPerPoint * (float)c.FuryCapHigh)}% at {c.FuryCapHigh} Fury. Class damage reduction is capped at {Pc(c.ClassDamageReductionCap)}%.", 
				"ravager" => $"One-handed weapons, knives and bare hands: each melee hit gives x{c.RavagerGainMultiplier} Fury instead of x{c.MeleeGainMultiplier}, and can gain every {N(c.RavagerMinGainInterval)}s.", 
				"giantbreaker" => $"Two-handed weapons and dual axes: each melee hit gives x{c.GiantbreakerGainMultiplier} Fury instead of x{c.MeleeGainMultiplier}, and your stagger is 25% stronger.", 
				"bloodfury" => $"A kill gives {c.BloodfuryKillFury} Fury and heals {Pc(c.BloodfuryKillHeal)}% of your max health.", 
				"whirlwind" => $"A strike all around you: x{N(c.WhirlwindDamage)} weapon damage within {N(c.WhirlwindRadius)} m, up to {c.WhirlwindMaxTargets} targets, with extra stagger. Costs {c.WhirlwindFurySpend} Fury, and hitting several enemies gives some Fury back. {N(c.WhirlwindCooldown)}s cooldown. Free during Frenzy.", 
				"crushing_blow" => $"Costs {c.CrushingBlowFurySpend} Fury and arms your next secondary attack until it lands or you holster your weapon: x{N(c.CrushingBlowDamage)} weapon damage and extra stagger. A landed Crushing Blow primes Titan Slam. {N(c.CrushingBlowCooldown)}s cooldown. Free during Frenzy.", 
				"wrath" => "Your abilities (Whirlwind, Crushing Blow and Titan Slam) do " + Pc(c.WrathAbilityDamage) + "% more damage.", 
				"endurance" => "Abilities cost " + Pc(c.EnduranceFuryReduction) + "% less Fury, and Frenzy's cooldown is " + N(c.EnduranceFrenzyCooldownReduction) + "s shorter.", 
				"bloodied" => "While you are below " + Pc(c.BloodiedHealthThreshold) + "% health, abilities do " + Pc(c.BloodiedAbilityDamage) + "% more damage and a kill heals " + Pc(c.BloodiedKillHeal) + "% of your max health.", 
				"titan_slam" => $"A slam around you: x{N(c.TitanSlamDamage)} weapon damage within {N(c.TitanSlamRadius)} m, up to {c.TitanSlamMaxTargets} targets, with heavy stagger and knockback. Costs {c.TitanSlamFurySpend} Fury. Within {N(c.CrushComboSeconds)}s of a landed Crushing Blow it does {Pc(c.CrushComboDamage)}% more damage. {N(c.TitanSlamCooldown)}s cooldown. Free during Frenzy.", 
				"unchained" => $"For {N(c.UnchainedSeconds)}s your Fury cap is {c.UnchainedCapBonus} higher, Fury does not drain, and each point is worth double. {N(c.UnchainedCooldown)}s cooldown.", 
				"rampage" => "Each kill during Frenzy adds " + N(c.RampageSecondsPerKill) + "s to it, up to " + N(c.RampageMaxExtraSeconds) + "s extra per Frenzy. Best in a pack.", 
				"unbroken" => "During Frenzy and Unchained you cannot be staggered and you take " + Pc(c.UnbrokenDamageReduction) + "% less physical damage. That counts toward the total damage reduction cap (" + Pc(c.ClassDamageReductionCap) + "% max).", 
				"sundering" => $"Hits from Whirlwind, Crushing Blow and Titan Slam mark enemies with Rend, up to {c.SunderingMaxStacks} stacks. Each stack makes every hit you land on them {Pc(c.SunderingDamagePerStack)}% stronger, for {N(c.SunderingSeconds)}s after the last stack. Best against a boss.", 
				"bloodtithe" => "Fury you spend on abilities heals you for " + Pc(c.BloodtitheHealPerPoint) + "% of your max health per point.", 
				"momentum" => "Every ability you use takes " + N(c.MomentumCooldownCut) + "s off the cooldowns of your other abilities.", 
				"overcharge" => $"Your Fury cap is {c.OverchargeCapBonus} higher, but Fury starts draining {N(0f - c.OverchargeDrainDelay)}s sooner.", 
				"bloodbath" => $"A strike around you: x{N(c.BloodbathStrikeDamage)} weapon damage within {N(c.BloodbathStrikeRadius)} m, up to {c.BloodbathStrikeMaxTargets} targets. It heals you for {Pc(c.BloodbathHealFraction)}% of your max health and sends you into a rage for {N(c.BloodbathEnrageSeconds)}s: you grow larger and do {Pc(c.BloodbathEnrageDamage)}% more damage. {c.BloodbathCooldownSeconds}s cooldown.", 
				"last_stand" => $"The lower your health, the harder you hit: up to {Pc(c.LastStandMaxDamageBonus)}% more damage as it falls. Activate to take no damage of any kind for {N(c.LastStandImmunitySeconds)}s. {c.LastStandCooldownSeconds}s cooldown.", 
				_ => "", 
			};
		}

		public static string MasteryEffect(string id, int rank, BerserkerConfig c)
		{
			return id switch
			{
				"second_wind" => "+" + Pc(MasteryRamp.Units(rank) * c.SecondWindRegenPerRank) + "% stamina regeneration", 
				"bloodlust" => "Fury starts draining " + N(MasteryRamp.Units(rank) * c.BloodlustDrainDelayPerRank) + "s later", 
				"thick_hide" => Pc(MasteryRamp.Units(rank) * c.ThickHideReductionPerRank) + "% less physical damage taken (counts toward the class cap)", 
				"brutality" => "+" + N((float)rank * c.BrutalityFlatPerRank) + " flat damage on every hit, added before the Fury bonus", 
				_ => "", 
			};
		}

		public static string MasteryName(string id)
		{
			return id switch
			{
				"second_wind" => "Second Wind", 
				"bloodlust" => "Bloodlust", 
				"thick_hide" => "Thick Hide", 
				"brutality" => "Brutality", 
				_ => id.Replace('_', ' '), 
			};
		}

		public static string MasteryTooltip(string id, int rank, int classRank, int pointsAvailable, BerserkerConfig c)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(MasteryName(id)).Append("  ").Append(rank)
				.Append('/')
				.Append(7)
				.Append('\n');
			stringBuilder.Append("Now: ").Append((rank == 0) ? "none" : MasteryEffect(id, rank, c)).Append('\n');
			if (rank >= 7)
			{
				stringBuilder.Append("Maxed.");
				return stringBuilder.ToString();
			}
			int num = rank + 1;
			stringBuilder.Append("Next: ").Append(MasteryEffect(id, num, c)).Append('\n');
			stringBuilder.Append("Cost: 1 mastery point");
			int num2 = ClassDefinition.RequiredClassRank(BerserkerCatalog.Definition.UpgradeIndex(id), num);
			if (num2 > classRank)
			{
				stringBuilder.Append("\nLocked: needs class rank ").Append(num2);
			}
			else if (pointsAvailable < 1)
			{
				stringBuilder.Append("\nLocked: no mastery point available");
			}
			return stringBuilder.ToString();
		}

		public static IEnumerable<string> AllOptions()
		{
			foreach (TalentTier tier in BerserkerCatalog.Tiers)
			{
				foreach (string option in tier.Options)
				{
					yield return option;
				}
			}
		}
	}
	public sealed class BoneShield
	{
		private float _pool;

		private float _max;

		private double _deadline = double.PositiveInfinity;

		public float Pool => _pool;

		public float Max => _max;

		public bool Active(double now)
		{
			Expire(now);
			return _pool > 0f;
		}

		public bool Lingering(double now)
		{
			if (now < _deadline)
			{
				return !double.IsPositiveInfinity(_deadline);
			}
			return false;
		}

		public float Fill(float amount, float max, double now, float multiplier = 1f)
		{
			Expire(now);
			if (amount <= 0f || max <= 0f || !(multiplier > 0f))
			{
				return 0f;
			}
			_max = max;
			_pool = Math.Min(_pool, max);
			float num = Math.Min(amount * multiplier, max - _pool);
			_pool += num;
			return num;
		}

		public float Absorb(float damage, double now)
		{
			Expire(now);
			if (damage <= 0f || _pool <= 0f)
			{
				return Math.Max(0f, damage);
			}
			float num = Math.Min(_pool, damage);
			_pool -= num;
			return damage - num;
		}

		public void StartLinger(double now, double linger)
		{
			_deadline = now + Math.Max(0.0, linger);
		}

		public void Hold()
		{
			_deadline = double.PositiveInfinity;
		}

		public void Clear()
		{
			_pool = 0f;
			_max = 0f;
			_deadline = double.PositiveInfinity;
		}

		private void Expire(double now)
		{
			if (now >= _deadline)
			{
				Clear();
			}
		}
	}
	public sealed class TalentTier
	{
		public int Level { get; }

		public IReadOnlyList<string> Options { get; }

		public int RequiredRank { get; }

		public TalentTier(int level, int requiredRank, params string[] options)
		{
			Level = level;
			RequiredRank = requiredRank;
			Options = options;
		}
	}
	public static class MageCatalog
	{
		public static readonly IReadOnlyList<TalentTier> Tiers = new TalentTier[8]
		{
			new TalentTier(1, 0, "caster", "conjurer"),
			new TalentTier(5, 0, "fire", "frost", "lightning"),
			new TalentTier(10, 0, "elemental_burst", "elemental_ward", "entangle", "pack_ward"),
			new TalentTier(15, 0, "potency", "flow", "pack_echo", "bulwark"),
			new TalentTier(20, 0, "prismatic_lance", "prismatic_convergence", "spirit_volley"),
			new TalentTier(30, 0, "swift_bolt", "splash", "siphon", "rally"),
			new TalentTier(40, 0, "elemental_zones", "proliferation", "greater_companion", "shared_bond"),
			new TalentTier(50, 0, "cataclysm", "avatar")
		};

		public static readonly IReadOnlyList<string> Upgrades = new string[4] { "eitr_flow", "elemental_stride", "deep_reserve", "attunement" };

		public static readonly HashSet<string> BuiltTier40 = new HashSet<string> { "greater_companion", "shared_bond", "elemental_zones", "proliferation" };

		public const string Id = "mage";

		public const string CataclysmId = "cataclysm";

		public const string AvatarId = "avatar";

		public static readonly ClassDefinition Definition = new ClassDefinition("mage", "Mage", Tiers, Upgrades, null, OptionAvailable, OptionRetained);

		public static int RequiredClassRank(int upgradeRank)
		{
			return ClassDefinition.RequiredClassRank(0, upgradeRank);
		}

		public static bool OptionAvailable(IReadOnlyDictionary<int, string> choices, int tierLevel, string option)
		{
			if (tierLevel != 10 && tierLevel != 15 && tierLevel != 20 && tierLevel != 30 && tierLevel != 40)
			{
				return true;
			}
			choices.TryGetValue(1, out string value);
			switch (tierLevel)
			{
			case 40:
				if (!BuiltTier40.Contains(option))
				{
					return false;
				}
				if (value == "caster")
				{
					if (!(option == "elemental_zones"))
					{
						return option == "proliferation";
					}
					return true;
				}
				if (value == "conjurer")
				{
					if (!(option == "greater_companion"))
					{
						return option == "shared_bond";
					}
					return true;
				}
				return false;
			case 30:
				if (value == "caster")
				{
					if (!(option == "swift_bolt"))
					{
						return option == "splash";
					}
					return true;
				}
				if (value == "conjurer")
				{
					if (!(option == "siphon"))
					{
						return option == "rally";
					}
					return true;
				}
				return false;
			case 10:
				if (value == "caster")
				{
					if (!(option == "elemental_burst"))
					{
						return option == "elemental_ward";
					}
					return true;
				}
				if (value == "conjurer")
				{
					if (!(option == "entangle"))
					{
						return option == "pack_ward";
					}
					return true;
				}
				return false;
			case 20:
				if (value == "caster")
				{
					if (!(option == "prismatic_lance"))
					{
						return option == "prismatic_convergence";
					}
					return true;
				}
				if (value == "conjurer")
				{
					if (!(option == "prismatic_lance"))
					{
						return option == "spirit_volley";
					}
					return true;
				}
				return false;
			default:
				if (value == "caster")
				{
					if (!(option == "potency"))
					{
						return option == "flow";
					}
					return true;
				}
				if (value == "conjurer")
				{
					if (!(option == "pack_echo"))
					{
						return option == "bulwark";
					}
					return true;
				}
				return false;
			}
		}

		public static bool OptionRetained(IReadOnlyDictionary<int, string> choices, int tierLevel, string option)
		{
			if (!OptionAvailable(choices, tierLevel, option) && tierLevel != 10)
			{
				return tierLevel == 20;
			}
			return true;
		}

		public static TalentTier? TierAt(int level)
		{
			return Tiers.FirstOrDefault((TalentTier t) => t.Level == level);
		}
	}
	public static class Derived
	{
		public static float MaxEitr(int level, int deepReserveRanks)
		{
			return 40f + 2f * (float)(level - 1) + 2f * MasteryRamp.Units(deepReserveRanks);
		}

		public static float EitrRegenBonus(int eitrFlowRanks)
		{
			return 0.1f * MasteryRamp.Units(eitrFlowRanks);
		}

		public static float PetSpeedBonus(int strideRanks)
		{
			return 0.05f * MasteryRamp.Units(strideRanks);
		}
	}
	public sealed class CharacterState
	{
		private readonly ProgressionConfig _cfg;

		private readonly ClassRegistry _registry;

		private readonly Dictionary<string, ClassState> _classes = new Dictionary<string, ClassState>();

		private static readonly ClassState NoClassState = new ClassState();

		internal const int MaxCapDropLevels = 5;

		public string? ActiveClassId { get; private set; }

		public int ResetCount { get; private set; }

		public long UltimateCooldownEndUnix { get; private set; }

		public ClassState Mage => EnsureClass("mage");

		public IEnumerable<string> StartedClasses => _classes.Keys.OrderBy<string, string>((string k) => k, StringComparer.Ordinal);

		public bool HasClass => ActiveClassId != null;

		private ClassState Active
		{
			get
			{
				if (ActiveClassId == null)
				{
					return NoClassState;
				}
				return _classes[ActiveClassId];
			}
		}

		private ClassDefinition ActiveDef
		{
			get
			{
				_registry.TryGet(ActiveClassId ?? "mage", out ClassDefinition def);
				return def;
			}
		}

		public ClassState? ActiveState
		{
			get
			{
				if (ActiveClassId == null)
				{
					return null;
				}
				return _classes[ActiveClassId];
			}
		}

		public ClassDefinition? ActiveDefinition
		{
			get
			{
				if (ActiveClassId == null || !_registry.TryGet(ActiveClassId, out ClassDefinition def))
				{
					return null;
				}
				return def;
			}
		}

		public IEnumerable<ClassDefinition> AvailableClasses => _registry.All;

		public string ActiveRankName
		{
			get
			{
				if (ActiveClassId != null)
				{
					return RankNamesOf(ActiveDef)[Active.Rank];
				}
				return "";
			}
		}

		public int Level => LevelFor(Active.ClassXp);

		public int Ceiling => _cfg.RankCeilings[Active.Rank];

		public bool AtCeiling
		{
			get
			{
				if (HasClass)
				{
					return Active.ClassXp >= Threshold(Ceiling);
				}
				return false;
			}
		}

		public bool IsUltimateAvailable
		{
			get
			{
				if (HasClass)
				{
					return Level >= 50;
				}
				return false;
			}
		}

		public bool IsHuntsEndAvailable
		{
			get
			{
				if (ActiveClassId == "ranger")
				{
					return IsUltimateAvailable;
				}
				return false;
			}
		}

		public string UltimatePick => ActiveChoice(50);

		public bool HasUltimatePick => UltimatePick.Length != 0;

		public bool UltimatePickPending
		{
			get
			{
				if (IsUltimateAvailable && ActiveDefinition?.TierAt(50) != null)
				{
					return !HasUltimatePick;
				}
				return false;
			}
		}

		public int MasteryPointLimit
		{
			get
			{
				if (!HasClass)
				{
					return 0;
				}
				ClassDefinition activeDef = ActiveDef;
				MasteryShape masteryShape = activeDef.MasteryShape;
				bool flag = activeDef.HasFourthUpgrade && Active.Rank >= masteryShape.FourthUpgradeClassRank;
				int? levelsPerRank = masteryShape.LevelsPerRank;
				if (levelsPerRank.HasValue)
				{
					int valueOrDefault = levelsPerRank.GetValueOrDefault();
					return Math.Min(masteryShape.RanksPerUpgrade, Ceiling / valueOrDefault) * (flag ? activeDef.Upgrades.Count : 3);
				}
				return Math.Min(3 * masteryShape.RanksPerUpgrade, 6 * (Active.Rank + 1)) + (flag ? masteryShape.RanksPerUpgrade : 0);
			}
		}

		public long MasteryAllowance => Enumerable.Range(0, MasteryPointLimit).Sum((Func<int, long>)((int n) => PointCost(n)));

		public bool MasteryComplete => Active.MasteryXp >= MasteryAllowance;

		public int PointsEarned
		{
			get
			{
				if (!HasClass)
				{
					return 0;
				}
				return Math.Min(PointsFor(ActiveDef, Active.MasteryXp), MasteryPointLimit);
			}
		}

		public int PointsAvailable => Math.Max(0, PointsEarned - Active.SpentTotal);

		public bool CapstoneLost
		{
			get
			{
				if (HasClass)
				{
					return Active.CapstoneLost;
				}
				return false;
			}
		}

		public int RestedPool { get; private set; }

		public long LogoutUnix { get; private set; }

		public int RestedCap => (int)Math.Min(2147483647.0, Math.Round((double)_cfg.RestedCapLevels * (double)_cfg.CostForLevel(Level)));

		public int NextResetPrice => _cfg.ResetPrices[Math.Min(ResetCount, _cfg.ResetPrices.Length - 1)];

		public (long Into, long Cost) MasteryPointProgress
		{
			get
			{
				long num = 0L;
				int i = 0;
				long masteryXp = Active.MasteryXp;
				int masteryPointLimit;
				for (masteryPointLimit = MasteryPointLimit; i < masteryPointLimit && num + PointCost(i) <= masteryXp; i++)
				{
					num += PointCost(i);
				}
				(long, int) tuple = ((i >= masteryPointLimit) ? (0L, 0) : (masteryXp - num, PointCost(i)));
				return (Into: tuple.Item1, Cost: tuple.Item2);
			}
		}

		public bool AtSliceTerminal
		{
			get
			{
				if (HasClass && Active.Rank >= _cfg.PromotionTrophies.Length)
				{
					return AtCeiling;
				}
				return false;
			}
		}

		public CharacterState(ProgressionConfig cfg, ClassRegistry? registry = null)
			: this(cfg, registry, "mage")
		{
		}

		private CharacterState(ProgressionConfig cfg, ClassRegistry? registry, string? activeId)
		{
			_cfg = cfg ?? throw new ArgumentNullException("cfg");
			_registry = registry ?? ClassRegistry.Default;
			if (activeId != null)
			{
				EnsureClass(activeId);
				ActiveClassId = activeId;
			}
		}

		public static CharacterState CreateNew(ProgressionConfig cfg, ClassRegistry? registry = null)
		{
			return new CharacterState(cfg, registry, null);
		}

		private ClassState EnsureClass(string id)
		{
			if (!_registry.TryGet(id, out ClassDefinition def))
			{
				throw new ArgumentException("Unknown class '" + id + "'.", "id");
			}
			if (!_classes.TryGetValue(id, out ClassState value))
			{
				value = new ClassState(def.Upgrades);
				_classes[id] = value;
			}
			return value;
		}

		public ClassState? GetClass(string id)
		{
			if (!_classes.TryGetValue(id, out ClassState value))
			{
				return null;
			}
			return value;
		}

		private IReadOnlyList<string> RankNamesOf(ClassDefinition d)
		{
			return d.RankNames ?? _cfg.RankNames;
		}

		public int LevelOf(string classId)
		{
			if (!_classes.TryGetValue(classId, out ClassState value))
			{
				return 1;
			}
			return LevelFor(value.ClassXp);
		}

		private long MasteryAllowanceAnyRank(ClassDefinition def)
		{
			long num = Enumerable.Range(0, def.MasteryPointCap).Sum((Func<int, long>)((int n) => _cfg.MasteryPointCost(def, n)));
			if (!def.MasteryShape.AcceptsLegacyPrices)
			{
				return num;
			}
			return Math.Max(num, ProgressionConfig.LegacyMasteryAllowance);
		}

		public string ActiveChoiceOf(string classId, int tierLevel)
		{
			if (!_classes.TryGetValue(classId, out ClassState value) || !value.Choices.TryGetValue(tierLevel, out string value2))
			{
				return "";
			}
			if (!_registry.TryGet(classId, out ClassDefinition def))
			{
				return value2;
			}
			TalentTier talentTier = def.TierAt(tierLevel);
			if (talentTier == null)
			{
				return "";
			}
			if (LevelFor(value.ClassXp) < talentTier.Level || value.Rank < talentTier.RequiredRank)
			{
				return "";
			}
			if (value.CapstoneLost && talentTier.Level == 20)
			{
				return "";
			}
			return value2;
		}

		public string ActiveChoice(int tierLevel)
		{
			if (ActiveClassId != null)
			{
				return ActiveChoiceOf(ActiveClassId, tierLevel);
			}
			return "";
		}

		public int PointCost(int n)
		{
			return _cfg.MasteryPointCost(ActiveDefinition ?? MageCatalog.Definition, n);
		}

		private int PointsFor(ClassDefinition def, long masteryXp)
		{
			long num = 0L;
			int i;
			for (i = 0; i < def.MasteryPointCap && num + _cfg.MasteryPointCost(def, i) <= masteryXp; i++)
			{
				num += _cfg.MasteryPointCost(def, i);
			}
			return i;
		}

		internal int PointsForUnramped(long masteryXp)
		{
			long num = 0L;
			int i;
			for (i = 0; i < 28 && num + _cfg.MasteryPointBaseCost(i) <= masteryXp; i++)
			{
				num += _cfg.MasteryPointBaseCost(i);
			}
			return i;
		}

		public int LevelFor(int xp)
		{
			int i = 1;
			for (int num = xp; i < 80 && num >= _cfg.CostForLevel(i); i++)
			{
				num -= _cfg.CostForLevel(i);
			}
			return i;
		}

		public int Threshold(int level)
		{
			int num = 0;
			for (int i = 1; i < level; i++)
			{
				num += _cfg.CostForLevel(i);
			}
			return num;
		}

		public SwitchResult SwitchClass(string classId, bool resting)
		{
			string activeClassId = ActiveClassId;
			if (!_registry.TryGet(classId ?? "", out ClassDefinition _))
			{
				return new SwitchResult(ok: false, Failure.UnknownClass, activeClassId, classId);
			}
			if (!resting)
			{
				return new SwitchResult(ok: false, Failure.NotResting, activeClassId, classId);
			}
			if (classId == activeClassId)
			{
				return new SwitchResult(ok: false, Failure.AlreadyActive, activeClassId, classId);
			}
			EnsureClass(classId);
			ActiveClassId = classId;
			RestedPool = Math.Min(RestedPool, RestedCap);
			return new SwitchResult(ok: true, Failure.None, activeClassId, classId);
		}

		public long UltimateCooldownSecondsRemaining(DateTimeOffset now)
		{
			return Math.Max(0L, UltimateCooldownEndUnix - Math.Max(0L, now.ToUnixTimeSeconds()));
		}

		public void ResetUltimateCooldown()
		{
			UltimateCooldownEndUnix = 0L;
		}

		public bool TryStartUltimateCooldown(int seconds, DateTimeOffset now)
		{
			if (UltimateCooldownSecondsRemaining(now) > 0)
			{
				return false;
			}
			UltimateCooldownEndUnix = ((seconds > 0) ? (Math.Max(0L, now.ToUnixTimeSeconds()) + seconds) : 0);
			return true;
		}

		public RangerResult TryHuntsEnd(RangerConfig config, bool validTarget, float eitr, float maxEitr, int arrows, DateTimeOffset now)
		{
			return TryUltimate(config, validTarget, eitr, maxEitr, arrows, now);
		}

		public RangerResult TryUltimate(RangerConfig config, bool validTarget, float eitr, float maxEitr, int arrows, DateTimeOffset now)
		{
			if (!HasClass)
			{
				return RangerResult.Fail(Failure.NoClass, "hunts_end");
			}
			if (ActiveClassId != "ranger")
			{
				return RangerResult.Fail(Failure.WrongClass, "hunts_end");
			}
			if (!IsUltimateAvailable || ActiveDefinition?.TierAt(50) == null)
			{
				return RangerResult.Fail(Failure.AbilityLocked, "hunts_end");
			}
			string ultimatePick = UltimatePick;
			if (ultimatePick.Length == 0)
			{
				return RangerResult.Fail(Failure.NoUltimatePick, ultimatePick);
			}
			if (!validTarget)
			{
				return RangerResult.Fail(Failure.NoTarget, ultimatePick);
			}
			if (UltimateCooldownSecondsRemaining(now) > 0)
			{
				return RangerResult.Fail(Failure.UltimateOnCooldown, ultimatePick);
			}
			RangerMath rangerMath = new RangerMath(config);
			float num;
			int seconds;
			int val;
			if (!(ultimatePick == "pack_attack"))
			{
				if (!(ultimatePick == "lone_kill"))
				{
					return RangerResult.Fail(Failure.AbilityLocked, ultimatePick);
				}
				val = config.LoneKillArrowCost;
				num = rangerMath.LoneKillEitrCost(maxEitr);
				seconds = config.LoneKillCooldownSeconds;
			}
			else
			{
				val = config.HuntsEndArrowCost;
				num = rangerMath.HuntsEndEitrCost(maxEitr);
				seconds = config.PackAttackCooldownSeconds;
			}
			val = Math.Max(0, val);
			if (!(eitr >= num))
			{
				return RangerResult.Fail(Failure.NotEnoughEitr, ultimatePick);
			}
			if (arrows < val)
			{
				return RangerResult.Fail(Failure.NotEnoughArrows, ultimatePick);
			}
			if (!TryStartUltimateCooldown(seconds, now))
			{
				return RangerResult.Fail(Failure.UltimateOnCooldown, ultimatePick);
			}
			return new RangerResult(ok: true, Failure.None, ultimatePick, num, val);
		}

		public UltimateResult TryBerserkerUltimate(BerserkerConfig config, DateTimeOffset now)
		{
			if (!HasClass)
			{
				return UltimateResult.Fail(Failure.NoClass, "");
			}
			if (ActiveClassId != "berserker")
			{
				return UltimateResult.Fail(Failure.WrongClass, "");
			}
			if (!IsUltimateAvailable || ActiveDefinition?.TierAt(50) == null)
			{
				return UltimateResult.Fail(Failure.AbilityLocked, "");
			}
			string ultimatePick = UltimatePick;
			if (ultimatePick.Length == 0)
			{
				return UltimateResult.Fail(Failure.NoUltimatePick, "");
			}
			if (UltimateCooldownSecondsRemaining(now) > 0)
			{
				return UltimateResult.Fail(Failure.UltimateOnCooldown, ultimatePick);
			}
			int num = ((ultimatePick == "bloodbath") ? config.BloodbathCooldownSeconds : ((ultimatePick == "last_stand") ? config.LastStandCooldownSeconds : (-1)));
			if (num < 0)
			{
				return UltimateResult.Fail(Failure.AbilityLocked, ultimatePick);
			}
			if (!TryStartUltimateCooldown(num, now))
			{
				return UltimateResult.Fail(Failure.UltimateOnCooldown, ultimatePick);
			}
			return new UltimateResult(ok: true, Failure.None, ultimatePick, num);
		}

		public UltimateResult TryWarriorUltimate(WarriorConfig config, DateTimeOffset now)
		{
			if (!HasClass)
			{
				return UltimateResult.Fail(Failure.NoClass, "");
			}
			if (ActiveClassId != "warrior")
			{
				return UltimateResult.Fail(Failure.WrongClass, "");
			}
			if (!IsUltimateAvailable || ActiveDefinition?.TierAt(50) == null)
			{
				return UltimateResult.Fail(Failure.AbilityLocked, "");
			}
			string ultimatePick = UltimatePick;
			if (ultimatePick.Length == 0)
			{
				return UltimateResult.Fail(Failure.NoUltimatePick, "");
			}
			if (UltimateCooldownSecondsRemaining(now) > 0)
			{
				return UltimateResult.Fail(Failure.UltimateOnCooldown, ultimatePick);
			}
			int num = ((ultimatePick == "shield_wall") ? config.ShieldWallCooldownSeconds : ((ultimatePick == "warlord") ? config.WarlordCooldownSeconds : (-1)));
			if (num < 0)
			{
				return UltimateResult.Fail(Failure.AbilityLocked, ultimatePick);
			}
			if (!TryStartUltimateCooldown(num, now))
			{
				return UltimateResult.Fail(Failure.UltimateOnCooldown, ultimatePick);
			}
			return new UltimateResult(ok: true, Failure.None, ultimatePick, num);
		}

		public UltimateResult TryNecromancerUltimate(NecromancerConfig config, DateTimeOffset now)
		{
			if (!HasClass)
			{
				return UltimateResult.Fail(Failure.NoClass, "");
			}
			if (ActiveClassId != "necromancer")
			{
				return UltimateResult.Fail(Failure.WrongClass, "");
			}
			if (!IsUltimateAvailable || ActiveDefinition?.TierAt(50) == null)
			{
				return UltimateResult.Fail(Failure.AbilityLocked, "");
			}
			string ultimatePick = UltimatePick;
			if (ultimatePick.Length == 0)
			{
				return UltimateResult.Fail(Failure.NoUltimatePick, "");
			}
			if (UltimateCooldownSecondsRemaining(now) > 0)
			{
				return UltimateResult.Fail(Failure.UltimateOnCooldown, ultimatePick);
			}
			int num = ((ultimatePick == "lich_form") ? config.LichCooldownSeconds : ((ultimatePick == "final_oath") ? config.FinalOathCooldownSeconds : (-1)));
			if (num < 0)
			{
				return UltimateResult.Fail(Failure.AbilityLocked, ultimatePick);
			}
			if (!TryStartUltimateCooldown(num, now))
			{
				return UltimateResult.Fail(Failure.UltimateOnCooldown, ultimatePick);
			}
			return new UltimateResult(ok: true, Failure.None, ultimatePick, num);
		}

		public UltimateResult TryMageUltimate(MageConfig config, float eitr, float maxEitr, DateTimeOffset now)
		{
			if (!HasClass)
			{
				return UltimateResult.Fail(Failure.NoClass, "");
			}
			if (ActiveClassId != "mage")
			{
				return UltimateResult.Fail(Failure.WrongClass, "");
			}
			if (!IsUltimateAvailable || ActiveDefinition?.TierAt(50) == null)
			{
				return UltimateResult.Fail(Failure.AbilityLocked, "");
			}
			string ultimatePick = UltimatePick;
			if (ultimatePick.Length == 0)
			{
				return UltimateResult.Fail(Failure.NoUltimatePick, "");
			}
			if (UltimateCooldownSecondsRemaining(now) > 0)
			{
				return UltimateResult.Fail(Failure.UltimateOnCooldown, ultimatePick);
			}
			int num = ((ultimatePick == "cataclysm") ? config.CataclysmCooldownSeconds : ((ultimatePick == "avatar") ? config.AvatarCooldownSeconds : (-1)));
			if (num < 0)
			{
				return UltimateResult.Fail(Failure.AbilityLocked, ultimatePick);
			}
			float num2 = ((ultimatePick == "cataclysm") ? (Math.Max(0f, config.CataclysmEitrFraction) * Math.Max(0f, maxEitr)) : 0f);
			if (eitr < num2)
			{
				return UltimateResult.Fail(Failure.NotEnoughEitr, ultimatePick);
			}
			if (!TryStartUltimateCooldown(num, now))
			{
				return UltimateResult.Fail(Failure.UltimateOnCooldown, ultimatePick);
			}
			return new UltimateResult(ok: true, Failure.None, ultimatePick, num, num2);
		}

		public XpRouting GrantCombatXp(int amount)
		{
			if (amount < 0)
			{
				throw new ArgumentOutOfRangeException("amount");
			}
			if (!HasClass)
			{
				return new XpRouting(0, 0, amount, 0, levelGained: false);
			}
			ClassState active = Active;
			int level = Level;
			int pointsEarned = PointsEarned;
			int val = Math.Max(0, Threshold(Ceiling) - active.ClassXp);
			int num = Math.Min(amount, val);
			int num2 = amount - num;
			int num3 = (int)Math.Min(num2, active.MasteryDebt);
			active.MasteryDebt -= num3;
			if (active.MasteryDebt == 0L)
			{
				active.MasteryDebtDeaths = 0;
			}
			num2 -= num3;
			long val2 = Math.Max(0L, MasteryAllowance - active.MasteryXp);
			int num4 = (int)Math.Min(num2, val2);
			active.ClassXp += num;
			active.MasteryXp += num4;
			if (active.CapstoneLost && LevelFor(active.ClassXp) >= 20)
			{
				active.CapstoneLost = false;
			}
			return new XpRouting(num, num4, num2 - num4, PointsEarned - pointsEarned, Level > level, num3);
		}

		public void SetProgressForTesting(int level, long masteryXp)
		{
			if (HasClass)
			{
				Active.ClassXp = Threshold(Math.Max(1, Math.Min(level, Ceiling)));
				Active.MasteryXp = Math.Max(0L, Math.Min(masteryXp, MasteryAllowance));
			}
		}

		public KillXpResult GrantKillXp(int amount)
		{
			if (amount < 0)
			{
				throw new ArgumentOutOfRangeException("amount");
			}
			int num = 0;
			if (HasClass && _cfg.RestedEnabled && RestedPool > 0 && amount > 0)
			{
				int num2 = Math.Max(0, Threshold(Ceiling) - Active.ClassXp);
				double val = Math.Floor((double)amount * (Math.Max(1.0, _cfg.RestedMultiplier) - 1.0));
				num = (int)Math.Min(Math.Min(RestedPool, val), Math.Max(0, num2 - amount));
			}
			XpRouting routing = GrantCombatXp(amount + num);
			RestedPool -= num;
			return new KillXpResult(routing, num);
		}

		public void StampLogout(DateTimeOffset now)
		{
			LogoutUnix = Math.Max(0L, now.ToUnixTimeSeconds());
		}

		public int ApplyOfflineAccrual(DateTimeOffset now)
		{
			if (LogoutUnix <= 0)
			{
				return 0;
			}
			long num = now.ToUnixTimeSeconds() - LogoutUnix;
			LogoutUnix = 0L;
			if (!HasClass || !_cfg.RestedEnabled || num <= 0 || AtCeiling)
			{
				return 0;
			}
			double val = Math.Floor((double)num / 3600.0 * (double)_cfg.RestedAccrualPerHour * (double)_cfg.CostForLevel(Level));
			int restedCap = RestedCap;
			int restedPool = RestedPool;
			RestedPool = (int)Math.Max(restedPool, Math.Min(restedCap, (double)restedPool + Math.Min(val, restedCap)));
			return RestedPool - restedPool;
		}

		public CommandResult SelectTalent(int tierLevel, string option, bool resting)
		{
			return SelectTalent(tierLevel, option, resting, DateTimeOffset.UnixEpoch);
		}

		public CommandResult SelectTalent(int tierLevel, string option, bool resting, DateTimeOffset now)
		{
			if (!HasClass)
			{
				return CommandResult.Fail(Failure.NoClass);
			}
			TalentTier talentTier = ActiveDef.TierAt(tierLevel);
			if (talentTier == null || !talentTier.Options.Contains(option))
			{
				return CommandResult.Fail(Failure.UnknownOption);
			}
			if (!resting)
			{
				return CommandResult.Fail(Failure.NotResting);
			}
			if (Active.Rank < talentTier.RequiredRank || Level < talentTier.Level)
			{
				return CommandResult.Fail(Failure.LockedOption);
			}
			if (!ActiveDef.IsOptionAvailable(Active.Choices, tierLevel, option))
			{
				return CommandResult.Fail(Failure.LockedOption);
			}
			if (tierLevel == 50 && UltimateCooldownSecondsRemaining(now) > 0)
			{
				return CommandResult.Fail(Failure.UltimateOnCooldown);
			}
			Active.Choices[tierLevel] = option;
			foreach (TalentTier tier in ActiveDef.Tiers)
			{
				if (tier.Level > tierLevel && Active.Choices.TryGetValue(tier.Level, out string value) && !ActiveDef.IsOptionAvailable(Active.Choices, tier.Level, value))
				{
					Active.Choices.Remove(tier.Level);
				}
			}
			return CommandResult.Success();
		}

		public CommandResult PurchaseMastery(string upgradeId, bool resting)
		{
			if (!HasClass)
			{
				return CommandResult.Fail(Failure.NoClass);
			}
			if (!ActiveDef.Upgrades.Contains(upgradeId))
			{
				return CommandResult.Fail(Failure.UnknownOption);
			}
			if (!resting)
			{
				return CommandResult.Fail(Failure.NotResting);
			}
			int num = Active.Spent[upgradeId] + 1;
			if (num > ActiveDef.MasteryRanksPerUpgrade)
			{
				return CommandResult.Fail(Failure.MaxedUpgrade);
			}
			if (!CanBuyMasteryRank(ActiveDef, ActiveDef.UpgradeIndex(upgradeId), num, Active.Rank, Level))
			{
				return CommandResult.Fail(Failure.RankGate);
			}
			if (PointsAvailable < 1)
			{
				return CommandResult.Fail(Failure.NoPointAvailable);
			}
			Active.Spent[upgradeId] = num;
			return CommandResult.Success();
		}

		private static bool CanBuyMasteryRank(ClassDefinition def, int upgradeIndex, int upgradeRank, int classRank, int level)
		{
			MasteryShape masteryShape = def.MasteryShape;
			if (upgradeIndex >= 3 && classRank < masteryShape.FourthUpgradeClassRank)
			{
				return false;
			}
			int? levelsPerRank = masteryShape.LevelsPerRank;
			if (levelsPerRank.HasValue)
			{
				int valueOrDefault = levelsPerRank.GetValueOrDefault();
				return level >= upgradeRank * valueOrDefault;
			}
			if (upgradeIndex < 3)
			{
				return classRank >= ClassDefinition.RequiredClassRank(upgradeIndex, upgradeRank);
			}
			return true;
		}

		public CommandResult ResetMastery(bool resting, IInventory inventory)
		{
			if (!HasClass)
			{
				return CommandResult.Fail(Failure.NoClass);
			}
			if (!resting)
			{
				return CommandResult.Fail(Failure.NotResting);
			}
			if (Active.SpentTotal == 0)
			{
				return CommandResult.Fail(Failure.NothingToReset);
			}
			int nextResetPrice = NextResetPrice;
			if (nextResetPrice > 0)
			{
				if (inventory.Count(_cfg.CoinItem) < nextResetPrice)
				{
					return CommandResult.Fail(Failure.InsufficientCoins);
				}
				if (!inventory.Remove(_cfg.CoinItem, nextResetPrice))
				{
					return CommandResult.Fail(Failure.InsufficientCoins);
				}
			}
			foreach (string item in Active.Spent.Keys.ToList())
			{
				Active.Spent[item] = 0;
			}
			ResetCount++;
			return CommandResult.Success();
		}

		public Failure PromotionBlocker(IInventory inventory, bool resting = true)
		{
			if (!HasClass)
			{
				return Failure.NoClass;
			}
			if (!resting)
			{
				return Failure.NotResting;
			}
			if (Active.Rank >= _cfg.PromotionTrophies.Length)
			{
				return Failure.AlreadyMaxRank;
			}
			if (!AtCeiling)
			{
				return Failure.NotAtCeiling;
			}
			if (inventory.Count(_cfg.PromotionTrophies[Active.Rank]) < 1)
			{
				return Failure.MissingTrophy;
			}
			return Failure.None;
		}

		public PromotionPreview? PreviewPromotion(IInventory inventory, bool resting = true)
		{
			if (!HasClass || Active.Rank >= _cfg.PromotionTrophies.Length)
			{
				return null;
			}
			int rank = Active.Rank;
			int to = rank + 1;
			int ceiling = Ceiling;
			ClassDefinition activeDef = ActiveDef;
			IReadOnlyList<string> readOnlyList = RankNamesOf(activeDef);
			TalentTier talentTier = (from t in activeDef.Tiers
				where t.RequiredRank == to
				orderby t.Level
				select t).FirstOrDefault();
			return new PromotionPreview(_cfg.PromotionTrophies[rank], inventory.Count(_cfg.PromotionTrophies[rank]), rank, to, readOnlyList[rank], readOnlyList[to], ceiling, _cfg.RankCeilings[to], talentTier?.Level, PromotionBlocker(inventory, resting));
		}

		public CommandResult Promote(IInventory inventory, bool resting = true)
		{
			Failure failure = PromotionBlocker(inventory, resting);
			if (failure != Failure.None)
			{
				return CommandResult.Fail(failure);
			}
			if (!inventory.Remove(_cfg.PromotionTrophies[Active.Rank], 1))
			{
				return CommandResult.Fail(Failure.MissingTrophy);
			}
			Active.Rank++;
			return CommandResult.Success();
		}

		public int ApplyDeathPenalty(float fraction = 0.5f)
		{
			if (fraction < 0f || fraction > 1f)
			{
				throw new ArgumentOutOfRangeException("fraction");
			}
			if (!HasClass)
			{
				return 0;
			}
			int level = Level;
			if (level == _cfg.RankCeilings[_cfg.RankCeilings.Length - 1])
			{
				AddMasteryDebt();
				return 0;
			}
			int val = Threshold(Math.Max(1, level - 1));
			int num = (int)Math.Ceiling((double)_cfg.CostForLevel(level) * (double)fraction - 1E-09);
			int num2 = Math.Max(val, Active.ClassXp - num);
			int result = Active.ClassXp - num2;
			Active.ClassXp = num2;
			return result;
		}

		private void AddMasteryDebt()
		{
			ClassState active = Active;
			int n = Math.Min(PointsEarned, MasteryPointLimit - 1);
			decimal num = 1m;
			for (int i = 0; i < active.MasteryDebtDeaths; i++)
			{
				if (!(num < 2m))
				{
					break;
				}
				num = Math.Min(2m, num * 1.1m);
			}
			long num2 = (long)Math.Ceiling((decimal)PointCost(n) * 0.5m * num);
			if (num2 > 0)
			{
				active.MasteryDebt += Math.Min(num2, long.MaxValue - active.MasteryDebt);
				if (active.MasteryDebtDeaths < int.MaxValue)
				{
					active.MasteryDebtDeaths++;
				}
			}
		}

		public string Encode()
		{
			bool flag = _classes.Values.Any((ClassState c) => c.MasteryDebt > 0);
			bool anyLost = _classes.Values.Any((ClassState c) => c.CapstoneLost);
			bool flag2 = UltimateCooldownEndUnix != 0;
			bool writeDebtFields = flag || flag2;
			if (ActiveClassId == "mage" && _classes.Count == 1 && !anyLost && !writeDebtFields)
			{
				ClassState m = _classes["mage"];
				string text = string.Join(",", MageCatalog.Upgrades.Select((string u) => m.Spent[u]));
				string text2 = ChoiceList(MageCatalog.Definition, m);
				return $"rt2|{ResetCount}|{m.ClassXp}|{m.Rank}|{m.MasteryXp}|{text}|{text2}|{RestedPool}|{LogoutUnix}";
			}
			IEnumerable<string> values = _classes.OrderBy<KeyValuePair<string, ClassState>, string>((KeyValuePair<string, ClassState> kv) => kv.Key, StringComparer.Ordinal).Select(delegate(KeyValuePair<string, ClassState> kv)
			{
				_registry.TryGet(kv.Key, out ClassDefinition def);
				ClassState c = kv.Value;
				string text5 = string.Join(",", def.Upgrades.Select((string u) => c.Spent[u]));
				string text6 = ChoiceList(def, c);
				string text7 = $"{kv.Key}:{c.ClassXp}:{c.Rank}:{c.MasteryXp}:{text5}:{text6}";
				if (anyLost || writeDebtFields)
				{
					text7 += (c.CapstoneLost ? ":L" : ":");
				}
				if (writeDebtFields)
				{
					text7 += $":{c.MasteryDebt}:{c.MasteryDebtDeaths}";
				}
				return text7;
			});
			string text3 = (flag2 ? "rt6" : (flag ? "rt5" : (anyLost ? "rt4" : "rt3")));
			string text4 = string.Format("{0}|{1}|{2}|{3}|{4}", text3, ResetCount, RestedPool, LogoutUnix, ActiveClassId ?? "");
			if (flag2)
			{
				text4 += $"|{UltimateCooldownEndUnix}";
			}
			return text4 + "|" + string.Join(";", values);
		}

		private static string ChoiceList(ClassDefinition def, ClassState c)
		{
			string value;
			List<string> list = def.Tiers.Select((TalentTier t) => (!c.Choices.TryGetValue(t.Level, out value)) ? "" : value).ToList();
			while (list.Count > 5 && list[list.Count - 1] == "")
			{
				list.RemoveAt(list.Count - 1);
			}
			return string.Join(",", list);
		}

		public static CharacterState Decode(string text, ProgressionConfig cfg, ClassRegistry? registry = null)
		{
			string[] array = text.Split('|');
			if ((array.Length == 6 && (array[0] == "rt3" || array[0] == "rt4" || array[0] == "rt5")) || (array.Length == 7 && array[0] == "rt6"))
			{
				return DecodeClassRecords(array, cfg, registry);
			}
			int num;
			if (array.Length == 9)
			{
				num = ((array[0] == "rt2") ? 1 : 0);
				if (num != 0)
				{
					goto IL_0095;
				}
			}
			else
			{
				num = 0;
			}
			if (array.Length != 7 || !(array[0] == "rt1"))
			{
				throw new FormatException("Unsupported save version.");
			}
			goto IL_0095;
			IL_0095:
			CharacterState characterState = new CharacterState(cfg, registry);
			if (!int.TryParse(array[1], out var result) || result < 0)
			{
				throw new FormatException("Bad reset count.");
			}
			characterState.ResetCount = result;
			characterState.LoadClassRecord("mage", array[2], array[3], array[4], array[5], array[6]);
			if (num != 0)
			{
				characterState.LoadRested(array[7], array[8]);
			}
			return characterState;
		}

		private static CharacterState DecodeClassRecords(string[] p, ProgressionConfig cfg, ClassRegistry? registry)
		{
			bool flag = p[0] == "rt6";
			bool flag2 = flag || p[0] == "rt5";
			bool flag3 = flag2 || p[0] == "rt4";
			int num = (flag2 ? 9 : (flag3 ? 7 : 6));
			CharacterState characterState = CreateNew(cfg, registry);
			if (!int.TryParse(p[1], out var result) || result < 0)
			{
				throw new FormatException("Bad reset count.");
			}
			characterState.ResetCount = result;
			if (flag)
			{
				if (!long.TryParse(p[5], out var result2) || result2 < 0)
				{
					throw new FormatException("Bad ultimate cooldown end.");
				}
				characterState.UltimateCooldownEndUnix = result2;
			}
			string text = p[flag ? 6 : 5];
			HashSet<string> hashSet = new HashSet<string>();
			if (text.Length > 0)
			{
				string[] array = text.Split(';');
				for (int i = 0; i < array.Length; i++)
				{
					string[] array2 = array[i].Split(':');
					if (array2.Length != num)
					{
						throw new FormatException("Bad class record.");
					}
					if (flag3 && array2[6] != "" && array2[6] != "L")
					{
						throw new FormatException("Bad class flag.");
					}
					if (!hashSet.Add(array2[0]))
					{
						throw new FormatException("Duplicate class.");
					}
					if (!characterState._registry.TryGet(array2[0], out ClassDefinition _))
					{
						throw new FormatException("Unknown class.");
					}
					characterState.LoadClassRecord(array2[0], array2[1], array2[2], array2[3], array2[4], array2[5], flag3 && array2[6] == "L");
					if (flag2)
					{
						if (!long.TryParse(array2[7], out var result3) || result3 < 0)
						{
							throw new FormatException("Bad mastery debt.");
						}
						if (!int.TryParse(array2[8], out var result4) || result4 < 0 || result3 == 0 != (result4 == 0))
						{
							throw new FormatException("Bad mastery debt death count.");
						}
						ClassState classState = characterState._classes[array2[0]];
						classState.MasteryDebt = result3;
						classState.MasteryDebtDeaths = result4;
					}
				}
			}
			if (p[4].Length > 0)
			{
				if (!characterState._classes.ContainsKey(p[4]))
				{
					throw new FormatException("Active class has no record.");
				}
				characterState.ActiveClassId = p[4];
			}
			characterState.LoadRested(p[2], p[3]);
			return characterState;
		}

		private void LoadClassRecord(string id, string xpText, string rankText, string masteryText, string spentText, string choicesText, bool lost = false)
		{
			if (!_registry.TryGet(id, out ClassDefinition def))
			{
				throw new FormatException("Unknown class.");
			}
			ClassDefinition classDefinition = def;
			ClassState classState = EnsureClass(id);
			if (!int.TryParse(xpText, out var result) || result < 0)
			{
				throw new FormatException("Bad class XP.");
			}
			if (!int.TryParse(rankText, out var result2) || result2 < 0 || result2 >= _cfg.RankCeilings.Length)
			{
				throw new FormatException("Bad rank.");
			}
			if (!long.TryParse(masteryText, out var result3) || result3 < 0)
			{
				throw new FormatException("Bad mastery XP.");
			}
			classState.ClassXp = result;
			classState.Rank = result2;
			classState.MasteryXp = result3;
			classState.CapstoneLost = lost;
			if (result > Threshold(_cfg.RankCeilings[result2]))
			{
				throw new FormatException("XP above rank ceiling.");
			}
			TalentTier capstone = classDefinition.Capstone;
			if (lost)
			{
				if (result2 < capstone.RequiredRank)
				{
					throw new FormatException("Capstone marker without the capstone rank.");
				}
				if (result >= Threshold(capstone.Level))
				{
					throw new FormatException("Capstone marker at the cap.");
				}
				if (result < Threshold(capstone.Level - 5))
				{
					throw new FormatException("Capstone marker too far below the cap.");
				}
			}
			else if (result2 > 0 && result < Threshold(Math.Max(1, _cfg.RankCeilings[result2 - 1] - 1)))
			{
				throw new FormatException("Rank without the level it requires.");
			}
			if (result3 > MasteryAllowanceAnyRank(classDefinition))
			{
				throw new FormatException("Mastery above allowance.");
			}
			int num = LevelFor(result);
			string[] array = spentText.Split(',');
			if (array.Length != classDefinition.Upgrades.Count && array.Length != 3)
			{
				throw new FormatException("Bad spent list.");
			}
			for (int i = 0; i < array.Length; i++)
			{
				if (!int.TryParse(array[i], out var result4) || result4 < 0 || result4 > classDefinition.MasteryRanksPerUpgrade)
				{
					throw new FormatException("Bad spent value.");
				}
				if (result4 > 0 && !CanBuyMasteryRank(classDefinition, i, result4, result2, _cfg.RankCeilings[result2]))
				{
					throw new FormatException("Rank gate violated.");
				}
				classState.Spent[classDefinition.Upgrades[i]] = result4;
			}
			int num2 = PointsFor(classDefinition, classState.MasteryXp);
			if (classDefinition.MasteryShape.AcceptsLegacyPrices)
			{
				num2 = Math.Max(num2, PointsForUnramped(classState.MasteryXp));
			}
			if (classState.SpentTotal > num2)
			{
				throw new FormatException("Spent more points than earned.");
			}
			string[] array2 = choicesText.Split(',');
			if (array2.Length < 5 || array2.Length > classDefinition.Tiers.Count)
			{
				throw new FormatException("Bad choices.");
			}
			for (int j = 0; j < array2.Length; j++)
			{
				if (!(array2[j] == ""))
				{
					TalentTier talentTier = classDefinition.Tiers[j];
					bool flag = classDefinition.Id == "necromancer" && j == 5 && array2.Length == 6;
					if (flag)
					{
						string text = array2[j];
						bool flag2 = ((text == "lich_form" || text == "final_oath") ? true : false);
						flag = flag2;
					}
					if (flag)
					{
						talentTier = classDefinition.TierAt(50);
					}
					if (!talentTier.Options.Contains(array2[j]) || result2 < talentTier.RequiredRank)
					{
						throw new FormatException("Invalid choice.");
					}
					if (num < talentTier.Level - 1 && (!lost || talentTier != capstone))
					{
						throw new FormatException("Choice above the class level.");
					}
					classState.Choices[talentTier.Level] = array2[j];
				}
			}
			foreach (TalentTier tier in classDefinition.Tiers)
			{
				if (classState.Choices.TryGetValue(tier.Level, out string value) && !classDefinition.IsOptionRetained(classState.Choices, tier.Level, value))
				{
					classState.Choices.Remove(tier.Level);
				}
			}
		}

		private void LoadRested(string poolText, string stampText)
		{
			if (!int.TryParse(poolText, out var result) || result < 0)
			{
				throw new FormatException("Bad rested pool.");
			}
			if (!long.TryParse(stampText, out var result2) || result2 < 0)
			{
				throw new FormatException("Bad logout time.");
			}
			RestedPool = Math.Min(result, RestedCap);
			LogoutUnix = result2;
		}
	}
	public readonly struct ChillResult
	{
		public bool Counted { get; }

		public float Added { get; }

		public float Meter { get; }

		public bool Froze { get; }

		public double FreezeSeconds { get; }

		public bool HighRoll { get; }

		public ChillResult(bool counted, float added, float meter, bool froze, double freezeSeconds, bool highRoll)
		{
			Counted = counted;
			Added = added;
			Meter = meter;
			Froze = froze;
			FreezeSeconds = freezeSeconds;
			HighRoll = highRoll;
		}
	}
	public sealed class ChillTracker
	{
		private sealed class Target
		{
			public double Meter;

			public double LastHit = double.NegativeInfinity;

			public double FrozenUntil = double.NegativeInfinity;

			public double ImmuneUntil = double.NegativeInfinity;

			public double LastFreezeStart = double.NegativeInfinity;

			public int Step;
		}

		private readonly MageConfig _cfg;

		private readonly Func<double> _rng;

		private readonly Dictionary<long, Target> _targets = new Dictionary<long, Target>();

		public ChillTracker(MageConfig cfg, Func<double> rng)
		{
			_cfg = cfg;
			_rng = rng;
		}

		private Target Get(long id)
		{
			if (!_targets.TryGetValue(id, out Target value))
			{
				value = (_targets[id] = new Target());
			}
			return value;
		}

		public bool IsFrozen(long id, double now)
		{
			if (_targets.TryGetValue(id, out Target value))
			{
				return now < value.FrozenUntil;
			}
			return false;
		}

		public bool IsImmune(long id, double now)
		{
			if (_targets.TryGetValue(id, out Target value) && now >= value.FrozenUntil)
			{
				return now < value.ImmuneUntil;
			}
			return false;
		}

		public double Meter(long id, double now)
		{
			if (!_targets.TryGetValue(id, out Target value))
			{
				return 0.0;
			}
			return Decayed(value, now);
		}

		private double Decayed(Target t, double now)
		{
			double num = now - t.LastHit - (double)_cfg.ChillHoldSeconds;
			if (!(num <= 0.0))
			{
				return Math.Max(0.0, t.Meter - num * (double)_cfg.ChillDecayPerSecond);
			}
			return t.Meter;
		}

		public void Forget(long id)
		{
			_targets.Remove(id);
		}

		public ChillResult Hit(long id, double now, bool eligible = true, float gainFactor = 1f)
		{
			Target target = Get(id);
			if (!eligible || now < target.FrozenUntil || now < target.ImmuneUntil)
			{
				return new ChillResult(counted: false, 0f, (float)Decayed(target, now), froze: false, 0.0, highRoll: false);
			}
			if (target.Step > 0 && (now - target.LastFreezeStart > _cfg.FreezeSequenceResetSeconds || (now >= target.ImmuneUntil && target.ImmuneUntil > double.NegativeInfinity && target.Step >= _cfg.FreezeDurations.Length)))
			{
				target.Step = 0;
			}
			target.Meter = Decayed(target, now);
			bool flag = _rng() < (double)_cfg.ChillHighChance;
			float num = (flag ? _cfg.ChillHighMin : _cfg.ChillLowMin);
			float num2 = (flag ? _cfg.ChillHighMax : _cfg.ChillLowMax);
			float num3 = Math.Min(100f, (num + (float)_rng() * (num2 - num)) * Math.Max(0f, gainFactor));
			target.Meter += num3;
			target.LastHit = now;
			if (target.Meter < (double)_cfg.ChillThreshold)
			{
				return new ChillResult(counted: true, num3, (float)target.Meter, froze: false, 0.0, flag);
			}
			target.Meter = 0.0;
			int num4 = Math.Min(target.Step, _cfg.FreezeDurations.Length - 1);
			double num5 = _cfg.FreezeDurations[num4];
			target.FrozenUntil = now + num5;
			target.LastFreezeStart = now;
			target.Step++;
			if (target.Step >= _cfg.FreezeDurations.Length)
			{
				target.ImmuneUntil = target.FrozenUntil + _cfg.FreezeImmunitySeconds;
			}
			return new ChillResult(counted: true, num3, 0f, froze: true, num5, flag);
		}
	}
	public sealed class ClassDefinition
	{
		private static readonly Regex IdPattern = new Regex("^[a-z][a-z0-9_]*$", RegexOptions.Compiled);

		public static readonly int[] TierLevels = new int[8] { 1, 5, 10, 15, 20, 30, 40, 50 };

		public static readonly int[] TierRanks = new int[8];

		public const int UltimateLevel = 50;

		public const int RequiredTierCount = 5;

		public const int CapstoneLevel = 20;

		public const int UpgradeCount = 3;

		public const int MaxUpgradeCount = 4;

		public const int RankNameCount = 6;

		public bool HasFourthUpgrade => Upgrades.Count > 3;

		public MasteryShape MasteryShape { get; }

		public int MasteryRanksPerUpgrade => MasteryShape.RanksPerUpgrade;

		public int MasteryPointCap => (MasteryShape.LevelsPerRank.HasValue ? Upgrades.Count : 4) * MasteryRanksPerUpgrade;

		public string Id { get; }

		public string DisplayName { get; }

		public IReadOnlyList<TalentTier> Tiers { get; }

		public IReadOnlyList<string> Upgrades { get; }

		public IReadOnlyList<string>? RankNames { get; }

		public Func<IReadOnlyDictionary<int, string>, int, string, bool>? OptionAvailable { get; }

		public Func<IReadOnlyDictionary<int, string>, int, string, bool>? OptionRetained { get; }

		public TalentTier Capstone => TierAt(20);

		public static int RequiredClassRank(int upgradeIndex, int upgradeRank)
		{
			if (upgradeIndex < 3)
			{
				return (upgradeRank - 1) / 2;
			}
			return 4;
		}

		public int UpgradeIndex(string id)
		{
			for (int i = 0; i < Upgrades.Count; i++)
			{
				if (Upgrades[i] == id)
				{
					return i;
				}
			}
			return -1;
		}

		public ClassDefinition(string id, string displayName, IReadOnlyList<TalentTier> tiers, IReadOnlyList<string> upgrades, IReadOnlyList<string>? rankNames = null, Func<IReadOnlyDictionary<int, string>, int, string, bool>? optionAvailable = null, Func<IReadOnlyDictionary<int, string>, int, string, bool>? optionRetained = null, MasteryShape? masteryShape = null)
		{
			OptionAvailable = optionAvailable;
			OptionRetained = optionRetained;
			MasteryShape = masteryShape ?? Retheme.Core.MasteryShape.Standard;
			if (id == null || !IdPattern.IsMatch(id))
			{
				throw new ArgumentException("Class id must match [a-z][a-z0-9_]*.", "id");
			}
			if (string.IsNullOrWhiteSpace(displayName))
			{
				throw new ArgumentException("Display name required.", "displayName");
			}
			if (tiers == null || tiers.Count < 5 || tiers.Count > TierLevels.Length)
			{
				throw new ArgumentException("A class needs the first five shared tiers and may define later tiers in order.", "tiers");
			}
			for (int i = 0; i < tiers.Count; i++)
			{
				TalentTier talentTier = tiers[i];
				int num = Array.IndexOf(TierLevels, talentTier.Level);
				if (num < 0 || !((i < 5) ? (num == i) : (num > Array.IndexOf(TierLevels, tiers[i - 1].Level))) || talentTier.RequiredRank != TierRanks[num])
				{
					throw new ArgumentException($"Tier {i} must be level {TierLevels[Math.Min(i, TierLevels.Length - 1)]} or a later shared tier, in order, rank {TierRanks[Math.Max(num, 0)]}.", "tiers");
				}
				if (talentTier.Options.Count < 1 || talentTier.Options.Any((string o) => o == null || !IdPattern.IsMatch(o)) || talentTier.Options.Distinct().Count() != talentTier.Options.Count)
				{
					throw new ArgumentException($"Tier {talentTier.Level} options must be unique ids.", "tiers");
				}
			}
			if (upgrades == null || upgrades.Count < 3 || upgrades.Count > 4 || upgrades.Any((string u) => u == null || !IdPattern.IsMatch(u)) || upgrades.Distinct().Count() != upgrades.Count)
			{
				throw new ArgumentException($"A class needs {3} unique upgrade ids, plus a fourth optionally.", "upgrades");
			}
			if (rankNames != null && rankNames.Count != 6)
			{
				throw new ArgumentException($"{6} rank names required.", "rankNames");
			}
			Id = id;
			DisplayName = displayName;
			Tiers = tiers;
			Upgrades = upgrades;
			RankNames = rankNames;
		}

		public TalentTier? TierAt(int level)
		{
			return Tiers.FirstOrDefault((TalentTier t) => t.Level == level);
		}

		public bool IsOptionAvailable(IReadOnlyDictionary<int, string> choices, int tierLevel, string option)
		{
			if (OptionAvailable != null)
			{
				return OptionAvailable(choices, tierLevel, option);
			}
			return true;
		}

		public bool IsOptionRetained(IReadOnlyDictionary<int, string> choices, int tierLevel, string option)
		{
			if (OptionRetained == null)
			{
				return IsOptionAvailable(choices, tierLevel, option);
			}
			return OptionRetained(choices, tierLevel, option);
		}

		public IEnumerable<string> OfferedOptions(IReadOnlyDictionary<int, string> choices, int tierLevel)
		{
			return (TierAt(tierLevel)?.Options ?? new string[0]).Where((string o) => IsOptionAvailable(choices, tierLevel, o));
		}
	}
	public sealed class ClassRegistry
	{
		private readonly Dictionary<string, ClassDefinition> _byId;

		public IEnumerable<ClassDefinition> All => _byId.Values.OrderBy<ClassDefinition, string>((ClassDefinition d) => d.Id, StringComparer.Ordinal);

		public static ClassRegistry Default { get; } = new ClassRegistry(MageCatalog.Definition, BerserkerCatalog.Definition, NecromancerCatalog.Definition, RangerCatalog.Definition, WarriorCatalog.Definition);

		public ClassRegistry(params ClassDefinition[] definitions)
		{
			_byId = new Dictionary<string, ClassDefinition>();
			foreach (ClassDefinition classDefinition in definitions)
			{
				if (_byId.ContainsKey(classDefinition.Id))
				{
					throw new ArgumentException("Duplicate class id '" + classDefinition.Id + "'.");
				}
				_byId[classDefinition.Id] = classDefinition;
			}
		}

		public bool TryGet(string id, out ClassDefinition def)
		{
			return _byId.TryGetValue(id, out def);
		}
	}
	public sealed class ClassState
	{
		public int ClassXp { get; internal set; }

		public int Rank { get; internal set; }

		public long MasteryXp { get; internal set; }

		public long MasteryDebt { get; internal set; }

		public int MasteryDebtDeaths { get; internal set; }

		public bool CapstoneLost { get; internal set; }

		public Dictionary<string, int> Spent { get; }

		public Dictionary<int, string> Choices { get; } = new Dictionary<int, string>();

		public int SpentTotal => Spent.Values.Sum();

		public ClassState()
			: this(MageCatalog.Upgrades)
		{
		}

		public ClassState(IEnumerable<string> upgradeIds)
		{
			Spent = upgradeIds.ToDictionary((string u) => u, (string _) => 0);
		}
	}
	public static class ClassText
	{
		public static string Blurb(string classId)
		{
			return classId switch
			{
				"mage" => "Cast fire, frost or lightning bolts with Eitr, backed by an elemental companion that fights at your side. Your spells and your companion grow as you rise.", 
				"berserker" => "Hit things to build Fury, then spend it to hit harder. Works with any melee weapon. Your rage gains new uses with every rank.", 
				"ranger" => "A bow and a Dire Wolf that hunts beside you. Mark your prey, loose arrows from range and let the wolf finish what you start.", 
				"necromancer" => "Summon skeletal thralls using blood magic, growing in number as you advance.\nChoose between enhancing your damage over time abilities with Wither and Pestilence, or a Revenant pet that can use melee talents of its own.", 
				"warrior" => "A melee fighter built on timing and weapon mastery: parry, guard and counter. Early access, not yet played in depth.", 
				_ => "", 
			};
		}

		public static IReadOnlyList<KeyValuePair<string, string>> Ultimates(string classId)
		{
			return classId switch
			{
				"mage" => new KeyValuePair<string, string>[2]
				{
					U("Cataclysm", "A three-wave blast of fire, frost and lightning."),
					U("Avatar", "All three elemental companions fight beside you.")
				}, 
				"berserker" => new KeyValuePair<string, string>[2]
				{
					U("Bloodbath", "A heavy strike that heals you, then a short enrage."),
					U("Last Stand", "Seconds of immunity, with more damage as your health falls.")
				}, 
				"ranger" => new KeyValuePair<string, string>[2]
				{
					U("Pack Attack", "A volley of arrows and a pack of Dire Wolves."),
					U("Lone Kill", "The same volley with no wolves, hitting harder the weaker the target.")
				}, 
				"necromancer" => new KeyValuePair<string, string>[2]
				{
					U("Lich Form", "Become a lich: Siphon drains any enemy and a Bone Shield soaks up overheal."),
					U("Final Oath", "25 ghosts rise and home in on your enemies.")
				}, 
				_ => new KeyValuePair<string, string>[0], 
			};
			static KeyValuePair<string, string> U(string name, string text)
			{
				return new KeyValuePair<string, string>(name, text);
			}
		}

		public static string PromotionText(string nextRankName, int[] rankCeilings, int rank)
		{
			if (rank + 1 >= rankCeilings.Length)
			{
				return "Promotion: you rise to the rank of " + nextRankName + ".";
			}
			int num = rankCeilings[rank] + 1;
			int num2 = rankCeilings[rank + 1];
			if (num > num2)
			{
				return $"Promotion: you rise to the rank of {nextRankName}. Levels stop at {rankCeilings[rank]}; further experience earns mastery points.";
			}
			return $"Promotion: you rise to the rank of {nextRankName} and may gain levels {num}-{num2}.";
		}
	}
	public static class CompanionChipText
	{
		public const string DeadSuffix = "(dead)";

		public static string Title(string name, ChipState state)
		{
			if (state != ChipState.Fallen)
			{
				return name;
			}
			return name + " (dead)";
		}

		public static int WholeSeconds(double seconds)
		{
			if (!double.IsNaN(seconds) && !(seconds <= 0.0))
			{
				return (int)Math.Min(2147483647.0, Math.Ceiling(seconds));
			}
			return 0;
		}

		public static string Respawning(double secondsLeft)
		{
			return "Respawning in: " + WholeSeconds(secondsLeft).ToString(CultureInfo.InvariantCulture) + "s";
		}

		public static string Following(float hpFraction)
		{
			return "HP " + (Math.Max(0f, Math.Min(1f, float.IsNaN(hpFraction) ? 0f : hpFraction)) * 100f).ToString("0", CultureInfo.InvariantCulture) + "%  Following";
		}

		public static string NotSummoned(string keyLabel, float eitrCost)
		{
			return keyLabel + " to summon (" + eitrCost.ToString("0", CultureInfo.InvariantCulture) + " Eitr)";
		}

		public static string Status(ChipState state, float hpFraction, double secondsLeft, string keyLabel, float eitrCost)
		{
			return state switch
			{
				ChipState.Fallen => Respawning(secondsLeft), 
				ChipState.Active => Following(hpFraction), 
				_ => NotSummoned(keyLabel, eitrCost), 
			};
		}
	}
	public enum PetKind
	{
		Fire,
		Frost,
		Earth
	}
	public static class CompanionMath
	{
		public static PetKind KindFor(string element)
		{
			if (!(element == "frost"))
			{
				if (!(element == "lightning"))
				{
					return PetKind.Fire;
				}
				return PetKind.Earth;
			}
			return PetKind.Frost;
		}

		public static float BaseHealth(PetKind k, int level)
		{
			return k switch
			{
				PetKind.Fire => 80f + 4f * (float)(level - 1), 
				PetKind.Frost => 100f + 5f * (float)(level - 1), 
				_ => 140f + 6f * (float)(level - 1), 
			};
		}

		public static float BaseDamage(PetKind k, int level)
		{
			return k switch
			{
				PetKind.Fire => 10f + (float)(level - 1), 
				PetKind.Frost => 10f + (float)(level - 1), 
				_ => 10f + (float)(level - 1), 
			};
		}

		public static float AttackInterval(PetKind k)
		{
			if (k != PetKind.Earth)
			{
				return 2f;
			}
			return 2.5f;
		}

		public static float Health(MageConfig cfg, PetKind k, int level, bool conjurer, bool caster = false, bool greater = false)
		{
			return BaseHealth(k, level) * (1f + (conjurer ? cfg.ConjurerCompanionBonus : 0f) + (greater ? cfg.GreaterCompanionHealthBonus : 0f)) * (caster ? cfg.CasterPetFactor : 1f);
		}

		public static float Damage(MageConfig cfg, PetKind k, int level, bool conjurer, bool potency, bool caster = false, bool greater = false)
		{
			return BaseDamage(k, level) * (1f + (conjurer ? cfg.ConjurerCompanionBonus : 0f) + (potency ? cfg.PotencyDamageBonus : 0f) + (greater ? cfg.GreaterCompanionDamageBonus : 0f)) * (caster ? cfg.CasterPetFactor : 1f);
		}

		public static float Scale(MageConfig cfg, PetKind k, bool caster, bool greater = false)
		{
			return ((k == PetKind.Earth) ? cfg.PetGolemScale : 1f) * (caster ? cfg.CasterPetScale : 1f) * (greater ? cfg.GreaterCompanionScale : 1f);
		}

		public static float SiphonFraction(MageConfig cfg, bool greater)
		{
			if (!greater)
			{
				return cfg.BoltSiphonFraction;
			}
			return cfg.GreaterSiphonFraction;
		}

		public static float SiphonRecoverySeconds(MageConfig cfg, bool greater)
		{
			if (!greater)
			{
				return cfg.SiphonRecoverySeconds;
			}
			return cfg.GreaterSiphonRecoverySeconds;
		}

		public static bool TripleHit(MageConfig cfg, bool greater, double roll)
		{
			if (greater)
			{
				return roll < (double)cfg.TripleHitChance;
			}
			return false;
		}

		public static int EchoCount(bool packEcho, bool tripleHit)
		{
			if (!tripleHit)
			{
				return packEcho ? 1 : 0;
			}
			return 2;
		}

		public static float SpeedMultiplier(MageConfig cfg, int strideRanks)
		{
			return 1f + cfg.PetStrideSpeedPerRank * MasteryRamp.Units(strideRanks);
		}
	}
	public sealed class PetLifecycle
	{
		private readonly Func<double> _deathCooldown;

		public bool Active { get; private set; }

		public float HealthFraction { get; private set; } = 1f;

		public double ReadyAt { get; private set; }

		public PetLifecycle(MageConfig cfg)
			: this(() => cfg.PetDeathCooldownSeconds)
		{
		}

		public PetLifecycle(Func<double> deathCooldownSeconds)
		{
			_deathCooldown = deathCooldownSeconds;
		}

		public bool Fallen(double now)
		{
			if (!Active)
			{
				return now < ReadyAt;
			}
			return false;
		}

		public double SecondsUntilReady(double now)
		{
			return Math.Max(0.0, ReadyAt - now);
		}

		public bool CanSummon(double now)
		{
			if (!Active)
			{
				return now >= ReadyAt;
			}
			return false;
		}

		public void Summoned()
		{
			Active = true;
		}

		public void Dismissed(float healthFraction)
		{
			Active = false;
			HealthFraction = Math.Max(0.01f, Math.Min(1f, healthFraction));
		}

		public void FullHeal()
		{
			HealthFraction = 1f;
		}

		public void RegenStowed(float fractionPerSecond, float dt)
		{
			if (!Active && !(dt <= 0f) && !(fractionPerSecond <= 0f))
			{
				HealthFraction = Math.Min(1f, HealthFraction + fractionPerSecond * Math.Min(dt, 2f));
			}
		}

		public void Died(double now)
		{
			Active = false;
			HealthFraction = 1f;
			ReadyAt = now + _deathCooldown();
		}

		public double ShortenRecovery(double now, double seconds)
		{
			if (!Fallen(now) || seconds <= 0.0)
			{
				return 0.0;
			}
			double readyAt = ReadyAt;
			ReadyAt = Math.Max(now, ReadyAt - seconds);
			return readyAt - ReadyAt;
		}

		public void Restore(bool active, float healthFraction, double readyAt)
		{
			Active = active;
			HealthFraction = Math.Max(0.01f, Math.Min(1f, healthFraction));
			ReadyAt = readyAt;
		}
	}
	public static class PetSaveCodec
	{
		public static string Encode(bool active, float healthFraction, double readyAt)
		{
			return string.Format(CultureInfo.InvariantCulture, "pet1|{0}|{1:0.###}|{2:0.###}", active ? 1 : 0, healthFraction, readyAt);
		}

		public static (bool Active, float Health, double ReadyAt) Decode(string? text)
		{
			string[] array = text?.Split('|');
			CultureInfo invariantCulture = CultureInfo.InvariantCulture;
			if (array == null || array.Length != 4 || array[0] != "pet1" || !float.TryParse(array[2], NumberStyles.Float, invariantCulture, out var result) || !double.TryParse(array[3], NumberStyles.Float, invariantCulture, out var result2))
			{
				return (Active: false, Health: 1f, ReadyAt: 0.0);
			}
			return (Active: array[1] == "1", Health: result, ReadyAt: result2);
		}
	}
	public sealed class MageConfig : ProgressionConfig
	{
		public float BoltDamage { get; set; } = 24f;

		public int FrostShards { get; set; } = 3;

		public float FrostShardInterval { get; set; } = 0.12f;

		public float BoltStartFactor { get; set; } = 0.7f;

		public int BoltFullDamageLevel { get; set; } = 10;

		public float BoltEitrCost { get; set; } = 8f;

		public float BoltCooldownSeconds { get; set; } = 0.8f;

		public int CataclysmCooldownSeconds { get; set; } = 150;

		public int CataclysmWaves { get; set; } = 3;

		public float CataclysmWaveFraction { get; set; } = 0.4f;

		public double CataclysmWaveDelaySeconds { get; set; } = 0.7;

		public float CataclysmEitrFraction { get; set; } = 0.6f;

		public float CataclysmDamage { get; set; } = 500f;

		public float CataclysmRadius { get; set; } = 12f;

		public int CataclysmMaxTargets { get; set; } = 20;

		public float CataclysmStagger { get; set; } = 4f;

		public float CataclysmKnockback { get; set; } = 8f;

		public int AvatarCooldownSeconds { get; set; } = 120;

		public double AvatarSeconds { get; set; } = 20.0;

		public float AvatarDamageFactor { get; set; } = 1f;

		public float BurstDamage { get; set; } = 35f;

		public float BurstStaggerMultiplier { get; set; } = 3f;

		public float BurstKnockback { get; set; }

		public float BurstRadius { get; set; } = 4f;

		public int BurstMaxTargets { get; set; } = 6;

		public float BurstRange { get; set; } = 20f;

		public float BurstEitrCost { get; set; } = 18f;

		public float BurstCooldownSeconds { get; set; } = 12f;

		public float WardBase { get; set; } = 35f;

		public float WardPerLevel { get; set; } = 2f;

		public float WardDurationSeconds { get; set; } = 8f;

		public float WardEitrCost { get; set; } = 16f;

		public float WardCooldownSeconds { get; set; } = 20f;

		public float CasterDamageBonus { get; set; } = 0.2f;

		public float ConjurerCompanionBonus { get; set; } = 0.2f;

		public float LanceDamage { get; set; } = 108f;

		public float LanceEitrCost { get; set; } = 30f;

		public float LanceCooldownSeconds { get; set; } = 15f;

		public float LanceRange { get; set; } = 30f;

		public int LanceFullTargets { get; set; } = 3;

		public float LanceFalloff { get; set; } = 0.25f;

		public float LanceFloor { get; set; } = 0.25f;

		public float ConvergenceDamage { get; set; } = 36f;

		public float ConvergenceRadius { get; set; } = 4f;

		public int ConvergenceMaxTargets { get; set; } = 6;

		public float ConvergenceRange { get; set; } = 20f;

		public float ConvergenceEitrCost { get; set; } = 24f;

		public float ConvergenceCooldownSeconds { get; set; } = 18f;

		public float EntangleRadius { get; set; } = 6f;

		public float EntangleSeconds { get; set; } = 3f;

		public float EntangleCooldownSeconds { get; set; } = 18f;

		public float EntangleEitrCost { get; set; } = 18f;

		public float EntangleRange { get; set; } = 20f;

		public int EntangleMaxTargets { get; set; } = 8;

		public double EntangleImmunitySeconds { get; set; } = 8.0;

		public float PackWardPetFraction { get; set; } = 1f;

		public int SpiritCount { get; set; } = 3;

		public float SpiritDamageFactor { get; set; } = 0.4f;

		public float SpiritLifetimeSeconds { get; set; } = 1.5f;

		public float SpiritVolleyCooldownSeconds { get; set; } = 20f;

		public float SpiritVolleyEitrCost { get; set; } = 40f;

		public float SpiritFireDelaySeconds { get; set; } = 0.25f;

		public float SwiftBoltSpeedFactor { get; set; } = 1.6f;

		public float SwiftBoltRangeFactor { get; set; } = 1.3f;

		public float SplashRadius { get; set; } = 2.5f;

		public float SplashDamageFactor { get; set; } = 0.4f;

		public float BoltSiphonFraction { get; set; } = 0.1f;

		public float SiphonRecoverySeconds { get; set; } = 4f;

		public float RallySpeedBonus { get; set; } = 0.2f;

		public float RallySeconds { get; set; } = 4f;

		public float ProliferationRadius { get; set; } = 5f;

		public int ProliferationMaxTargets { get; set; } = 5;

		public float ProliferationDamageFactor { get; set; } = 0.5f;

		public int ProliferationMaxGenerations { get; set; } = 3;

		public float ProliferationFalloff { get; set; } = 0.8f;

		public float ProliferationMarkSeconds { get; set; } = 6f;

		public float ZoneSeconds { get; set; } = 3f;

		public float ZoneRadius { get; set; } = 3f;

		public float ZoneDamagePerSecond { get; set; } = 0.15f;

		public float ZoneTickSeconds { get; set; } = 1f;

		public int ZoneMaxCount { get; set; } = 3;

		public float SharedBondFraction { get; set; } = 0.25f;

		public float GreaterCompanionScale { get; set; } = 1.4f;

		public float GreaterCompanionHealthBonus { get; set; } = 0.6f;

		public float GreaterCompanionDamageBonus { get; set; } = 0.2f;

		public float GreaterSiphonFraction { get; set; } = 0.18f;

		public float GreaterSiphonRecoverySeconds { get; set; } = 6f;

		public float TripleHitChance { get; set; } = 0.1f;

		public float ShockSeconds { get; set; } = 4f;

		public float ShockStaggerBonus { get; set; } = 0.5f;

		public float AttunementPerRank { get; set; } = 0.02f;

		public float ChillThreshold { get; set; } = 100f;

		public float ChillLowMin { get; set; } = 20f;

		public float ChillLowMax { get; set; } = 40f;

		public float ChillHighMin { get; set; } = 60f;

		public float ChillHighMax { get; set; } = 100f;

		public float ChillHighChance { get; set; } = 0.1f;

		public float ChillHoldSeconds { get; set; } = 3f;

		public float ChillDecayPerSecond { get; set; } = 20f;

		public double[] FreezeDurations { get; } = new double[3] { 2.0, 1.0, 0.5 };

		public float FreezeCrackVolume { get; set; } = 1.5f;

		public double FreezeImmunitySeconds { get; set; } = 8.0;

		public double FreezeSequenceResetSeconds { get; set; } = 12.0;

		public float PetSummonEitrCost { get; set; } = 16f;

		public double PetDeathCooldownSeconds { get; set; } = 45.0;

		public float PetStrideSpeedPerRank { get; set; } = 0.05f;

		public float PetPhysicalReduction { get; set; } = 0.5f;

		public float CasterPetFactor { get; set; } = 0.65f;

		public float CasterPetScale { get; set; } = 0.8f;

		public float PetStowedRegenPerSecond { get; set; } = 0.01f;

		public float PetGolemScale { get; set; } = 0.45f;

		public bool PetGolemStyled { get; set; } = true;

		pub

Retheme.Plugin.dll

Decompiled a day 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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Retheme.Core;
using Retheme.Plugin.Ui;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Retheme.Plugin")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+609bf44172567216185c1ebf7d8a2c167bebee52")]
[assembly: AssemblyProduct("Retheme.Plugin")]
[assembly: AssemblyTitle("Retheme.Plugin")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Retheme.Plugin
{
	internal sealed class ArenaCommand : ConsoleCommand
	{
		public override string Name => "retheme_arena";

		public override string Help => "Spawn the feel-test enemies for the current step (clears any left over first).";

		public override bool IsCheat => true;

		public override void Run(string[] args)
		{
			Console instance = Console.instance;
			if (instance != null)
			{
				instance.Print(TestRunner.SpawnFeelArena());
			}
		}

		internal static void Register()
		{
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new ArenaCommand());
		}
	}
	internal static class BasicBolt
	{
		internal const string LightningStaff = "StaffLightning";

		private static float _readyAt;

		internal static Vector3? AimOverride;

		internal static GameObject? LastLaunched;

		internal static float LastLaunchTime;

		internal static Vector3 LastLaunchOrigin;

		private static readonly int AimMask = LayerMask.GetMask(new string[10] { "Default", "static_solid", "Default_small", "piece", "terrain", "vehicle", "character", "character_net", "character_ghost", "hitbox" });

		internal static string? LastCarrier { get; private set; }

		internal static (float Damage, string Element, int Shards)? Last { get; private set; }

		internal static float ReadyAt => _readyAt;

		internal static void ResetCooldown()
		{
			_readyAt = 0f;
		}

		internal static void TryCast(Player player, MageConfig cfg)
		{
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			if (!ClassGate.IsMage || Time.time < _readyAt || ((Character)player).IsDead() || ((Character)player).InCutscene() || !Spells.Pay(player, cfg.BoltEitrCost))
			{
				return;
			}
			_readyAt = Time.time + cfg.BoltCooldownSeconds * cfg.CooldownMultiplier;
			BoltUpgrades.OnBoltCast(cfg);
			float num = Spells.Dmg(cfg, cfg.BoltDamage * SpellMath.BoltLevelFactor(cfg, RethemePlugin.State.Level));
			string element = Spells.Element;
			int num2 = ((!(element == "frost")) ? 1 : Mathf.Max(1, cfg.FrostShards));
			Last = (num, element, num2);
			RethemePlugin.Logger.LogInfo((object)$"[bolt] {element} {num:0.#} in {num2} shot(s)");
			if (num2 == 1)
			{
				Player player2 = player;
				HitData hit = NewHit(num);
				string staff = ((element == "lightning") ? "StaffLightning" : "StaffFireball");
				Vector3? aimOverride = AimOverride;
				bool fromHand = !AimOverride.HasValue;
				Launch(player2, hit, staff, 0f, aimOverride, null, fromHand);
			}
			else
			{
				((MonoBehaviour)RethemePlugin.Instance).StartCoroutine(Volley(player, cfg, num2, num / (float)num2));
			}
			Vector3 origin;
			Vector3 dir;
			if (!AimOverride.HasValue)
			{
				(origin, dir) = HandAim(player);
			}
			else
			{
				Vector3 val = ((Character)player).GetEyePoint() + AimOverride.Value * 0.6f;
				Vector3 value = AimOverride.Value;
				dir = value;
				origin = val;
			}
			float echo = EchoMath.Damage(cfg, num);
			Spells.Echo(delegate
			{
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Expected O, but got Unknown
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)player == (Object)null) && !((Character)player).IsDead())
				{
					HitData hit2 = new HitData();
					Spells.SetElement(hit2, echo, echo: true);
					Launch(player, hit2, (element == "lightning") ? "StaffLightning" : ((element == "frost") ? "StaffIceShards" : "StaffFireball"), 0f, dir, origin);
					Spells.LastEcho = ("bolt", echo);
				}
			});
		}

		internal static (Vector3 Origin, Vector3 Dir) HandAim(Player player)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			Vector3 lookDir = ((Character)player).GetLookDir();
			Vector3 eyePoint = ((Character)player).GetEyePoint();
			VisEquipment component = ((Component)player).GetComponent<VisEquipment>();
			Transform val = (((Object)(object)component != (Object)null) ? component.m_rightHand : null);
			if ((Object)(object)val == (Object)null)
			{
				return (Origin: eyePoint + lookDir * 0.6f, Dir: lookDir);
			}
			Vector3 val2 = eyePoint + lookDir * 60f;
			float num = 60f;
			RaycastHit[] array = Physics.RaycastAll(eyePoint, lookDir, 60f, AimMask, (QueryTriggerInteraction)1);
			for (int i = 0; i < array.Length; i++)
			{
				RaycastHit val3 = array[i];
				if (!((Object)(object)((RaycastHit)(ref val3)).collider == (Object)null) && !((Object)(object)((Component)((RaycastHit)(ref val3)).collider).GetComponentInParent<Player>() == (Object)(object)player) && ((RaycastHit)(ref val3)).distance < num)
				{
					num = ((RaycastHit)(ref val3)).distance;
					val2 = ((RaycastHit)(ref val3)).point;
				}
			}
			Vector3 val4 = val.position + lookDir * 0.35f;
			Vector3 val5 = val2 - val4;
			if (!(((Vector3)(ref val5)).sqrMagnitude < 0.01f))
			{
				return (Origin: val4, Dir: ((Vector3)(ref val5)).normalized);
			}
			return (Origin: val4, Dir: lookDir);
		}

		private static HitData NewHit(float damage)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_000e: Expected O, but got Unknown
			HitData val = new HitData();
			Spells.SetElement(val, damage);
			return val;
		}

		private static IEnumerator Volley(Player player, MageConfig cfg, int shards, float each)
		{
			for (int i = 0; i < shards; i++)
			{
				if ((Object)(object)player == (Object)null)
				{
					break;
				}
				if (((Character)player).IsDead())
				{
					break;
				}
				HitData hit = NewHit(each);
				Vector3? aimOverride = AimOverride;
				bool fromHand = !AimOverride.HasValue;
				Launch(player, hit, "StaffIceShards", 2.5f, aimOverride, null, fromHand);
				if (i < shards - 1)
				{
					yield return (object)new WaitForSeconds(cfg.FrostShardInterval);
				}
			}
		}

		internal static bool Launch(Player player, HitData hit, string staff = "StaffFireball", float spreadDegrees = 0f, Vector3? dirOverride = null, Vector3? originOverride = null, bool fromHand = false, float speedScale = 1f)
		{
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: 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_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			if (fromHand && !dirOverride.HasValue && !originOverride.HasValue)
			{
				(Vector3 Origin, Vector3 Dir) tuple = HandAim(player);
				Vector3 item = tuple.Origin;
				Vector3 item2 = tuple.Dir;
				originOverride = item;
				dirOverride = item2;
			}
			object obj;
			if (!((Object)(object)ObjectDB.instance != (Object)null))
			{
				obj = null;
			}
			else
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(staff);
				obj = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
			}
			ItemDrop val = (ItemDrop)obj;
			Attack val2 = val?.m_itemData.m_shared.m_attack;
			if (val2 == null || (Object)(object)val2.m_attackProjectile == (Object)null)
			{
				RethemePlugin.Logger.LogWarning((object)("[bolt] projectile for " + staff + " not found"));
				return false;
			}
			hit.m_skill = (SkillType)9;
			LastCarrier = ((Object)val2.m_attackProjectile).name;
			Vector3 val3 = (Vector3)(((??)dirOverride) ?? ((Character)player).GetLookDir());
			if (spreadDegrees > 0f)
			{
				val3 = Quaternion.Euler(Random.Range(0f - spreadDegrees, spreadDegrees), Random.Range(0f - spreadDegrees, spreadDegrees), 0f) * val3;
			}
			Vector3 val4 = (Vector3)(((??)originOverride) ?? (((Character)player).GetEyePoint() + val3 * 0.6f));
			if (Spells.CastFx >= 0.5f)
			{
				try
				{
					EffectList startEffect = val2.m_startEffect;
					if (startEffect != null)
					{
						startEffect.Create(val4, Quaternion.LookRotation(val3), (Transform)null, 1f, -1, default(ZDOID));
					}
					EffectList triggerEffect = val2.m_triggerEffect;
					if (triggerEffect != null)
					{
						triggerEffect.Create(val4, Quaternion.LookRotation(val3), (Transform)null, 1f, -1, default(ZDOID));
					}
				}
				catch (Exception ex)
				{
					RethemePlugin.Logger.LogWarning((object)("[bolt] cast fx: " + ex.Message));
				}
			}
			GameObject obj2 = Object.Instantiate<GameObject>(val2.m_attackProjectile, val4, Quaternion.LookRotation(val3));
			(float Speed, float Ttl) tuple2 = BoltUpgrades.LaunchFactors(RethemePlugin.Config);
			float item3 = tuple2.Speed;
			float item4 = tuple2.Ttl;
			BoltUpgrades.LastLaunchSpeedFactor = item3;
			IProjectile component = obj2.GetComponent<IProjectile>();
			if (component != null)
			{
				component.Setup((Character)(object)player, val3 * val2.m_projectileVel * RethemePlugin.Config.BoltSpeedMultiplier * item3 * speedScale, -1f, hit, val.m_itemData, (ItemData)null);
			}
			Projectile component2 = obj2.GetComponent<Projectile>();
			if ((Object)(object)component2 != (Object)null && item4 != 1f)
			{
				component2.m_ttl *= item4;
			}
			BoltUpgrades.Track(obj2, hit.GetTotalDamage());
			LastLaunched = obj2;
			LastLaunchTime = Time.time;
			LastLaunchOrigin = val4;
			return true;
		}
	}
	internal sealed class TestRunner : MonoBehaviour
	{
		private sealed class CapSnapshot
		{
			public int Level;

			public int Rank;

			public int Spent;

			public int Xp;

			public long Mastery;

			public string Lance = "";

			public string Tier10 = "";
		}

		private sealed class Row
		{
			public string Scenario = "";

			public string Manual = "";

			public string Expected = "";

			public string Observed = "";

			public bool Pass;
		}

		private sealed class Spec
		{
			public string Name;

			public string Manual;

			public string? Tier1;

			public string? Tier15;

			public float Damage;

			public float Cost;

			public Spec(string name, float damage, float cost, string manual)
			{
				Name = name;
				Damage = damage;
				Cost = cost;
				Manual = manual;
			}
		}

		private sealed class FakeInventory : IInventory
		{
			private readonly Dictionary<string, int> _items;

			public FakeInventory(IEnumerable<string> items)
			{
				_items = items.ToDictionary((string i) => i, (string _) => 1);
			}

			public int Count(string n)
			{
				if (!_items.TryGetValue(n, out var value))
				{
					return 0;
				}
				return value;
			}

			public bool Remove(string n, int a)
			{
				if (Count(n) < a)
				{
					return false;
				}
				_items[n] -= a;
				return true;
			}
		}

		[StructLayout(LayoutKind.Auto)]
		[CompilerGenerated]
		private struct <>c__DisplayClass97_1
		{
			public List<GameObject> grp;
		}

		private static readonly (int Tier, string Option)[] BerserkerDefaults = new(int, string)[7]
		{
			(1, "crushing"),
			(5, "ravager"),
			(10, "whirlwind"),
			(15, "wrath"),
			(20, "titan_slam"),
			(30, "sundering"),
			(40, "bloodtithe")
		};

		private static readonly (string Pack, int PackCount, string Heavy, string Boss, string Where)[] BerserkerArenas = new(string, int, string, string, string)[5]
		{
			("Boar", 4, "Greydwarf_Elite", "Eikthyr", "Meadows"),
			("Greydwarf", 6, "Troll", "Eikthyr", "Black Forest"),
			("Draugr", 5, "Abomination", "gd_king", "Swamp"),
			("Wolf", 5, "StoneGolem", "Bonemass", "Mountains"),
			("Goblin", 5, "GoblinBrute", "GoblinKing", "Plains")
		};

		private static readonly string[][] BerserkerExtraWeapons = new string[5][]
		{
			new string[1] { "KnifeFlint" },
			new string[2] { "AtgeirBronze", "KnifeCopper" },
			new string[3] { "SledgeIron", "AtgeirIron", "KnifeCopper" },
			new string[3] { "Battleaxe", "AtgeirIron", "KnifeSilver" },
			new string[3] { "Battleaxe", "AtgeirIron", "KnifeSilver" }
		};

		internal static int FeelArenaRank = -1;

		private static readonly FieldRef<Player, float> StaminaRef = AccessTools.FieldRefAccess<Player, float>("m_stamina");

		private static readonly (int Tier, string Option)[] NecroDefaults = new(int, string)[6]
		{
			(1, "hexer"),
			(5, "plagueweaver"),
			(10, "harvest"),
			(15, "endless_host"),
			(20, "pestilence"),
			(50, "lich_form")
		};

		private static readonly FieldRef<MonsterAI, Character> AiTarget = AccessTools.FieldRefAccess<MonsterAI, Character>("m_targetCreature");

		internal const string Character = "tosser";

		internal const string WorldName = "tosashdf";

		private const float TimeLimitSeconds = 420f;

		private readonly List<Row> _rows = new List<Row>();

		private string _abort = "";

		internal static bool NoNaturalSpawns;

		internal static readonly string[] AllGroups = new string[27]
		{
			"bolt", "p5", "tier30", "p6", "fx", "area", "chill", "shock", "pet", "petqa",
			"mastery", "classes", "berserker", "warrior", "ultimate", "necro", "npass", "pest", "rev", "thrall",
			"swap", "lich", "oath", "dmight", "ranger", "ui", "respawn"
		};

		internal static readonly string[] SmokeGroups = new string[4] { "bolt", "mastery", "ui", "respawn" };

		private static readonly (int Tier, string Option)[] WarriorDefaults = new(int, string)[5]
		{
			(1, "sentinel"),
			(5, "bastion"),
			(10, "challenging_shout"),
			(15, "unyielding"),
			(20, "immovable")
		};

		private static readonly FieldRef<Humanoid, float> BlockTimerRef = AccessTools.FieldRefAccess<Humanoid, float>("m_blockTimer");

		private static readonly FieldRef<Character, bool> BlockingRef = AccessTools.FieldRefAccess<Character, bool>("m_blocking");

		private static string LastBlockDiag = "";

		private static readonly MethodInfo RpcDamage = AccessTools.Method(typeof(Character), "RPC_Damage", (Type[])null, (Type[])null);

		internal static string ResultsPath => Path.Combine(Paths.BepInExRootPath, "retheme-test-results.md");

		private void ApplyBerserkerSetup(string step, string? picks)
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			MageConfig config = RethemePlugin.Config;
			int num = Mathf.Clamp(step[step.Length - 1] - 48, 0, 5);
			int num2 = Mathf.Min(num, 4);
			NoNaturalSpawns = true;
			ClearPet();
			ClearClutter();
			ClearHostiles();
			string[] array = new string[5] { "stomp", "slam", "shockwave", "nova", "groundhit" };
			foreach (string text in array)
			{
				((Terminal)Console.instance).TryRunCommand("retheme_prefabs " + text, false, false);
			}
			CharacterState val = CharacterState.CreateNew((ProgressionConfig)(object)config, (ClassRegistry)null);
			val.SwitchClass("berserker", true);
			FakeInventory fakeInventory = new FakeInventory(((ProgressionConfig)config).PromotionTrophies);
			for (int j = 0; j < num; j++)
			{
				val.GrantCombatXp(268435455);
				val.Promote((IInventory)(object)fakeInventory, true);
			}
			val.GrantCombatXp(268435455);
			(int, string)[] berserkerDefaults = BerserkerDefaults;
			for (int i = 0; i < berserkerDefaults.Length; i++)
			{
				var (tier, option) = berserkerDefaults[i];
				TryPick(val, tier, option);
			}
			array = (picks ?? "").Split(new char[2] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string id in array)
			{
				TalentTier val2 = ((IEnumerable<TalentTier>)BerserkerCatalog.Tiers).FirstOrDefault((Func<TalentTier, bool>)((TalentTier t) => t.Options.Contains(id)));
				if (val2 == null)
				{
					RethemePlugin.Logger.LogWarning((object)("[test] berserker pick '" + id + "' is not an option; ignored"));
				}
				else
				{
					TryPick(val, val2.Level, id);
				}
			}
			val.SetProgressForTesting(val.Level, long.MaxValue);
			bool flag;
			do
			{
				flag = false;
				foreach (string upgrade in val.ActiveDefinition.Upgrades)
				{
					CommandResult val3 = val.PurchaseMastery(upgrade, true);
					if (((CommandResult)(ref val3)).Ok)
					{
						flag = true;
					}
				}
			}
			while (flag);
			RethemePlugin.State = val;
			FreshKit();
			BerserkerBuild val4 = BerserkerBuild.From(val);
			BerserkerGame.Kit.Sync(val4, BerserkerGame.Now);
			BerserkerGame.Meter.Clear();
			BerserkerGame.Meter.AddRaw(BerserkerGame.Meter.Cap);
			FeelKit.Give(localPlayer, num2);
			FeelKit.GiveExtras(localPlayer, BerserkerExtraWeapons[num2]);
			string text2 = FeelKit.GiveTrinket(localPlayer);
			FillStamina(localPlayer);
			((Character)localPlayer).Heal(((Character)localPlayer).GetMaxHealth(), false);
			((Terminal)Console.instance).TryRunCommand("devcommands", false, false);
			bool flag2 = num < 5;
			localPlayer.SetGodMode(flag2);
			FeelArenaRank = num2;
			(string, int, string, string, string) tuple2 = BerserkerArenas[num2];
			IEnumerable<string> values = from kv in val.ActiveState.Choices
				orderby kv.Key
				select kv.Value.Replace('_', ' ');
			string text3 = string.Format("Setup ready ({0}, {1}): level {2}, {3}, picks: {4}. {5} Frenzy, {6} ability, {7} capstone. Trinket: {8}. No enemies yet: stage up, then press F5 and type retheme_arena. God mode {9}.", step, tuple2.Item5, val.Level, val.ActiveRankName, string.Join(", ", values), RethemePlugin.KeyLabel(0), RethemePlugin.KeyLabel(1), RethemePlugin.KeyLabel(2), (text2 == "") ? "none found" : Localization.instance.Localize(text2), flag2 ? "on (type god to toggle)" : "off");
			((Character)localPlayer).Message((MessageType)2, text3, 0, (Sprite)null, false);
			RethemePlugin.Logger.LogInfo((object)("[test] " + text3));
		}

		internal static string SpawnFeelArena()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return "retheme_arena: not in a world";
			}
			if (FeelArenaRank < 0)
			{
				return "retheme_arena: start a Berserker or Ranger feel step first";
			}
			(string, int, string, string, string) tuple = BerserkerArenas[FeelArenaRank];
			ClearHostiles();
			SpawnCluster(localPlayer, tuple.Item2, out var point, tuple.Item1, 10f);
			SpawnCluster(localPlayer, 1, out point, tuple.Item3, 18f);
			SpawnCluster(localPlayer, 1, out point, tuple.Item4, 45f);
			return $"retheme_arena ({tuple.Item5}): {tuple.Item2} {tuple.Item1} at 10 m, {tuple.Item3} at 18 m, {tuple.Item4} at 45 m";
		}

		private static void TryPick(CharacterState state, int tier, string option)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			CommandResult val = state.SelectTalent(tier, option, true);
			if (!((CommandResult)(ref val)).Ok)
			{
				RethemePlugin.Logger.LogInfo((object)$"[test] berserker pick {option} (tier {tier}) not open at this rank; skipped");
			}
		}

		private static void FillStamina(Player p)
		{
			StaminaRef.Invoke(p) = ((Character)p).GetMaxStamina();
		}

		private static CharacterState NewBerserker(MageConfig cfg, int promotions)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			CharacterState val = CharacterState.CreateNew((ProgressionConfig)(object)cfg, (ClassRegistry)null);
			val.SwitchClass("berserker", true);
			FakeInventory fakeInventory = new FakeInventory(((ProgressionConfig)cfg).PromotionTrophies);
			for (int i = 0; i < promotions; i++)
			{
				val.GrantCombatXp(268435455);
				val.Promote((IInventory)(object)fakeInventory, true);
			}
			val.GrantCombatXp(268435455);
			if (val.ActiveState.Rank == 2)
			{
				val.SetProgressForTesting(20, long.MaxValue);
			}
			if (val.ActiveState.Rank == 4)
			{
				val.SetProgressForTesting(40, long.MaxValue);
			}
			return val;
		}

		private static void Pick(CharacterState s, int tier, string? option)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			if (option == null)
			{
				s.ActiveState.Choices.Remove(tier);
				return;
			}
			CommandResult val = s.SelectTalent(tier, option, true);
			if (((CommandResult)(ref val)).Ok)
			{
				return;
			}
			throw new Exception($"SelectTalent({tier}, {option}) failed");
		}

		private static void FreshKit()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			BerserkerGame.Kit = new BerserkerKit(BerserkerGame.Config, (IFuryMeter)(object)BerserkerGame.Meter, (TrinketCharge)null);
		}

		private static void ClearStatus(Player p, StatusEffect? se)
		{
			if ((Object)(object)se != (Object)null)
			{
				((Character)p).GetSEMan().RemoveStatusEffect(se.NameHash(), false);
			}
		}

		private IEnumerator BerserkerScenarios(Player player, CharacterState mage)
		{
			MageConfig cfg = RethemePlugin.Config;
			BerserkerConfig bc = BerserkerGame.Config;
			NativeFury meter = BerserkerGame.Meter;
			RethemePlugin.State = mage;
			yield return (object)new WaitForSeconds(0.5f);
			float stockMax = ((Character)player).GetMaxAdrenaline();
			CharacterState b = (RethemePlugin.State = NewBerserker(cfg, 2));
			FreshKit();
			yield return (object)new WaitForSeconds(0.5f);
			float maxAdrenaline = ((Character)player).GetMaxAdrenaline();
			ChillRow("Berserker is offered in the class chooser", "Open the spellbook Class tab", "Berserker playable, Mage still playable", string.Format("berserker {0}, mage {1}, other {2}", ClassGate.IsPlayable("berserker"), ClassGate.IsPlayable("mage"), ClassGate.IsPlayable("no_such_class")), ClassGate.IsPlayable("berserker") && ClassGate.IsPlayable("mage") && !ClassGate.IsPlayable("no_such_class"));
			ChillRow("Fury cap replaces the trinket cap (level 20 = 50)", "Switch to Berserker; read the Fury bar's maximum", $"50 (the Mage's stock maximum was {stockMax:0})", $"{maxAdrenaline:0}", Near(maxAdrenaline, 50f, 0.01f));
			Pick(b, 1, null);
			Pick(b, 5, null);
			meter.Clear();
			BerserkerGame.InMelee = true;
			BerserkerGame.MeleeWeapon = (WeaponClass)1;
			((Character)player).AddAdrenaline(2f);
			int first = meter.Value;
			((Character)player).AddAdrenaline(2f);
			int second = meter.Value;
			yield return (object)new WaitForSeconds(0.4f);
			((Character)player).AddAdrenaline(2f);
			int value = meter.Value;
			BerserkerGame.InMelee = false;
			ChillRow("Melee hit gains x4 native, one gain per swing", "Hit an enemy twice quickly, then once more after a beat", "native +2 gives 8; a second gain inside 0.3 s gives nothing; then 16", $"{first}, {second}, {value}", first == 8 && second == 8 && value == 16);
			Pick(b, 5, "giantbreaker");
			meter.Clear();
			FreshKit();
			BerserkerGame.InMelee = true;
			BerserkerGame.MeleeWeapon = (WeaponClass)2;
			((Character)player).AddAdrenaline(2f);
			int gb = meter.Value;
			BerserkerGame.MeleeWeapon = (WeaponClass)1;
			yield return (object)new WaitForSeconds(0.4f);
			((Character)player).AddAdrenaline(2f);
			int num = meter.Value - gb;
			Pick(b, 5, "ravager");
			meter.Clear();
			FreshKit();
			BerserkerGame.MeleeWeapon = (WeaponClass)1;
			((Character)player).AddAdrenaline(2f);
			int value2 = meter.Value;
			BerserkerGame.InMelee = false;
			ChillRow("Weapon specialization changes the gain", "Pick Giantbreaker, hit with a two-hander and a sword; then Ravager with a sword", "Giantbreaker two-handed 12, one-handed 8; Ravager one-handed 10", $"{gb}, {num}, {value2}", gb == 12 && num == 8 && value2 == 10);
			Pick(b, 5, null);
			meter.Clear();
			FreshKit();
			((Character)player).AddAdrenaline(5f);
			float num2 = BerserkerGame.Meter.Value;
			ChillRow("Parry / dodge style gain stays native (not x4)", "Parry an attack and read the Fury bar", "between 1 and 5 (the native +5 through the game's own scaling)", $"{num2}", num2 >= 1f && num2 <= 5f);
			yield return TrinketScenarios(player, b, bc);
			FreshKit();
			meter.Clear();
			meter.Cap = 50;
			meter.AddRaw(30f);
			BerserkerGame.Kit.TryFrenzy(BerserkerBuild.From(b), BerserkerGame.Now);
			meter.Clear();
			meter.AddRaw(10f);
			FreshKit();
			AbilityResult val = BerserkerGame.Kit.TryFrenzy(BerserkerBuild.From(b), BerserkerGame.Now);
			ChillRow("Frenzy needs 20 Fury and spends nothing when it fails", "Press G with little Fury", "fails (not enough Fury), Fury unchanged at 10", string.Format("{0}, Fury {1}", val.Ok ? "cast" : ((object)val.Reason/*cast due to .constrained prefix*/).ToString(), meter.Value), !val.Ok && (int)val.Reason == 16 && meter.Value == 10);
			FreshKit();
			meter.Clear();
			meter.AddRaw(30f);
			BerserkerGame.CastFrenzy(player);
			AbilityResult lastAbility = BerserkerGame.LastAbility;
			double now = BerserkerGame.Now;
			((Character)player).AddAdrenaline(5f);
			int value3 = meter.Value;
			(float, float) tuple = BerserkerGame.Kit.AttackModifiers(BerserkerBuild.From(b), now);
			BerserkerGame.CastFrenzy(player);
			AbilityResult lastAbility2 = BerserkerGame.LastAbility;
			ChillRow("Frenzy: spends all Fury, freezes the meter, +2% damage per point, half stamina", "Build 30 Fury, press G, hit things", "Fury 30 -> 0, gains discarded, damage +60%, stamina saving 50%, second cast refused", $"spent {((lastAbility != null) ? new int?(lastAbility.FurySpent) : ((int?)null))}, Fury now {value3}, damage +{tuple.Item1:P0}, saving {tuple.Item2:P0}, second {((lastAbility2 != null) ? new Failure?(lastAbility2.Reason) : ((Failure?)null))}", lastAbility != null && lastAbility.Ok && lastAbility.FurySpent == 30 && value3 == 0 && Near(tuple.Item1, 0.6f, 0.001f) && Near(tuple.Item2, 0.5f, 0.001f) && lastAbility2 != null && (int)lastAbility2.Reason == 20);
			Pick(b, 10, "whirlwind");
			Pick(b, 20, "titan_slam");
			FreshKit();
			meter.Clear();
			meter.AddRaw(40f);
			FillStamina(player);
			float stamina = player.GetStamina();
			Vector3 point;
			List<GameObject> ring = SpawnCluster(player, 3, out point, "Boar", 0.5f);
			BerserkerGame.LastAbility = null;
			BerserkerGame.LastTargets = -1;
			BerserkerGame.CastActive10(player);
			float stamUsed = stamina - player.GetStamina();
			yield return (object)new WaitForSeconds(0.3f);
			AbilityResult lastAbility3 = BerserkerGame.LastAbility;
			ChillRow("Whirlwind: point-blank, spends 15 Fury (no stamina), +5 per 2 targets", "Stand among 3 enemies, press backtick", "hits 3, spends 15 and gains 5 (Fury 30, plus any native stagger gains), x1.3 weapon damage with +16% from Fury, no stamina used", $"hits {BerserkerGame.LastTargets}, Fury {meter.Value}, x{((lastAbility3 != null) ? new float?(lastAbility3.WeaponDamage) : ((float?)null)):0.##} bonus {((lastAbility3 != null) ? new float?(lastAbility3.DamageBonus) : ((float?)null)):P0}, stamina {stamUsed:0.#}", lastAbility3 != null && lastAbility3.Ok && BerserkerGame.LastTargets == 3 && lastAbility3.FurySpent == 15 && lastAbility3.FuryGained == 5 && meter.Value >= 30 && Near(lastAbility3.WeaponDamage, 1.3f) && Near(lastAbility3.DamageBonus, 0.16f, 0.001f) && stamUsed < 1f);
			foreach (GameObject item in ring)
			{
				if ((Object)(object)item != (Object)null)
				{
					ZNetScene.instance.Destroy(item);
				}
			}
			FreshKit();
			meter.Clear();
			meter.AddRaw(40f);
			FillStamina(player);
			List<GameObject> pack = SpawnCluster(player, 10, out point, "Boar", 0.5f);
			BerserkerGame.LastAbility = null;
			BerserkerGame.LastTargets = -1;
			BerserkerGame.CastCapstone(player);
			yield return (object)new WaitForSeconds(0.3f);
			AbilityResult lastAbility4 = BerserkerGame.LastAbility;
			ChillRow("Titan Slam: radius 5, up to 8 targets, spends 20 Fury", "Stand among 10 enemies, press J", "hits 8 (cap), spends 20 (Fury 20 plus any native stagger gains), x2.5 weapon damage", $"hits {BerserkerGame.LastTargets}, Fury {meter.Value}, x{((lastAbility4 != null) ? new float?(lastAbility4.WeaponDamage) : ((float?)null)):0.##}", lastAbility4 != null && lastAbility4.Ok && BerserkerGame.LastTargets == 8 && lastAbility4.FurySpent == 20 && meter.Value >= 20 && Near(lastAbility4.WeaponDamage, 2.5f));
			foreach (GameObject item2 in pack)
			{
				if ((Object)(object)item2 != (Object)null)
				{
					ZNetScene.instance.Destroy(item2);
				}
			}
			ChillRow("Whirlwind and Titan Slam use melee visuals and the weapon's swing animation", "Cast Whirlwind and Titan Slam and watch", "the stock club-hit ring and ground slam play instead of the Mage fire impact, and the weapon's swing animation is triggered", $"effect plays {BerserkerGame.FxPlayed}, swing animation '{BerserkerGame.LastSwing}'", BerserkerGame.FxPlayed >= 2 && BerserkerGame.LastSwing != "");
			Pick(b, 10, "crushing_blow");
			FreshKit();
			meter.Clear();
			meter.AddRaw(40f);
			FillStamina(player);
			BerserkerGame.CastActive10(player);
			bool flag = BerserkerGame.Kit.CrushingBlowArmed(BerserkerGame.Now);
			BerserkerGame.OnSecondaryStarted();
			HitData val2 = new HitData();
			val2.m_damage.m_slash = 10f;
			BerserkerGame.ModifyOutgoing(val2);
			ChillRow("Crushing Blow: spends 30 Fury, next secondary does x2.2 and x2 stagger", "Press backtick, then secondary attack", "Fury 40 -> 10, armed, 10 damage becomes 25.52 (x2.2 with the +16% Fury bonus), stagger x2", $"Fury {meter.Value}, armed {flag}, damage {((DamageTypes)(ref val2.m_damage)).GetTotalDamage():0.##}, stagger x{val2.m_staggerMultiplier:0.#}", flag && meter.Value == 10 && Near(((DamageTypes)(ref val2.m_damage)).GetTotalDamage(), 25.52f) && Near(val2.m_staggerMultiplier, 2f));
			bool flag2 = !BerserkerGame.Kit.CrushingBlowArmed(BerserkerGame.Now);
			BerserkerGame.ActiveBlow = null;
			FreshKit();
			meter.Clear();
			meter.AddRaw(40f);
			FillStamina(player);
			BerserkerGame.CastActive10(player);
			BerserkerGame.OnSecondaryStarted();
			bool flag3 = BerserkerGame.Kit.CrushingBlowArmed(BerserkerGame.Now);
			ChillRow("Crushing Blow is used up by a landed hit, not by a miss", "Arm it, swing the secondary at nothing; then at an enemy", "spent after the hit, still armed after the miss", $"spent on hit {flag2}, armed after a miss {flag3}", flag2 && flag3);
			BerserkerGame.ActiveBlow = null;
			FreshKit();
			meter.Clear();
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("MeadHealthMinor");
			object obj;
			if (itemPrefab == null)
			{
				obj = null;
			}
			else
			{
				ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
				if (component == null)
				{
					obj = null;
				}
				else
				{
					ItemData itemData = component.m_itemData;
					obj = ((itemData != null) ? itemData.Clone() : null);
				}
			}
			ItemData val3 = (ItemData)obj;
			GameObject itemPrefab2 = ObjectDB.instance.GetItemPrefab("CookedMeat");
			object obj2;
			if (itemPrefab2 == null)
			{
				obj2 = null;
			}
			else
			{
				ItemDrop component2 = itemPrefab2.GetComponent<ItemDrop>();
				if (component2 == null)
				{
					obj2 = null;
				}
				else
				{
					ItemData itemData2 = component2.m_itemData;
					obj2 = ((itemData2 != null) ? itemData2.Clone() : null);
				}
			}
			ItemData val4 = (ItemData)obj2;
			int num3 = ((val3 != null) ? BerserkerGame.OnConsumed(player, val3) : (-1));
			int num4 = ((val4 != null) ? BerserkerGame.OnConsumed(player, val4) : (-1));
			ChillRow("Any mead grants Fury (20); food does not", "Drink a mead, then eat cooked meat", "+20 Fury from the mead, nothing from the meat", $"mead +{num3}, meat +{num4}, Fury {meter.Value}", num3 == BerserkerGame.Config.MeadFury && num4 == 0 && meter.Value == BerserkerGame.Config.MeadFury);
			meter.Clear();
			StaminaRef.Invoke(player) = 0f;
			float num5 = BerserkerGame.RefundStamina(player);
			float num6 = (float)Passives.Total("berserker", (PassiveStat)5, BerserkerGame.Build.Level, 0) / 1000f * ((Character)player).GetMaxStamina();
			ChillRow("Fury abilities refund a share of max stamina (passive)", "Use an ability with low stamina", $"{num6:0.#} stamina back at this level", $"{num5:0.#} back, stamina now {player.GetStamina():0.#}", Near(num5, num6) && Near(player.GetStamina(), num6, 0.2f));
			FillStamina(player);
			FreshKit();
			meter.Clear();
			HitData val5 = new HitData();
			val5.m_damage.m_slash = ((Character)player).GetMaxHealth() * 0.05f;
			int num7 = BerserkerGame.OnDamageTaken(player, val5);
			meter.Clear();
			BerserkerGame.InBlock = true;
			((Character)player).AddAdrenaline(5f);
			int value4 = meter.Value;
			BerserkerGame.InBlock = false;
			ChillRow("Taking damage builds Fury; plain blocking does not", "Take a hit for 5% of your health; then a block or parry's native Adrenaline", "5 Fury from the hit, 0 from the block", $"{num7} from the hit, {value4} from the block", num7 == 5 && value4 == 0);
			meter.Clear();
			Pick(b, 5, "ravager");
			FreshKit();
			meter.Clear();
			BerserkerGame.InMelee = true;
			BerserkerGame.MeleeWeapon = (WeaponClass)1;
			HitData val6 = new HitData();
			val6.SetAttacker((Character)(object)player);
			int num8 = BerserkerGame.OnStructureHit(val6);
			BerserkerGame.InMelee = false;
			int num9 = BerserkerGame.OnStructureHit(val6);
			ChillRow("Hitting a tree or rock gives half the Fury of a creature hit", "Chop a tree or mine a rock with a melee weapon (simulated here)", "Ravager one-handed: 5 inside a swing (10 from a creature), 0 outside one", $"{num8} inside a swing, {num9} outside", num8 == 5 && num9 == 0);
			meter.Clear();
			Pick(b, 5, null);
			Pick(b, 20, "unchained");
			FreshKit();
			meter.Clear();
			FillStamina(player);
			BerserkerGame.CastCapstone(player);
			yield return (object)new WaitForSeconds(0.3f);
			float maxAdrenaline2 = ((Character)player).GetMaxAdrenaline();
			bool flag4 = BerserkerGame.Kit.DrainSuspended(BerserkerGame.Now);
			ChillRow("Unchained: Fury cap +30 and no drain for 10 s", "Press J", "cap 80, drain suspended", $"cap {maxAdrenaline2:0}, drain suspended {flag4}", Near(maxAdrenaline2, 80f, 0.01f) && flag4);
			FreshKit();
			yield return (object)new WaitForSeconds(0.3f);
			Pick(b, 1, "hardened");
			meter.Clear();
			meter.AddRaw(50f);
			HitData val7 = new HitData();
			val7.m_damage.m_blunt = 100f;
			val7.m_damage.m_fire = 100f;
			BerserkerGame.ModifyIncoming(val7);
			HitData val8 = new HitData();
			val8.m_damage.m_slash = 100f;
			BerserkerGame.ModifyOutgoing(val8);
			ChillRow("Fury bonuses at 50: +20% damage out, Hardened -15% physical in", "Fill Fury, compare damage dealt and taken", "100 slash becomes 120; 100 blunt becomes 85; fire untouched", $"{val8.m_damage.m_slash:0.#}, {val7.m_damage.m_blunt:0.#}, fire {val7.m_damage.m_fire:0.#}", Near(val8.m_damage.m_slash, 120f, 0.1f) && Near(val7.m_damage.m_blunt, 85f, 0.1f) && Near(val7.m_damage.m_fire, 100f, 0.01f));
			Pick(b, 1, null);
			Pick(b, 5, "bloodfury");
			meter.Clear();
			FreshKit();
			((Character)player).SetHealth(((Character)player).GetMaxHealth() * 0.5f);
			float hpBefore = ((Character)player).GetHealth();
			BerserkerGame.OnKill(player);
			yield return (object)new WaitForSeconds(0.2f);
			ChillRow("Bloodfury kill: +20 Fury and 3% max health", "Kill something with Bloodfury picked", $"Fury 20, health +{((Character)player).GetMaxHealth() * 0.03f:0.#}", $"Fury {meter.Value}, health +{((Character)player).GetHealth() - hpBefore:0.#}", meter.Value == 20 && Near(((Character)player).GetHealth() - hpBefore, ((Character)player).GetMaxHealth() * 0.03f, 0.5f));
			Pick(b, 5, null);
			FreshKit();
			meter.Clear();
			meter.AddRaw(40f);
			FillStamina(player);
			BerserkerGame.CastFrenzy(player);
			float regenBerserker = player.m_staminaRegen;
			RethemePlugin.State = mage;
			ClassSwitch.OnSwitched(new SwitchResult(true, (Failure)0, "berserker", "mage"));
			yield return (object)new WaitForSeconds(0.5f);
			ChillRow("Switching away clears Fury and restores stock behaviour", "Switch from Berserker to Mage mid-fight", $"Fury 0, no Frenzy, maximum back to {stockMax:0}, no stamina regen change", $"Fury {meter.Value}, Frenzy {BerserkerGame.Kit.FrenzyActive(BerserkerGame.Now)}, max {((Character)player).GetMaxAdrenaline():0}, regen {player.m_staminaRegen:0.##} (class {regenBerserker:0.##})", meter.Value == 0 && !BerserkerGame.Kit.FrenzyActive(BerserkerGame.Now) && Near(((Character)player).GetMaxAdrenaline(), stockMax, 0.01f));
			FreshKit();
			yield return BerserkerRank4Scenarios(player, mage);
		}

		private IEnumerator BerserkerRank4Scenarios(Player player, CharacterState mage)
		{
			MageConfig config = RethemePlugin.Config;
			NativeFury meter = BerserkerGame.Meter;
			CharacterState b = NewBerserker(config, 4);
			Pick(b, 1, null);
			Pick(b, 5, null);
			Pick(b, 10, "whirlwind");
			Pick(b, 20, "titan_slam");
			RethemePlugin.State = b;
			FreshKit();
			meter.Clear();
			FillStamina(player);
			yield return (object)new WaitForSeconds(0.5f);
			float baseCap = ((Character)player).GetMaxAdrenaline();
			Pick(b, 40, "overcharge");
			yield return (object)new WaitForSeconds(0.3f);
			float maxAdrenaline = ((Character)player).GetMaxAdrenaline();
			ChillRow("Overcharge: Fury cap +10", "Pick Overcharge at level 40 and read the Fury bar's maximum", "50 without it, 60 with it", $"{baseCap:0} without, {maxAdrenaline:0} with", Near(baseCap, 50f, 0.01f) && Near(maxAdrenaline, 60f, 0.01f));
			Pick(b, 40, null);
			yield return (object)new WaitForSeconds(0.2f);
			Pick(b, 40, "momentum");
			FreshKit();
			meter.Clear();
			meter.AddRaw(50f);
			FillStamina(player);
			yield return (object)new WaitForSeconds(0.3f);
			_ = BerserkerGame.Now;
			Vector3 point;
			List<GameObject> hostile = SpawnCluster(player, 1, out point, "Boar", 3f);
			yield return (object)new WaitForSeconds(0.3f);
			Vector3 value = ((hostile.Count > 0 && (Object)(object)hostile[0] != (Object)null) ? hostile[0].transform.position : ((Component)player).transform.position);
			BerserkerGame.CastActive10(player, value);
			double num = BerserkerGame.Kit.CooldownRemaining("whirlwind", BerserkerGame.Now);
			double num2 = BerserkerGame.Kit.CooldownRemaining("titan_slam", BerserkerGame.Now);
			BerserkerGame.CastCapstone(player, value);
			double num3 = BerserkerGame.Kit.CooldownRemaining("whirlwind", BerserkerGame.Now);
			foreach (GameObject item in hostile)
			{
				if ((Object)(object)item != (Object)null)
				{
					ZNetScene.instance.Destroy(item);
				}
			}
			ChillRow("Momentum: each ability cast takes 2 s off the others' cooldowns", "Pick Momentum, cast Whirlwind then Titan Slam", "Whirlwind's cooldown is about 2 s shorter right after the Titan Slam than right after its own cast", $"Whirlwind {num:0.0} s, then {num3:0.0} s (Titan {num2:0.0} s before its cast)", num > 7.0 && num3 < num - 1.5);
			Pick(b, 40, null);
			FreshKit();
			meter.Clear();
			yield return (object)new WaitForSeconds(0.2f);
			(float, float) passiveBases = BerserkerGame.PassiveBases;
			float num4 = 1f;
			RethemePlugin.State = mage;
			((Character)player).GetSEMan().ModifyHealthRegen(ref num4);
			RethemePlugin.State = b;
			float num5 = 1f;
			((Character)player).GetSEMan().ModifyHealthRegen(ref num5);
			num5 /= Mathf.Max(0.0001f, num4);
			ChillRow("Berserker passives at level 40: run cost, jump cost, health regeneration", "Switch to a level 40 Berserker; read the Stats tab", "run and jump cost -12.5% (x0.875), health regeneration +12.5% (x1.125)", $"run {player.m_runStaminaDrain:0.###}/{passiveBases.Item1:0.###}, jump {((Character)player).m_jumpStaminaUsage:0.###}/{passiveBases.Item2:0.###}, regen x{num5:0.###}", passiveBases.Item1 > 0f && Near(player.m_runStaminaDrain, passiveBases.Item1 * 0.875f, 0.001f) && Near(((Character)player).m_jumpStaminaUsage, passiveBases.Item2 * 0.875f, 0.001f) && Near(num5, 1.125f, 0.001f));
			b.ActiveState.Spent["brutality"] = 7;
			meter.Clear();
			HitData val = new HitData();
			val.m_damage.m_slash = 100f;
			BerserkerGame.ModifyOutgoing(val);
			meter.AddRaw(50f);
			HitData val2 = new HitData();
			val2.m_damage.m_slash = 100f;
			BerserkerGame.ModifyOutgoing(val2);
			ChillRow("Brutality: +14 flat damage per hit at 7 ranks, before the Fury bonus", "Buy Brutality ranks; hit with and without Fury", "100 slash becomes 114 with no Fury and 136.8 at 50 Fury", $"{val.m_damage.m_slash:0.#}, {val2.m_damage.m_slash:0.#}", Near(val.m_damage.m_slash, 114f, 0.1f) && Near(val2.m_damage.m_slash, 136.8f, 0.1f));
			b.ActiveState.Spent["brutality"] = 0;
			meter.Clear();
			Pick(b, 30, "unbroken");
			FreshKit();
			meter.Clear();
			meter.AddRaw(50f);
			FillStamina(player);
			BerserkerGame.CastFrenzy(player);
			int blockedBefore = BerserkerStaggerPatch.Blocked;
			((Character)player).Stagger(Vector3.forward);
			yield return (object)new WaitForSeconds(0.3f);
			int num6 = BerserkerStaggerPatch.Blocked - blockedBefore;
			HitData val3 = new HitData();
			val3.m_damage.m_blunt = 100f;
			BerserkerGame.ModifyIncoming(val3);
			ChillRow("Unbroken: no stagger and -15% physical damage during Frenzy", "Pick Unbroken, press G, get hit by something heavy", "the stagger is blocked (1), 100 blunt becomes 85, the player is not staggering", $"blocked {num6}, blunt {val3.m_damage.m_blunt:0.#}, staggering {((Character)player).IsStaggering()}", num6 >= 1 && Near(val3.m_damage.m_blunt, 85f, 0.1f) && !((Character)player).IsStaggering());
			FreshKit();
			Pick(b, 30, null);
			Pick(b, 30, "rampage");
			meter.Clear();
			meter.AddRaw(50f);
			FillStamina(player);
			BerserkerGame.CastFrenzy(player);
			double num7 = BerserkerGame.Kit.FrenzyRemaining(BerserkerGame.Now);
			BerserkerGame.OnKill(player);
			double num8 = BerserkerGame.Kit.FrenzyRemaining(BerserkerGame.Now);
			ChillRow("Rampage: a kill during Frenzy extends it by 1 s", "Pick Rampage, press G, kill something", "Frenzy time left grows by 1 s", $"{num7:0.00} -> {num8:0.00}", Mathf.Abs((float)(num8 - num7) - 1f) < 0.15f);
			FreshKit();
			Pick(b, 30, null);
			Pick(b, 30, "sundering");
			FreshKit();
			meter.Clear();
			meter.AddRaw(40f);
			FillStamina(player);
			List<GameObject> ring = SpawnCluster(player, 1, out point, "Boar", 0.5f);
			Character target = ((ring.Count > 0 && (Object)(object)ring[0] != (Object)null) ? ring[0].GetComponent<Character>() : null);
			if ((Object)(object)target != (Object)null)
			{
				target.SetMaxHealth(5000f);
				target.SetHealth(5000f);
			}
			BerserkerGame.LastRendStacks = 0;
			BerserkerGame.CastActive10(player);
			yield return (object)new WaitForSeconds(0.3f);
			int num9 = (((Object)(object)target != (Object)null) ? BerserkerGame.Kit.Rend.Stacks(((Object)target).GetInstanceID(), BerserkerGame.Now) : (-1));
			HitData val4 = new HitData();
			val4.m_damage.m_slash = 100f;
			if ((Object)(object)target != (Object)null)
			{
				BerserkerGame.OnHitLanded(target, val4);
			}
			ChillRow("Sundering: a Whirlwind hit adds a Rend stack, and Rend adds 4% to your hits", "Pick Sundering, Whirlwind an enemy, then hit it", "1 stack after the Whirlwind (the patch added it), the next 100 damage hit becomes 104", $"stacks {num9}, hit {val4.m_damage.m_slash:0.#}", (Object)(object)target != (Object)null && num9 == 1 && Near(val4.m_damage.m_slash, 104f, 0.1f));
			foreach (GameObject item2 in ring)
			{
				if ((Object)(object)item2 != (Object)null)
				{
					ZNetScene.instance.Destroy(item2);
				}
			}
			FreshKit();
			Pick(b, 30, null);
			Pick(b, 40, "bloodtithe");
			FreshKit();
			meter.Clear();
			meter.AddRaw(50f);
			FillStamina(player);
			((Character)player).SetHealth(((Character)player).GetMaxHealth() * 0.5f);
			float hp0 = ((Character)player).GetHealth();
			BerserkerGame.CastFrenzy(player);
			yield return (object)new WaitForSeconds(0.2f);
			float num10 = ((Character)player).GetHealth() - hp0;
			ChillRow("Bloodtithe: spending 50 Fury heals 7.5% of max health", "Pick Bloodtithe, press G at 50 Fury", $"health +{((Character)player).GetMaxHealth() * 0.075f:0.#}", $"health +{num10:0.#}", Near(num10, ((Character)player).GetMaxHealth() * 0.075f, 1f));
			FreshKit();
			Pick(b, 40, null);
			RethemePlugin.State = mage;
			yield return (object)new WaitForSeconds(0.3f);
			ClassSwitch.OnSwitched(new SwitchResult(true, (Failure)0, "berserker", "mage"));
			FreshKit();
		}

		private IEnumerator TrinketScenarios(Player player, CharacterState b, BerserkerConfig bc)
		{
			NativeFury meter = BerserkerGame.Meter;
			ItemDrop val = ObjectDB.instance.m_items.Select((GameObject i) => (!((Object)(object)i == (Object)null)) ? i.GetComponent<ItemDrop>() : null).FirstOrDefault((Func<ItemDrop, bool>)((ItemDrop d) => (Object)(object)d != (Object)null && (int)d.m_itemData.m_shared.m_itemType == 24 && (Object)(object)d.m_itemData.m_shared.m_fullAdrenalineSE != (Object)null));
			if ((Object)(object)val == (Object)null)
			{
				ChillRow("A full Fury bar does not fire the trinket", "Equip a trinket, fill Fury", "trinket not fired", "no trinket item with a full-bar effect found in the game data", pass: false);
				ChillRow("Spent Fury fires the trinket at half its cost", "Equip a trinket, press G with Fury", "trinket fires", "no trinket item found", pass: false);
				yield break;
			}
			string name = ((Object)((Component)val).gameObject).name;
			ItemData item = ((Humanoid)player).GetInventory().AddItem(name, 1, 1, 0, 0L, "", false, false);
			if (item == null || !((Humanoid)player).EquipItem(item, true))
			{
				ChillRow("Trinket scenarios", "Equip a trinket", "equipped", "could not equip " + name, pass: false);
				yield break;
			}
			StatusEffect se = item.m_shared.m_fullAdrenalineSE;
			ClearStatus(player, se);
			FreshKit();
			meter.Clear();
			yield return (object)new WaitForSeconds(0.5f);
			int cost = BerserkerGame.Kit.Trinket.TrinketCost;
			((Character)player).AddAdrenaline(100f);
			((Character)player).AddAdrenaline(100f);
			int value = meter.Value;
			bool flag = ((Character)player).GetSEMan().HaveStatusEffect(se.NameHash());
			ChillRow("A full Fury bar does not fire the equipped trinket", "Equip " + item.m_shared.m_name + ", fill Fury to the cap", "Fury stays at the cap (50), trinket effect not started", $"Fury {value}, trinket effect active {flag} (trinket cost {cost})", value == 50 && !flag && cost > 0);
			ClearStatus(player, se);
			FreshKit();
			meter.Clear();
			meter.Cap = 50;
			meter.AddRaw(50f);
			yield return (object)new WaitForSeconds(0.2f);
			BerserkerGame.CastFrenzy(player);
			yield return (object)new WaitForSeconds(0.2f);
			AbilityResult lastAbility = BerserkerGame.LastAbility;
			bool flag2 = ((Character)player).GetSEMan().HaveStatusEffect(se.NameHash());
			ChillRow("Spent Fury fires the equipped trinket", "With a trinket equipped, build Fury and press G", $"proc reported, trinket effect started (needs {Mathf.CeilToInt((float)cost * bc.TrinketCostFactor)} spent of cost {cost})", $"spent {((lastAbility != null) ? new int?(lastAbility.FurySpent) : ((int?)null))}, proc {((lastAbility != null) ? new bool?(lastAbility.TrinketProc) : ((bool?)null))}, effect active {flag2}", lastAbility != null && lastAbility.Ok && lastAbility.TrinketProc && flag2);
			ClearStatus(player, se);
			((Humanoid)player).UnequipItem(item, true);
			((Humanoid)player).GetInventory().RemoveItem(item);
			FreshKit();
			meter.Clear();
			CharacterState ult = (RethemePlugin.State = NewBerserker(RethemePlugin.Config, 5));
			FreshKit();
			yield return (object)new WaitForSeconds(0.3f);
			FillStamina(player);
			((Character)player).Heal(((Character)player).GetMaxHealth(), false);
			int num = BerserkerGame.BloodbathCasts + BerserkerGame.LastStandCasts;
			BerserkerGame.CastUltimate(player);
			ChillRow("Level 50 ultimate: an unpicked slot casts nothing", "Reach level 50 and press the ultimate key before picking", "no cast, no cooldown, pick pending", $"level {ult.Level}, casts {BerserkerGame.BloodbathCasts + BerserkerGame.LastStandCasts - num}, cooldown {ult.UltimateCooldownEndUnix}, pending {ult.UltimatePickPending}", ult.Level == 50 && BerserkerGame.BloodbathCasts + BerserkerGame.LastStandCasts == num && ult.UltimateCooldownEndUnix == 0L && ult.UltimatePickPending);
			Pick(ult, 50, "bloodbath");
			double enrageWas = bc.BloodbathEnrageSeconds;
			bc.BloodbathEnrageSeconds = 1.5;
			Vector3 point;
			List<GameObject> bbPack = SpawnCluster(player, 3, out point, "Boar", 1f);
			FreshKit();
			meter.Clear();
			FillStamina(player);
			((Character)player).SetHealth(((Character)player).GetMaxHealth() * 0.4f);
			float hpBefore = ((Character)player).GetHealth();
			float maxHp = ((Character)player).GetMaxHealth();
			Vector3 baseScale = ((Component)player).transform.localScale;
			BerserkerGame.LastTargets = -1;
			BerserkerGame.CastUltimate(player);
			yield return (object)new WaitForSeconds(0.3f);
			float healed = ((Character)player).GetHealth() - hpBefore;
			bool enragedNow = BerserkerGame.Enraged && Near(((Component)player).transform.localScale.x, baseScale.x * bc.BloodbathEnrageScale, 0.01f);
			float factor = BerserkerGame.UltimateDamageFactor();
			CommandResult val2 = ult.SelectTalent(50, "last_stand", true, DateTimeOffset.UtcNow);
			bool swapBlocked = (int)((CommandResult)(ref val2)).Reason == 27;
			long cool = ult.UltimateCooldownSecondsRemaining(DateTimeOffset.UtcNow);
			yield return (object)new WaitForSeconds(1.5f);
			bool flag3 = !BerserkerGame.Enraged && Near(((Component)player).transform.localScale.x, baseScale.x, 0.01f);
			ChillRow("Bloodbath: strike, heal 20%, enrage with bigger size and damage, then it ends", "Pick Bloodbath, press the ultimate key near enemies", $"hits enemies, heals {bc.BloodbathHealFraction:P0}, enrage x{bc.BloodbathEnrageScale} size and +{bc.BloodbathEnrageDamage:P0} damage, 15 s cooldown, swap blocked, enrage ends", $"hits {BerserkerGame.LastTargets}, healed {healed:0.#} of {maxHp:0.#}, enraged {enragedNow}, factor {factor:0.##}, cooldown {cool}s, swap blocked {swapBlocked}, ended {flag3}", BerserkerGame.LastTargets > 0 && healed >= maxHp * bc.BloodbathHealFraction * 0.95f && enragedNow && Near(factor, 1f + bc.BloodbathEnrageDamage, 0.02f) && cool > 0 && cool <= bc.BloodbathCooldownSeconds && swapBlocked && flag3);
			bc.BloodbathEnrageSeconds = enrageWas;
			foreach (GameObject item2 in bbPack)
			{
				if ((Object)(object)item2 != (Object)null)
				{
					ZNetScene.instance.Destroy(item2);
				}
			}
			ult.ResetUltimateCooldown();
			Pick(ult, 50, "last_stand");
			double immuneWas = bc.LastStandImmunitySeconds;
			bc.LastStandImmunitySeconds = 1.5;
			((Character)player).SetHealth(maxHp * 0.5f);
			float lowFactor = BerserkerGame.UltimateDamageFactor();
			int blockedBefore = BerserkerGame.ImmuneBlocked;
			BerserkerGame.CastUltimate(player);
			HitData val3 = new HitData();
			val3.m_damage.m_slash = 80f;
			val3.m_damage.m_fire = 20f;
			val3.m_pushForce = 50f;
			BerserkerGame.ModifyIncoming(val3);
			bool nulled = val3.GetTotalDamage() <= 0f && val3.m_pushForce <= 0f && BerserkerGame.Immune;
			yield return (object)new WaitForSeconds(1.8f);
			HitData val4 = new HitData();
			val4.m_damage.m_slash = 80f;
			BerserkerGame.ModifyIncoming(val4);
			bool flag4 = !BerserkerGame.Immune && val4.GetTotalDamage() > 0f;
			ChillRow("Last Stand: damage rises as health falls; 10 s of immunity to all damage, then it ends", "Pick Last Stand, press the ultimate key and get hit", $"+{bc.LastStandMaxDamageBonus / 2f:P0} damage at half health, hits during the window deal nothing and push nothing, damage returns after", $"factor at half health {lowFactor:0.##}, nulled {nulled}, blocked {BerserkerGame.ImmuneBlocked - blockedBefore}, damage returns {flag4}", Near(lowFactor, 1f + bc.LastStandMaxDamageBonus / 2f, 0.03f) && nulled && BerserkerGame.ImmuneBlocked - blockedBefore == 1 && flag4);
			bc.LastStandImmunitySeconds = immuneWas;
			BerserkerGame.EndUltimateEffects();
			ult.ResetUltimateCooldown();
			RethemePlugin.State = b;
			((Character)player).Heal(((Character)player).GetMaxHealth(), false);
			FreshKit();
			meter.Clear();
		}

		private IEnumerator FinalOathScenarios(Player player)
		{
			CharacterState state = (RethemePlugin.State = NewNecro(RethemePlugin.Config, 5));
			NecromancerGame.ResetForTest();
			NecromancerGame.ResetLichForTest();
			ClearHostiles();
			yield return null;
			TalentTier obj = state.ActiveDefinition.TierAt(50);
			IReadOnlyList<string> readOnlyList = ((obj != null) ? obj.Options : null);
			bool flag = readOnlyList?.SequenceEqual(new string[2] { "lich_form", "final_oath" }) ?? false;
			ChillRow("The level 50 Ultimate row offers both Necromancer picks", "Open the Talents tab at level 50", "Lich Form and Final Oath", (readOnlyList == null) ? "no options" : string.Join(", ", readOnlyList), flag && state.Level == 50 && state.UltimatePickPending);
			Pick(state, 50, "final_oath");
			float health = ((Character)player).GetHealth();
			float eitr = player.GetEitr();
			NecromancerGame.CastUltimate(player);
			int finalOathGhostsAlive = NecromancerGame.FinalOathGhostsAlive;
			long num = state.UltimateCooldownSecondsRemaining(DateTimeOffset.UtcNow);
			TestRunner testRunner = this;
			string observed = $"{finalOathGhostsAlive} ghosts, {num} s cooldown, HP/Eitr spent {health - ((Character)player).GetHealth():0.##}/{eitr - player.GetEitr():0.##}";
			int pass;
			if (finalOathGhostsAlive == 25 && num >= 149 && Near(((Character)player).GetHealth(), health) && Near(player.GetEitr(), eitr))
			{
				UltimateResult lastUltimate = NecromancerGame.LastUltimate;
				pass = ((lastUltimate != null && lastUltimate.Ok && lastUltimate.Ability == "final_oath" && lastUltimate.CooldownSeconds == 150) ? 1 : 0);
			}
			else
			{
				pass = 0;
			}
			testRunner.ChillRow("Final Oath launches a free radial wave on empty ground", "Cast with no enemies nearby", "25 ghosts, 150 s cooldown, no HP or Eitr spent", observed, (byte)pass != 0);
			CommandResult val = state.SelectTalent(50, "lich_form", true);
			ChillRow("Final Oath locks the Ultimate pick while the wave runs", "Try to pick Lich Form while the ghosts are out", "UltimateOnCooldown", $"{((CommandResult)(ref val)).Reason}, {NecromancerGame.FinalOathGhostsAlive} ghosts", !((CommandResult)(ref val)).Ok && (int)((CommandResult)(ref val)).Reason == 27 && NecromancerGame.FinalOathGhostsAlive > 0 && state.UltimatePick == "final_oath");
			state.ActiveState.Choices[50] = "lich_form";
			NecromancerGame.CastUltimate(player);
			UltimateResult refusedLich = NecromancerGame.LastUltimate;
			state.ActiveState.Choices[50] = "final_oath";
			yield return (object)new WaitForSeconds(7.5f);
			int inFlight = CountOathVisuals();
			yield return (object)new WaitForSeconds(1f);
			int num2 = CountOathVisuals();
			ChillRow("Final Oath ghosts expire after 8 s", "Let the wave fly with no hostiles nearby", "25 visuals at 7.5 s, zero ghosts and visuals at 8.5 s", $"{inFlight} visuals at 7.5 s, {NecromancerGame.FinalOathGhostsAlive} ghosts and {num2} visuals at 8.5 s", inFlight == 25 && NecromancerGame.FinalOathGhostsAlive == 0 && num2 == 0);
			state.ResetUltimateCooldown();
			Pick(state, 50, "lich_form");
			NecromancerGame.CastUltimate(player);
			bool lichActive = NecromancerGame.LichActive;
			state.ActiveState.Choices[50] = "final_oath";
			NecromancerGame.CastUltimate(player);
			UltimateResult lastUltimate2 = NecromancerGame.LastUltimate;
			ChillRow("Final Oath and Lich Form block each other's casts", "Cast each pick while the other pick's timer is running", "both casts refused with UltimateOnCooldown", $"Lich Form: {((refusedLich != null) ? new Failure?(refusedLich.Reason) : ((Failure?)null))}; Final Oath: {((lastUltimate2 != null) ? new Failure?(lastUltimate2.Reason) : ((Failure?)null))}", lichActive && refusedLich != null && !refusedLich.Ok && refusedLich.Ability == "lich_form" && (int)refusedLich.Reason == 27 && lastUltimate2 != null && !lastUltimate2.Ok && lastUltimate2.Ability == "final_oath" && (int)lastUltimate2.Reason == 27 && NecromancerGame.FinalOathGhostsAlive == 0);
			NecromancerGame.ResetLichForTest();
			state.ResetUltimateCooldown();
			Character distant = NecroDummy(player, "Draugr_Elite", 5f);
			NecromancerGame.CastUltimate(player);
			yield return (object)new WaitForSeconds(2f);
			bool flag2 = (Object)(object)distant == (Object)null || distant.IsDead() || distant.GetHealth() <= 0f || NecromancerGame.Kit.Curses.IsCursed(NecromancerGame.IdOf(distant));
			ChillRow("Final Oath reaches an enemy outside contact range", "Cast with a lone enemy 5 m ahead", "the traveling wave curses or kills the enemy", $"enemy hit {flag2}", flag2);
			NecroGone(distant);
			yield return null;
			NecromancerGame.ResetForTest();
			state.ResetUltimateCooldown();
			Character original = NecroDummy(player, "Draugr_Elite", 9f);
			NecromancerGame.CastUltimate(player);
			yield return null;
			yield return null;
			int tracking = NecromancerGame.FinalOathGhostsTargeting(original);
			Character nearest = NecroDummy(player, "Draugr_Elite", 4f, -2f);
			Character farther = NecroDummy(player, "Draugr_Elite", 8f, -2f);
			NecroKill(original);
			yield return null;
			yield return null;
			int num3 = NecromancerGame.FinalOathGhostsTargeting(nearest);
			ChillRow("Final Oath retargets after a target dies", "Kill the locked target with two new enemies in range", "ghosts leave the dead target and the closest replacement gains ghosts (ghosts with nothing in seek range keep flying straight)", $"originally tracked {tracking}, nearest now tracked {num3}, original now tracked {NecromancerGame.FinalOathGhostsTargeting(original)}", tracking > 0 && num3 > 0 && NecromancerGame.FinalOathGhostsTargeting(original) < tracking);
			NecroGone(original, nearest, farther);
			yield return OathDamageScenario(player, state, boss: false, 1125f);
			yield return OathDamageScenario(player, state, boss: true, 562.5f);
			state.ResetUltimateCooldown();
			NecromancerGame.CastUltimate(player);
			int beforeSwitch = NecromancerGame.FinalOathGhostsAlive;
			SwitchResult switched = ClassSwitch.Switch("mage", resting: true);
			bool clearedOnSwitch = NecromancerGame.FinalOathGhostsAlive == 0;
			yield return null;
			num2 = CountOathVisuals();
			ChillRow("Switching class during Final Oath clears the wave", "Switch to Mage with ghosts still in flight", "switch succeeds and all ghosts and visuals are removed", $"was {beforeSwitch}, switch {((SwitchResult)(ref switched)).Ok}, visuals {num2}", beforeSwitch == 25 && ((SwitchResult)(ref switched)).Ok && clearedOnSwitch && num2 == 0);
			NecromancerGame.ResetForTest();
		}

		private IEnumerator OathDamageScenario(Player player, CharacterState state, bool boss, float expected)
		{
			NecromancerGame.ResetForTest();
			state.ResetUltimateCooldown();
			Character target = NecroDummy(player, "Draugr_Elite", 0.5f);
			target.m_boss = boss;
			target.m_damageModifiers.m_spirit = (DamageModifier)0;
			target.m_damageModifiers.m_poison = (DamageModifier)3;
			target.SetMaxHealth(5000f);
			target.SetHealth(5000f);
			((Component)target).transform.position = ((Component)player).transform.position + ((Component)player).transform.forward * 0.5f;
			Physics.SyncTransforms();
			float hp = target.GetHealth();
			Skill blood = (Skill)AccessTools.Method(typeof(Skills), "GetSkill", (Type[])null, (Type[])null).Invoke(((Character)player).GetSkills(), new object[1] { (object)(SkillType)10 });
			float skillLevel = blood.m_level;
			float skillProgress = blood.m_accumulator;
			blood.m_level = 50f;
			blood.m_accumulator = 0f;
			NecromancerConfig cfg = NecromancerGame.Config;
			float maxHealth = ((Character)player).GetMaxHealth();
			((Character)player).SetHealth(maxHealth * 0.1f);
			NecromancerGame.CastUltimate(player);
			yield return null;
			yield return null;
			float level = blood.m_level;
			float accumulator = blood.m_accumulator;
			blood.m_level = 50f;
			blood.m_accumulator = 0f;
			for (int i = 0; i < cfg.FinalOathGhostCount; i++)
			{
				((Character)player).RaiseSkill((SkillType)10, 1f);
			}
			bool flag = Near(level, blood.m_level, 0.001f) && Near(accumulator, blood.m_accumulator, 0.001f) && (level > 50f || accumulator > 0f);
			blood.m_level = skillLevel;
			blood.m_accumulator = skillProgress;
			float num = Mathf.Min(Mathf.Min(expected / (float)cfg.FinalOathGhostCount * NecromancerGame.Kit.Rules.SiphonRate(NecromancerGame.Build, (SiphonSource)0, false), maxHealth * cfg.SiphonHitCapPct) * (float)cfg.FinalOathGhostCount, maxHealth * cfg.SiphonWindowCapPct);
			ChillRow(boss ? "Boss Oath contacts give capped Siphon and one XP award each" : "Same-frame Oath contacts share Siphon and give one XP award each", "Measure a point-blank volley against the Siphon cap and 25 native Blood Magic raises", $"Siphon {num:0.##}, Blood Magic matches 25 native raises", $"Siphon {NecromancerGame.LastSiphon:0.##}, matching XP={flag}", NecromancerGame.FinalOathGhostsAlive == 0 && flag && Near(NecromancerGame.LastSiphon, num));
			NecroFull(player);
			CurseTracker curses = NecromancerGame.Kit.Curses;
			long num2 = NecromancerGame.IdOf(target);
			if (!boss)
			{
				ChillRow("A full Final Oath volley leaves a single curse", "Hit one dummy with the full wave", "one curse on the dummy", $"{curses.Count} records, dummy cursed {curses.IsCursed(num2)}", curses.Count == 1 && curses.IsCursed(num2) && curses.OwnerOf(num2) == NecromancerGame.IdOf((Character)(object)player));
			}
			StatusEffect spirit = target.GetSEMan().GetStatusEffect(SEMan.s_statusEffectSpirit);
			if ((Object)(object)spirit != (Object)null)
			{
				yield return (object)new WaitForSeconds(spirit.m_ttl + 0.25f);
			}
			float num3 = hp - target.GetHealth();
			ChillRow(boss ? "A boss takes half the Final Oath damage" : "A lone dummy takes the full Final Oath volley", "Cast at a point-blank dummy with normal spirit resistance", $"{expected:0} spirit damage", $"{num3:0.##} health lost, Spirit applied {(Object)(object)spirit != (Object)null}", (Object)(object)spirit != (Object)null && Near(num3, expected, expected * 0.08f));
			NecroGone(target);
		}

		private static int CountOathVisuals()
		{
			return Object.FindObjectsByType<Transform>((FindObjectsSortMode)0).Count((Transform t) => ((Object)t).name == "retheme_oath_ghost");
		}

		private IEnumerator LichFormScenarios(Player player, CharacterState saved)
		{
			NecromancerGame.Config.ThrallLifeFloorPct = 0.5f;
			NecromancerGame.UseCheapRaiseForTest();
			MageConfig config = RethemePlugin.Config;
			NecromancerConfig nc = NecromancerGame.Config;
			double oldSeconds = nc.LichSeconds;
			double oldLinger = nc.LichShieldLingerSeconds;
			CharacterState n = (RethemePlugin.State = NewNecro(config, 5));
			NecromancerGame.ResetForTest();
			NecromancerGame.ResetLichForTest();
			Pick(n, 1, null);
			Pick(n, 5, null);
			Pick(n, 10, null);
			Pick(n, 15, null);
			Pick(n, 20, null);
			player.SetGodMode(true);
			NecroFull(player);
			yield return (object)new WaitForSeconds(1.5f);
			bool ultimatePickPending = n.UltimatePickPending;
			NecromancerGame.CastUltimate(player);
			bool flag = !LichSwapSpike.Active && !NecromancerGame.LichActive;
			ChillRow("Level 50 row: unpicked ultimate does nothing", "Press Y at level 50 before choosing", "pick pending, key inert", $"level {n.Level} rank {n.ActiveState.Rank}, pending {ultimatePickPending}, form {NecromancerGame.LichActive}", n.Level >= 50 && ultimatePickPending && flag);
			Pick(n, 50, "lich_form");
			float baseRun = ((Character)player).m_runSpeed;
			NecromancerGame.CastUltimate(player);
			yield return (object)new WaitForSeconds(0.6f);
			long num = n.UltimateCooldownSecondsRemaining(DateTimeOffset.UtcNow);
			TestRunner testRunner = this;
			object arg = NecromancerGame.LichActive;
			object arg2 = num;
			UltimateResult? lastUltimate = NecromancerGame.LastUltimate;
			string observed = $"active {arg}, cooldown {arg2}s, cast {((lastUltimate != null) ? new bool?(lastUltimate.Ok) : ((bool?)null))}";
			int pass;
			if (NecromancerGame.LichActive)
			{
				UltimateResult lastUltimate2 = NecromancerGame.LastUltimate;
				if (lastUltimate2 != null && lastUltimate2.Ok && num >= 148)
				{
					pass = ((num <= 150) ? 1 : 0);
					goto IL_02c6;
				}
			}
			pass = 0;
			goto IL_02c6;
			IL_02c6:
			testRunner.ChillRow("Lich Form starts on the ultimate key and uses the shared cooldown", "Pick Lich Form, press Y", "form active, cooldown about 150 s", observed, (byte)pass != 0);
			ChillRow("Lich Form: skeleton body, +25% run speed, drain mode on", "Look at the player while in the form", "skeleton mesh worn, run speed x1.25, Siphon in Lich mode", $"swap {LichSwapSpike.Active} ({LichSwapSpike.LastNote}), run {baseRun:0.##} -> {((Character)player).m_runSpeed:0.##}, siphon lich {NecromancerGame.Kit.Siphon.Lich}", LichSwapSpike.Active && Near(((Character)player).m_runSpeed, baseRun * (1f + nc.LichRunSpeedBonus), 0.01f) && NecromancerGame.Kit.Siphon.Lich);
			yield return LichSwapSpike.Shot("lich-form");
			float num2 = (float)AccessTools.Method(typeof(Player), "GetDodgeStaminaUse", (Type[])null, (Type[])null).Invoke(player, null);
			ChillRow("Lich Form: dodging costs no stamina", "Dodge in the form", "dodge cost 0", $"dodge cost {num2:0.##}", Near(num2, 0f, 0.001f));
			NecromancerGame.CastUltimate(player);
			TestRunner testRunner2 = this;
			UltimateResult? lastUltimate3 = NecromancerGame.LastUltimate;
			string observed2 = $"{((lastUltimate3 != null) ? new Failure?(lastUltimate3.Reason) : ((Failure?)null))}";
			UltimateResult lastUltimate4 = NecromancerGame.LastUltimate;
			testRunner2.ChillRow("A second cast is refused while the cooldown runs", "Press Y again", "refused, form unchanged", observed2, lastUltimate4 != null && !lastUltimate4.Ok && (int)lastUltimate4.Reason == 27);
			float max = ((Character)player).GetMaxHealth();
			((Character)player).SetHealth(max * 0.5f);
			NecromancerGame.Kit.Siphon.Reset();
			NecromancerGame.Kit.Siphon.Lich = true;
			NecromancerGame.LastSiphon = 0f;
			NecromancerGame.DrainForTest(player, 50f, 123456789L);
			float num3 = Mathf.Min(50f * NecromancerGame.Kit.Rules.SiphonRate(NecromancerGame.Build, (SiphonSource)0, false) * nc.LichDrainMultiplier, max * nc.SiphonHitCapPct);
			ChillRow("Lich drain: an uncursed target heals at double the spell rate", "Hit an uncursed enemy with Wither in the form", $"heals {num3:0.##} with Blood Thrift and the 5% per-hit cap", $"healed {NecromancerGame.LastSiphon:0.##}", Near(NecromancerGame.LastSiphon, num3));
			NecromancerGame.Kit.Siphon.Reset();
			NecromancerGame.Kit.Siphon.Lich = true;
			NecromancerGame.LastSiphon = 0f;
			for (int i = 0; i < 40; i++)
			{
				((Character)player).SetHealth(1f);
				NecromancerGame.DrainForTest(player, 5000f, 5L);
			}
			float lastSiphon = NecromancerGame.LastSiphon;
			ChillRow("Lich drain: the 5 s healing cap is 40% of max health", "Drain many hits at once", $"total at most {max * nc.LichWindowCapPct:0.#} (40% of {max:0.#})", $"drained {lastSiphon:0.#}", lastSiphon <= max * nc.LichWindowCapPct + 0.5f && lastSiphon >= max * nc.LichWindowCapPct - max * nc.SiphonHitCapPct - 0.5f);
			yield return (object)new WaitForSeconds(5.2f);
			NecromancerGame.Shield.Clear();
			NecromancerGame.Kit.Siphon.Reset();
			NecromancerGame.Kit.Siphon.Lich = true;
			((Character)player).SetHealth(max);
			NecromancerGame.DrainForTest(player, 5000f, 6L);
			float num4 = max * nc.SiphonHitCapPct * nc.LichShieldFillMultiplier;
			ChillRow("Healing past full health fills the Bone Shield", "Drain at full health", $"shield {num4:0.#} from capped drain, no health restored", $"shield {NecromancerGame.Shield.Pool:0.#}, overheal {NecromancerGame.LastOverheal:0.#}", Near(NecromancerGame.Shield.Pool, num4, 0.1f));
			yield return (object)new WaitForSeconds(0.6f);
			(bool On, float Fraction) playerShield = HudView.PlayerShield;
			bool item = playerShield.On;
			float item2 = playerShield.Fraction;
			float num5 = Mathf.Clamp01(NecromancerGame.Shield.Pool / max);
			ChillRow("The Bone Shield shows as a bar on the health bar", "Look at the health bar with a Bone Shield", $"bar on, covering {num5 * 100f:0.#}% of it", $"bar on {item}, covers {item2 * 100f:0.#}% (pool {NecromancerGame.Shield.Pool:0.#} of {max:0.#} health)", item && Near(item2, num5, 0.02f));
			float pool = NecromancerGame.Shield.Pool;
			float health = ((Character)player).GetHealth();
			HitData val = new HitData
			{
				m_point = ((Character)player).GetCenterPoint(),
				m_dir = Vector3.forward
			};
			val.m_damage.m_slash = pool * 0.5f;
			((Character)player).ApplyDamage(val, false, false, (DamageModifier)0);
			ChillRow("Bone Shield absorbs damage before health", "Take a hit while shielded", "pool drops by the hit, health unchanged", $"pool {pool:0.#} -> {NecromancerGame.Shield.Pool:0.#}, health {health:0.#} -> {((Character)player).GetHealth():0.#}", Near(NecromancerGame.Shield.Pool, pool * 0.5f, 0.2f) && Near(((Character)player).GetHealth(), health, 0.2f));
			NecromancerGame.Shield.Clear();
			((Character)player).SetHealth(max - 4f);
			((Character)player).Heal(10f, false);
			float pool2 = NecromancerGame.Shield.Pool;
			bool flag2 = Near(((Character)player).GetHealth(), max);
			((Character)player).Heal(2f * max, false);
			ChillRow("Ordinary healing converts only its overflow and respects the Bone Shield ceiling", "Deliver healing through the same path used by food regeneration and meads", $"4 HP restored, 6 HP converted at x{nc.LichShieldFillMultiplier:0.##}, ceiling {max * nc.LichShieldMaxPct:0.##}", $"health full={flag2}, first fill {pool2:0.##}, capped pool {NecromancerGame.Shield.Pool:0.##}", flag2 && Near(pool2, Mathf.Min(6f * nc.LichShieldFillMultiplier, max * nc.LichShieldMaxPct)) && Near(NecromancerGame.Shield.Pool, max * nc.LichShieldMaxPct));
			NecromancerBuild b = NecromancerGame.Build;
			((Character)player).SetHealth(max * 0.49f);
			double now = NecromancerGame.Now;
			NecromancerFailure why;
			bool refused = !NecromancerGame.TryRaiseOne(player, b, now, quiet: true, out why) && (int)why == 6;
			((Character)player).SetHealth(max * 0.5f);
			float lifeBefore = ((Character)player).GetHealth();
			NecromancerFailure why2;
			bool raised = NecromancerGame.TryRaiseOne(player, b, now, quiet: true, out why2);
			yield return (object)new WaitForSeconds(0.3f);
			bool raised2 = NecromancerGame.TryRaiseOne(player, b, NecromancerGame.Now + 2.0, quiet: true, out why2);
			yield return (object)new WaitForSeconds(0.5f);
			ChillRow("In the form raising a thrall costs no life", "Raise thralls with K while in Lich Form", "health unchanged after two raises", $"raised {raised}/{raised2}, health {lifeBefore:0.#} -> {((Character)player).GetHealth():0.#}", raised && raised2 && Near(((Character)player).GetHealth(), lifeBefore, 0.5f));
			ChillRow("Lich Form still requires the Raise Thrall life floor", "Attempt a free raise at 49% health, then at 50%", "49% refused, 50% succeeds with zero cost", $"49% result {why}, 50% raised={raised}", refused && raised);
			List<Character> list = NecromancerGame.ThrallList.ToList();
			if (list.Count >= 2)
			{
				Character val2 = list[0];
				Character val3 = list[1];
				((Component)val3).transform.position = ((Component)player).transform.position + ((Component)player).transform.forward * 30f;
				Physics.SyncTransforms();
				val2.SetHealth(val2.GetMaxHealth() * 0.3f);
				val3.SetHealth(val3.GetMaxHealth() * 0.3f);
				float health2 = val2.GetHealth();
				float health3 = val3.GetHealth();
				NecromancerGame.Kit.Siphon.Reset();
				NecromancerGame.Kit.Siphon.Lich = true;
				((Character)player).SetHealth(max * 0.5f);
				NecromancerGame.LastShared = 0f;
				NecromancerGame.DrainForTest(player, 50f, 7L);
				ChillRow("Healing is shared with minions within 20 m only", "Drain with thralls near and far", "the near thrall heals, the far one (30 m) does not", $"near {health2:0.#} -> {val2.GetHealth():0.#}, far {health3:0.#} -> {val3.GetHealth():0.#}, shared to {NecromancerGame.LastSharedCount}", val2.GetHealth() > health2 + 0.5f && Near(val3.GetHealth(), health3, 0.01f));
			}
			else
			{
				ChillRow("Healing is shared with minions within 20 m only", "Drain with thralls near and far", "two thralls available", $"only {list.Count} thrall(s) raised", pass: false);
			}
			Pick(n, 5, "soulreaper");
			Pick(n, 15, "hunger");
			b = NecromancerGame.Build;
			NecromancerKit kit = NecromancerGame.Kit;
			Character val4 = NecroDummy(player, "Draugr_Elite", 4f);
			long num6 = NecromancerGame.IdOf(val4);
			kit.OnWitherHit(b, NecromancerGame.Now, num6, NecromancerGame.IdOf((Character)(object)player), 0f, true, false);
			kit.Siphon.Reset();
			kit.Siphon.Lich = true;
			((Character)player).SetHealth(max * 0.5f);
			MinionStats stats = kit.ThrallStats(b, (ThrallType)2, NecromancerGame.Now);
			HitData val5 = new HitData();
			float lastSiphon2 = NecromancerGame.LastSiphon;
			NecromancerGame.OnMinionHit(val4, val5, new Minion
			{
				Kind = MinionKind.Thrall,
				Type = (ThrallType)2,
				Stats = stats
			});
			float num7 = kit.Rules.SiphonRate(b, (SiphonSource)1, true) * nc.LichDrainMultiplier;
			float num8 = Mathf.Min(val5.GetTotalDamage() * num7, max * nc.SiphonHitCapPct);
			float num9 = NecromancerGame.LastSiphon - lastSiphon2;
			ChillRow("Lich Wraith hits use the minion rate with Hunger, Blood Thrift and Soul Brand", "Drive a Wraith thrall hit on a branded target", $"minion-rate capped drain {num8:0.##}", $"drained {num9:0.##}", (int)kit.Curses.KindOf(num6).GetValueOrDefault() == 3 && num8 > 0f && Near(num9, num8));
			NecroGone(val4);
			NecromancerGame.EndLich(player, linger: false);
			NecromancerGame.Shield.Clear();
			NecroFull(player);
			NecromancerGame.Kit.Siphon.Reset();
			n.ResetUltimateCooldown();
			nc.LichSeconds = 2.0;
			nc.LichShieldLingerSeconds = 2.0;
			NecromancerGame.CastUltimate(player);
			yield return (object)new WaitForSeconds(0.5f);
			NecromancerGame.Shield.Fill(max, max, Time.timeAsDouble, 1f);
			yield return (object)new WaitForSeconds(2.4f);
			bool flag3 = !NecromancerGame.LichActive && !LichSwapSpike.Active && Near(((Character)player).m_runSpeed, baseRun, 0.01f) && !NecromancerGame.Kit.Siphon.Lich;
			float pool3 = NecromancerGame.Shield.Pool;
			ChillRow("The form ends on time: body, speed and drain restored, shield lingers", "Wait out the form", "form over, skeleton gone, run speed back, shield still up", $"form {NecromancerGame.LichActive}, swap {LichSwapSpike.Active}, run {((Character)player).m_runSpeed:0.##} (base {baseRun:0.##}), shield {pool3:0.#}", flag3 && pool3 >= max * 0.9f);
			NecromancerGame.Shield.Absorb(pool3, Time.timeAsDouble);
			((Character)player).SetHealth(max);
			((Character)player).Heal(5f, false);
			float pool4 = NecromancerGame.Shield.Pool;
			ChillRow("Ordinary overheal refills a depleted shield during linger", "Empty the pool after Lich Form ends, then heal at full HP", $"shield gains {5f * nc.LichShieldFillMultiplier:0.##}", $"shield gained {pool4:0.##}", flag3 && Near(pool4, 5f * nc.LichShieldFillMultiplier));
			yield return (object)new WaitForSeconds(2.2f);
			((Character)player).Heal(5f, false);
			ChillRow("The Bone Shield expires after its linger", "Wait out the linger", "shield gone", $"shield {NecromancerGame.Shield.Pool:0.#}", NecromancerGame.Shield.Pool <= 0.01f && !NecromancerGame.Shield.Active(Time.timeAsDouble));
			nc.LichSeconds = oldSeconds;
			nc.LichShieldLingerSeconds = oldLinger;
			n.ResetUltimateCooldown();
			NecromancerGame.CastUltimate(player);
			yield return (object)new WaitForSeconds(0.4f);
			bool onBefore = NecromancerGame.LichActive && LichSwapSpike.Active;
			SwitchResult sw = ClassSwitch.Switch("mage", resting: true);
			yield return (object)new WaitForSeconds(0.3f);
			ChillRow("Switching class ends the form at once", "Switch class while in the form", "form over, skeleton gone, speed back", $"was on {onBefore}, switch ok {((SwitchResult)(ref sw)).Ok}, form {NecromancerGame.LichActive}, swap {LichSwapSpike.Active}, run {((Character)player).m_runSpeed:0.##}", onBefore && ((SwitchResult)(ref sw)).Ok && !NecromancerGame.LichActive && !LichSwapSpike.Active && Near(((Character)player).m_runSpeed, baseRun, 0.01f));
			NecromancerGame.ResetLichForTest();
			NecromancerGame.ResetForTest();
			player.SetGodMode(true);
		}

		private IEnumerator LichSwapScenarios(Player player)
		{
			string contents = LichSwapSpike.Probe(player);
			File.WriteAllText(Path.Combine(Paths.BepInExRootPath, "retheme-lichswap-probe.txt"), contents);
			SkinnedMeshRenderer body = ((Component)player).GetComponentInChildren<VisEquipment>(true)?.m_bodyModel;
			Mesh mesh0 = (((Object)(object)body != (Object)null) ? body.sharedMesh : null);
			Material[] mats0 = (((Object)(object)body != (Object)null) ? ((Renderer)body).sharedMaterials : null);
			Transform[] bones0 = (((Object)(object)body != (Object)null) ? body.bones.ToArray() : null);
			CapsuleCollider caps = ((Component)player).GetComponent<CapsuleCollider>();
			float capH = (((Object)(object)caps != (Object)null) ? caps.height : 0f);
			Vector3 scale0 = ((Component)player).transform.localScale;
			yield return LichSwapSpike.Shot("0-before");
			bool ok = LichSwapSpike.Swap(player);
			yield return (object)new WaitForSeconds(1f);
			yield return LichSwapSpike.Shot("1-swapped");
			bool flag = (Object)(object)body != (Object)null && (Object)(object)body.sharedMesh != (Object)(object)mesh0;
			_rows.Add(new Row
			{
				Scenario = "Spike: skeleton body replaces the player body",
				Manual = "retheme_lichswap on",
				Expected = "swap applies, every skeleton bone maps onto the player rig",
				Observed = LichSwapSpike.LastNote,
				Pass = (ok && flag && LichSwapSpike.MissingBones == 0)
			});
			bool pass = (Object)(object)caps != (Object)null && Mathf.Approximately(caps.height, capH) && ((Component)player).transform.localScale == scale0;
			List<Row> rows = _rows;
			Row obj = new Row
			{
				Scenario = "Spike: collider and scale unchanged during the swap",
				Manual = "n/a",
				Expected = "capsule height and scale equal"
			};
			obj.Observed = $"height {((caps != null) ? new float?(caps.height) : ((float?)null))} (was {capH}), scale {((Component)player).transform.localScale}";
			obj.Pass = pass;
			rows.Add(obj);
			Inventory inventory = ((Humanoid)player).GetInventory();
			ItemData val = inventory.AddItem("SwordBronze", 1, 1, 0, 0L, "", false, false);
			ItemData val2 = inventory.AddItem("ShieldWood", 1, 1, 0, 0L, "", false, false);
			if (val != null)
			{
				((Humanoid)player).EquipItem(val, false);
			}
			if (val2 != null)
			{
				((Humanoid)player).EquipItem(val2, false);
			}
			yield return (object)new WaitForSeconds(1.5f);
			VisEquipment componentInChildren = ((Component)player).GetComponentInChildren<VisEquipment>(true);
			GameObject right = Traverse.Create((object)componentInChildren).Field("m_rightItemInstance").GetValue<GameObject>();
			GameObject left = Traverse.Create((object)componentInChildren).Field("m_leftItemInstance").GetValue<GameObject>();
			bool attached = (Object)(object)right != (Object)null && right.activeInHierarchy && (Object)(object)left != (Object)null && left.activeInHierarchy && right.transform.IsChildOf(((Component)player).transform) && left.transform.IsChildOf(((Component)player).transform);
			yield return LichSwapSpike.Shot("3-armed");
			_rows.Add(new Row
			{
				Scenario = "Spike: weapon and shield attach to the skeleton body",
				Manual = "Wield a sword and shield while swapped",
				Expected = "both instances active under the player's hand bones",
				Observed = "right " + (((Object)(object)right != (Object)null) ? ((Object)right.transform.parent).name : "none") + ", left " + (((Object)(object)left != (Object)null) ? ((Object)left.transform.parent).name : "none"),
				Pass = attached
			});
			Animator anim = ((Component)player).GetComponentInChildren<Animator>(true);
			bool attacked = ((Character)player).StartAttack((Character)null, false);
			yield return (object)new WaitForSeconds(0.25f);
			yield return LichSwapSpike.Shot("4-attack");
			bool inAttack = ((Character)player).InAttack();
			yield return (object)new WaitForSeconds(1.2f);
			List<Row> rows2 = _rows;
			Row obj2 = new Row
			{
				Scenario = "Spike: attack animation plays on the skeleton body",
				Manual = "Swing the sword while swapped",
				Expected = "attack starts and the animator runs it (see screenshot 4-attack)"
			};
			obj2.Observed = $"started {attacked}, in attack {inAttack}, animator speed {((anim != null) ? new float?(anim.speed) : ((float?)null))}";
			obj2.Pass = attacked && inAttack;
			rows2.Add(obj2);
			LichSwapSpike.Restore(player);
			yield return (object)new WaitForSeconds(0.5f);
			yield return LichSwapSpike.Shot("2-restored");
			bool flag2 = (Object)(object)body != (Object)null && (Object)(object)body.sharedMesh == (Object)(object)mesh0 && ((Renderer)body).sharedMaterials.SequenceEqual(mats0) && body.bones.SequenceEqual(bones0);
			_rows.Add(new Row
			{
				Scenario = "Spike: restore returns the original body",
				Manual = "retheme_lichswap off",
				Expected = "mesh, materials and bone map identical to before",
				Observed = $"identical {flag2}",
				Pass = flag2
			});
			bool ok2 = LichSwapSpike.Swap(player);
			yield return (object)new WaitForSeconds(0.5f);
			LichSwapSpike.Restore(player);
			yield return (object)new WaitForSeconds(0.5f);
			bool flag3 = (Object)(object)body != (Object)null && (Object)(object)body.sharedMesh == (Object)(object)mesh0 && ((Renderer)body).sharedMaterials.SequenceEqual(mats0) && body.bones.SequenceEqual(bones0) && ok2;
			_rows.Add(new Row
			{
				Scenario = "Spike: a second swap and restore cycle leaves nothing behind",
				Manual = "Toggle twice",
				Expected = "second cycle applies and restores identically",
				Observed = $"second swap {ok2}, restored {flag3}",
				Pass = flag3
			});
			LichSwapSpike.Swap(player);
			CharacterState state = RethemePlugin.State;
			SwitchResult sw = ClassSwitch.Switch((state.ActiveClassId == "mage") ? "berserker" : "mage", resting: true);
			yield return (object)new WaitForSeconds(0.3f);
			bool flag4 = !LichSwapSpike.Active && (Object)(object)body != (Object)null && (Object)(object)body.sharedMesh == (Object)(object)mesh0;
			_rows.Add(new Row
			{
				Scenario = "Spike: switching class restores the body",
				Manual = "Switch class while swapped",
				Expected = "swap cleared and original mesh back",
				Observed = $"switch ok {((SwitchResult)(ref sw)).Ok}, active {LichSwapSpike.Active}",
				Pass = (((SwitchResult)(ref sw)).Ok && flag4)
			});
			ClassSwitch.Switch("mage", resting: true);
			player.SetGodMode(false);
			LichSwapSpike.Swap(player);
			yield return (object)new WaitForSeconds(0.3f);
			HitData val3 = new HitData();
			val3.m_damage.m_damage = 100000f;
			val3.m_point = ((Character)player).GetCenterPoint();
			((Character)player).Damage(val3);
			yield return (object)new WaitForSeconds(0.5f);
			bool activeAfterDeath = LichSwapSpike.Active;
			float waited = 0f;
			while (waited < 30f)
			{
				yield return (object)new WaitForSeconds(1f);
				waited += 1f;
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null && (Object)(object)localPlayer != (Object)(object)player && !((Character)localPlayer).IsDead() && (Object)(object)ZNetScene.instance != (Object)null)
				{
					break;
				}
			}
			Player localPlayer2 = Player.m_localPlayer;
			SkinnedMeshRenderer freshBody = ((!((Object)(object)localPlayer2 != (Object)null)) ? null : ((Component)localPlayer2).GetComponentInChildren<VisEquipment>(true)?.m_bodyModel);
			bool respawned = (Object)(object)localPlayer2 != (Object)null && (Object)(object)localPlayer2 != (Object)(object)player && !((Character)localPlayer2).IsDead();
			bool freshOk = respawned && !LichSwapSpike.Active && (Object)(object)freshBody != (Object)null && (Object)(object)freshBody.sharedMesh != (Object)null && ((Object)freshBody.sharedMesh).name != "Skeleton";
			if (respawned)
			{
				localPlayer2.SetGodMode(true);
				yield return (object)new WaitForSeconds(1f);
				ClearClutter();
			}
			List<Row> rows3 = _rows;
			Row obj3 = new Row
			{
				Scenario = "Spike: death and respawn leave a normal body",
				Manual = "Die while swapped, respawn",
				Expected = "swap cleared at death; respawned body shows the player mesh"
			};
			obj3.Observed = string.Format("active at death {0}, respawned {1}, mesh {2}", activeAfterDeath, respawned, ((Object)(object)((freshBody != null) ? freshBody.sharedMesh : null) != (Object)null) ? ((Object)freshBody.sharedMesh).name : "none");
			obj3.Pass = !activeAfterDeath && freshOk;
			rows3.Add(obj3);
		}

		private IEnumerator MageUltimateScenarios(Player player, CharacterState mage)
		{
			MageConfig cfg = RethemePlugin.Config;
			CharacterState ult = CharacterState.CreateNew((ProgressionConfig)(object)cfg, (ClassRegistry)null);
			ult.SwitchClass("mage", true);
			FakeInventory fakeInventory = new FakeInventory(((ProgressionConfig)cfg).PromotionTrophies);
			for (int i = 0; i < 5; i++)
			{
				ult.GrantCombatXp(268435455);
				ult.Promote((IInventory)(object)fakeInventory, true);
			}
			ult.GrantCombatXp(268435455);
			Select(ult, 1, "caster");
			Select(ult, 5, "fire");
			RethemePlugin.State = ult;
			yield return (object)new WaitForSeconds(0.3f);
			((Character)player).Heal(((Character)player).GetMaxHealth(), false);
			((Character)player).AddEitr(10000f);
			int num = MageUltimate.CataclysmCasts + MageUltimate.AvatarCasts;
			MageUltimate.Cast(player);
			ChillRow("Mage level 50 ultimate: an unpicked slot casts nothing", "Reach level 50 and press the ultimate key before picking", "no cast, no cooldown, pick pending", $"level {ult.Level}, casts {MageUltimate.CataclysmCasts + MageUltimate.AvatarCasts - num}, cooldown {ult.UltimateCooldownEndUnix}, pending {ult.UltimatePickPending}", ult.Level == 50 && MageUltimate.CataclysmCasts + MageUltimate.AvatarCasts == num && ult.UltimateCooldownEndUnix == 0L && ult.UltimatePickPending);
			Pick(ult, 50, "cataclysm");
			Vector3 point;
			List<GameObject> near = SpawnCluster(player, 3, out point, "Boar", 9f);
			List<GameObject> far = SpawnCluster(player, 1, out point, "Boar", cfg.CataclysmRadius + 8f);
			yield return (object)new WaitForSeconds(0.3f);
			float farHp = far[0].GetComponent<Character>().GetHealth();
			yield return (object)new WaitForSeconds(1.2f);
			((Character)player).AddEitr(10000f);
			MageUltimate.LastTargets = -1;
			MageUltimate.Cast(player);
			yield return (object)new WaitForSeconds((float)(cfg.CataclysmWaveDelaySeconds * (double)(cfg.CataclysmWaves - 1)) + 0.5f);
			bool flag = (Object)(object)far[0] == (Object)null || Near(far[0].GetComponent<Character>().GetHealth(), farHp, 0.01f);
			long num2 = ult.UltimateCooldownSecondsRemaining(DateTimeOffset.UtcNow);
			CommandResult val = ult.SelectTalent(50, "avatar", true, DateTimeOffset.UtcNow);
			bool flag2 = (int)((CommandResult)(ref val)).Reason == 27;
			ChillRow("Cataclysm: a huge tri-element blast, reaching 12 m and no further", "Pick Cataclysm, press the ultimate key among enemies", $"{cfg.CataclysmWaves} waves of {cfg.CataclysmDamage * cfg.CataclysmWaveFraction:0} (more as a Caster) on the three boars at 9 m, spares the one beyond 12 m, {cfg.CataclysmCooldownSeconds} s cooldown, swap blocked", $"waves {MageUltimate.WavesFired}, hit {MageUltimate.LastTargets}, wave damage {MageUltimate.LastDamage:0.#}, far boar untouched {flag}, cooldown {num2}s, swap blocked {flag2}, Eitr spent {MageUltimate.LastEitrSpent:0.#} of {((Character)player).GetMaxEitr():0.#}", Near(MageUltimate.LastEitrSpent, cfg.CataclysmEitrFraction * ((Character)player).GetMaxEitr(), 1f) && MageUltimate.WavesFired == cfg.CataclysmWaves && MageUltimate.LastTargets >= 3 && MageUltimate.LastDamage >= cfg.CataclysmDamage * cfg.CataclysmWaveFraction && flag && num2 > 0 && num2 <= cfg.CataclysmCooldownSeconds && flag2);
			ClearHostiles(near);
			ClearHostiles(far);
			ult.ResetUltimateCooldown();
			Pick(ult, 50, "avatar");
			double was = cfg.AvatarSeconds;
			cfg.AvatarSeconds = 1.5;
			MageUltimate.Cast(player);
			yield return (object)new WaitForSeconds(0.6f);
			int count = PetManager.Avatar.Count;
			int kinds = PetManager.Avatar.Values.Select(((PetKind Kind, double Until) v) => v.Kind).Distinct().Count();
			bool normalUntouched = (Object)(object)PetManager.Current == (Object)null;
			yield return (object)new WaitForSeconds(1.8f);
			bool flag3 = PetManager.Avatar.Count == 0;
			ChillRow("Avatar: fire, frost and lightning companions together, then they fade", "Pick Avatar and press the ultimate key", $"three companions, one of each element, gone after {cfg.AvatarSeconds:0.#} s, normal companion unaffected", $"count {count}, distinct elements {kinds}, normal companion untouched {normalUntouched}, faded {flag3}", count == 3 && kinds == 3 && normalUntouched && flag3);
			cfg.AvatarSeconds = was;
			RethemePlugin.State = mage;
			((Character)player).Heal(((Character)player).GetMaxHealth(), false);
		}

		private IEnumerator NecromancerDeathsMightScenarios(Player player)
		{
			CharacterState state = NewNecro(RethemePlugin.Config, 4);
			state.SetProgressForTesting(50, 10000000L);
			RethemePlugin.State = state;
			NecromancerConfig cfg = NecromancerGame.Config;
			Pick(state, 1, "hexer");
			Pick(state, 5, "bonecaller");
			Pick(state, 20, "revenant");
			Pick(state, 30, "revenant_berserker");
			Pick(state, 40, "greater_revenant");
			Pick(state, 50, "lich_form");
			ClearHostiles();
			yield return null;
			InventoryGui gui = InventoryGui.instance;
			bool wasVisible = InventoryGui.IsVisible();
			bool wasResting = SpellbookDialog.ForceResting;
			int initialPoints = state.PointsAvailable;
			try
			{
				(float Health, float Damage) baseline = default((float, float));
				int[] array = new int[2] { 0, 6 };
				foreach (int ranks in array)
				{
					if (ranks > 0)
					{
						if ((Object)(object)gui != (Object)null)
						{
							SpellbookDialog.ForceResting = true;
							SpellbookDialog.Open(gui);
							SpellbookDialog.SelectTab(1);
							bool opened = SpellbookDialog.IsOpen && SpellbookDialog.Click("Death's Might");
							yield return null;
							yield return null;
							bool text = SpellbookDialog.Has("Each rank adds " + (cfg.DeathsMightStep * 100f).ToString("0.##", CultureInfo.InvariantCulture) + "%") && SpellbookDialog.Has("Bone Shield fill speed");
							bool clicked = opened && text && SpellbookDialog.Click("Buy rank 1");
							yield return null;
							yield return null;
							bool flag = clicked && state.ActiveState.Spent["deaths_might"] == 1;
							ChillRow("Death's Might opens in the Spellbook at class rank 4", "Open the fourth mastery and buy its first rank while resting", "per-rank effects shown and one point spent", string.Format("opened={0}, effects={1}, purchased={2}", opened, text, state.ActiveState.Spent["deaths_might"]), flag && state.PointsAvailable == initialPoints - 1);
							SpellbookDialog.Close();
							if (!wasVisible)
							{
								gui.Hide();
							}
						}
						else
						{
							ChillRow("Death's Might opens in the Spellbook at class rank 4", "Open Mastery", "dialog available", "no inventory GUI", pass: false);
						}
						for (int j = state.ActiveState.Spent["deaths_might"]; j < ranks; j++)
						{
							state.PurchaseMastery("deaths_might", true);
						}
					}
					double num = (double)ranks * 0.04;
					float num2 = (float)(1.0 + num);
					state.ResetUltimateCooldown();
					Pick(state, 20, "revenant");
					Pick(state, 30, "revenant_berserker");
					Pick(state, 40, "greater_revenant");
					Pick(state, 50, "lich_form");
					NecromancerGame.ResetForTest();
					NecromancerBuild build = NecromancerGame.Build;
					NecroFull(player);
					double now = NecromancerGame.Now;
					NecromancerGame.CastRevenant(player, build, now);
					Character revenantChar = NecromancerGame.RevenantChar;
					Character val = NecroDummy(player, "Draugr_Elite", 3f);
					float num3 = ((revenantChar != null) ? revenantChar.GetMaxHealth() : 0f);
					float num4 = 0f;
					bool flag2 = false;
					if ((Object)(object)revenantChar != (Object)null)
					{
						((Component)val).transform.position = ((Component)revenantChar).transform.position + ((Component)player).transform.forward * 1.5f;
						Physics.SyncTransforms();
						revenantChar.SetHealth(num3 * 0.7f);
						NecromancerGame.Kit.RevenantLineage.OnDamageTaken(build, now);
						HitData val2 = new HitData();
						val2.SetAttacker(revenantChar);
						NecromancerGame.OnMinionHit(val, val2, NecromancerGame.ByChar[revenantChar]);
						num4 = val2.GetTotalDamage();
						NecromancerGame.TickRevenant(player, build, now);
						double num5 = cfg.RevenantSlamCooldown * (1.0 - num);