Decompiled source of Vendetta v0.2.1

Vendetta.dll

Decompiled 10 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Steamworks;
using UnityEngine;
using Vendetta.Game;

[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("Vendetta")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Vendetta")]
[assembly: AssemblyTitle("Vendetta")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "This assembly was partially or fully created with the assistance of Generative AI (code and documentation).")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic (Claude, through Claude Code)")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Vendetta
{
	public struct Vec3
	{
		public float X;

		public float Y;

		public float Z;

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

		public static float Distance(Vec3 a, Vec3 b)
		{
			float num = a.X - b.X;
			float num2 = a.Y - b.Y;
			float num3 = a.Z - b.Z;
			return (float)Math.Sqrt(num * num + num2 * num2 + num3 * num3);
		}

		public override string ToString()
		{
			return "(" + X + ", " + Y + ", " + Z + ")";
		}
	}
	public enum Zone
	{
		Field,
		Wall,
		Courtyard,
		Mine
	}
	public interface IGamePlayer
	{
		string Id { get; }

		string Name { get; }

		bool IsDowned { get; }

		float MaxHealth { get; }

		Vec3 Position { get; }

		Zone Zone { get; }
	}
	public interface IGameMonster
	{
		int Id { get; }

		string TypeName { get; }

		bool IsAlive { get; }

		float MaxHealth { get; }

		Vec3 Position { get; }

		Zone Zone { get; }
	}
	public interface IGameBridge
	{
		bool IsHost { get; }

		void Tick(float dt);

		void ForceTarget(IGameMonster monster, IGamePlayer player);

		void SetAttackInterval(IGameMonster monster, float seconds);

		void Heal(IGameMonster monster, float amount);

		void Empower(IGameMonster monster, float sizeMultiplier, float healthMultiplier);

		bool NeedsLeap(IGameMonster monster, IGamePlayer target);

		bool NeedsLeapTo(IGameMonster monster, Vec3 point);

		bool CanWalkTo(IGameMonster monster, Vec3 point);

		bool CanHit(IGameMonster monster, IGamePlayer player);

		bool TryFindWallPoint(IGameMonster monster, out Vec3 point);

		bool HasReached(IGameMonster monster, Vec3 point);

		void PlayTelegraph(IGameMonster monster, float seconds);

		void CancelTelegraph(IGameMonster monster);

		bool Leap(IGameMonster monster, Vec3 destination);

		bool IsLeaping(IGameMonster monster);

		bool TryFindLanding(IGameMonster monster, Vec3 near, out Vec3 point);

		bool TryFindMineEntrance(out Vec3 point);

		void Guard(IGameMonster monster, Vec3 point, bool fight);

		void HuntKing(IGameMonster monster);

		bool TryFindKing(out Vec3 position);

		void ReleaseTarget(IGameMonster monster);

		void GrantOre(IGamePlayer player, int amount);

		void LoseRun();
	}
	public enum NemesisPerk
	{
		None,
		WallBreaker,
		TunnelStalker,
		ThickHide
	}
	[Serializable]
	public class NemesisRecord
	{
		public string MonsterName;

		public string MonsterType;

		public string TargetPlayerId;

		public string TargetPlayerName;

		public float CarriedHits;

		public NemesisPerk Perk;

		public int TimesReturned;

		public long CreatedUtcTicks;

		public static NemesisPerk PerkForKillZone(Zone zone)
		{
			return zone switch
			{
				Zone.Wall => NemesisPerk.WallBreaker, 
				Zone.Mine => NemesisPerk.TunnelStalker, 
				_ => NemesisPerk.ThickHide, 
			};
		}

		public static string PerkLabel(NemesisPerk perk)
		{
			return perk switch
			{
				NemesisPerk.WallBreaker => "Wall-Breaker", 
				NemesisPerk.TunnelStalker => "Tunnel Stalker", 
				NemesisPerk.ThickHide => "Thick Hide", 
				_ => "", 
			};
		}
	}
	public class NemesisRoster
	{
		private readonly List<NemesisRecord> _records = new List<NemesisRecord>();

		public IList<NemesisRecord> Records => _records.AsReadOnly();

		public void Add(NemesisRecord record, int maxActive)
		{
			_records.RemoveAll((NemesisRecord r) => r.MonsterName == record.MonsterName);
			_records.Add(record);
			while (maxActive > 0 && _records.Count > maxActive)
			{
				NemesisRecord item = _records.OrderBy((NemesisRecord r) => r.CreatedUtcTicks).First();
				_records.Remove(item);
			}
		}

		public bool Remove(string monsterName)
		{
			return _records.RemoveAll((NemesisRecord r) => r.MonsterName == monsterName) > 0;
		}

		public NemesisRecord FindForPlayers(IEnumerable<string> playerIds, ICollection<string> excludeNames)
		{
			HashSet<string> ids = new HashSet<string>(playerIds);
			return (from r in _records
				where ids.Contains(r.TargetPlayerId) && (excludeNames == null || !excludeNames.Contains(r.MonsterName))
				orderby r.CreatedUtcTicks
				select r).FirstOrDefault();
		}

		public string Save()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("# Vendetta nemeses: name|type|targetId|targetName|carriedHits|perk|timesReturned|createdTicks");
			foreach (NemesisRecord record in _records)
			{
				stringBuilder.AppendLine(string.Join("|", Esc(record.MonsterName), Esc(record.MonsterType), Esc(record.TargetPlayerId), Esc(record.TargetPlayerName), record.CarriedHits.ToString(CultureInfo.InvariantCulture), record.Perk.ToString(), record.TimesReturned.ToString(CultureInfo.InvariantCulture), record.CreatedUtcTicks.ToString(CultureInfo.InvariantCulture)));
			}
			return stringBuilder.ToString();
		}

		public static NemesisRoster Load(string text)
		{
			NemesisRoster nemesisRoster = new NemesisRoster();
			if (string.IsNullOrEmpty(text))
			{
				return nemesisRoster;
			}
			string[] array = text.Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].TrimEnd('\r');
				if (text2.Length == 0 || text2[0] == '#')
				{
					continue;
				}
				string[] array2 = text2.Split('|');
				if (array2.Length >= 8)
				{
					try
					{
						nemesisRoster._records.Add(new NemesisRecord
						{
							MonsterName = Unesc(array2[0]),
							MonsterType = Unesc(array2[1]),
							TargetPlayerId = Unesc(array2[2]),
							TargetPlayerName = Unesc(array2[3]),
							CarriedHits = float.Parse(array2[4], CultureInfo.InvariantCulture),
							Perk = (NemesisPerk)Enum.Parse(typeof(NemesisPerk), array2[5]),
							TimesReturned = int.Parse(array2[6], CultureInfo.InvariantCulture),
							CreatedUtcTicks = long.Parse(array2[7], CultureInfo.InvariantCulture)
						});
					}
					catch (Exception)
					{
					}
				}
			}
			return nemesisRoster;
		}

		private static string Esc(string s)
		{
			return (s ?? "").Replace("\\", "\\\\").Replace("|", "\\p").Replace("\n", "\\n")
				.Replace("\r", "");
		}

		private static string Unesc(string s)
		{
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < s.Length; i++)
			{
				if (s[i] == '\\' && i + 1 < s.Length)
				{
					char c = s[++i];
					stringBuilder.Append(c switch
					{
						'n' => '\n', 
						'p' => '|', 
						_ => c, 
					});
				}
				else
				{
					stringBuilder.Append(s[i]);
				}
			}
			return stringBuilder.ToString();
		}
	}
	public static class MonsterNames
	{
		private static readonly string[] First = new string[16]
		{
			"Grubnak", "Skarr", "Mogg", "Vrask", "Thul", "Gorza", "Krell", "Uzgob", "Ratch", "Bolg",
			"Snikrat", "Durza", "Ghorm", "Yazgul", "Brakka", "Nurk"
		};

		private static readonly string[] Epithet = new string[10] { "the Beard-Taker", "Dwarfbane", "the Grudgeholder", "Stonebiter", "the Patient", "Ironjaw", "the Unforgiving", "Axe-Eater", "the Long Memory", "Kingsbane" };

		public static string Generate(Random rng)
		{
			return First[rng.Next(First.Length)] + " " + Epithet[rng.Next(Epithet.Length)];
		}
	}
	public enum LeapGoal
	{
		Dwarf,
		Mine,
		King
	}
	public class VendettaState
	{
		public IGameMonster Monster;

		public IGamePlayer Target;

		public string MonsterName;

		public bool IsGreedWave;

		public bool IsNemesis;

		public NemesisPerk Perk;

		public VendettaStacks Stacks;

		public VendettaRegen Regen;

		public float TelegraphRemaining;

		public float LeapCooldown;

		public float MineChaseTimer = -1f;

		public LeapGoal LeapGoal;

		public bool HuntingKing;

		public bool AtWallOnly;

		public bool HasWallPoint;

		public Vec3 WallPoint;

		public Vec3 WallGoal;

		public float ShelterRemaining = -1f;

		public bool Sheltered;

		public bool ShelterAnnounced;

		public bool ShelterWarned;

		public bool WaitingAtMine;

		public bool ArrivedAtMine;

		public float MineTravelTime;

		public bool HasWaitPoint;

		public Vec3 WaitPoint;

		public float MineWaitTimer;

		public int LastAppliedStep = -1;

		public float RetargetTimer;

		public bool DownedItsTarget;

		public Zone KillZone;

		public NemesisRecord SourceRecord;
	}
	public class VendettaDirector
	{
		private const float LeapCooldownSeconds = 6f;

		private const float RetargetInterval = 0.5f;

		private readonly IGameBridge _bridge;

		private readonly Func<VendettaSettings> _settings;

		private readonly Random _rng;

		private readonly VendettaTargeting _targeting;

		private readonly Dictionary<string, PlayerWaveStats> _accumulating = new Dictionary<string, PlayerWaveStats>();

		private IList<IGamePlayer> _players = new List<IGamePlayer>();

		private bool _waveActive;

		private int _wave;

		private bool _runLost;

		private bool _nemesisReturnedThisRun;

		private IList<string> _waveTypes = new List<string>();

		private VendettaState _slainGrudge;

		private IGamePlayer _pendingTarget;

		private bool _pendingGreed;

		private NemesisRecord _pendingNemesis;

		private const float MineTravelSeconds = 60f;

		public NemesisRoster Roster { get; private set; }

		public VendettaState Current { get; private set; }

		public IGamePlayer DownedTarget { get; private set; }

		public float ReviveRemaining { get; private set; }

		public bool ReviveSecured { get; private set; }

		public event Action<string, string> Announce;

		public event Action RosterChanged;

		public event Action<string, string, bool> VendettaSlain;

		public VendettaDirector(IGameBridge bridge, Func<VendettaSettings> settings, NemesisRoster roster, Random rng = null)
		{
			_bridge = bridge;
			_settings = settings;
			_rng = rng ?? new Random();
			_targeting = new VendettaTargeting(settings, _rng);
			Roster = roster ?? new NemesisRoster();
		}

		public void OnRunStarted()
		{
			_targeting.ResetForNewRun();
			_accumulating.Clear();
			_nemesisReturnedThisRun = false;
			_runLost = false;
			_waveActive = false;
			Current = null;
			_waveTypes = new List<string>();
			_slainGrudge = null;
			ClearRevive();
		}

		public void OnWaveStarted(int waveNumber, IList<IGamePlayer> players, IList<string> monsterTypes = null)
		{
			if (!_bridge.IsHost)
			{
				return;
			}
			VendettaSettings vendettaSettings = _settings();
			_players = players ?? new List<IGamePlayer>();
			bool num = _waveActive && Current != null && Current.Monster.IsAlive;
			FlushSlainGrudge();
			_waveActive = true;
			_wave = waveNumber;
			_waveTypes = monsterTypes ?? new List<string>();
			if (num)
			{
				return;
			}
			Current = null;
			List<IGamePlayer> list = _players.Where((IGamePlayer p) => !p.IsDowned).ToList();
			List<PlayerWaveStats> players2 = list.Select(delegate(IGamePlayer p)
			{
				_accumulating.TryGetValue(p.Id, out var value);
				return new PlayerWaveStats
				{
					PlayerId = p.Id,
					DisplayName = p.Name,
					DamageDealt = (value?.DamageDealt ?? 0f),
					OreMined = (value?.OreMined ?? 0f)
				};
			}).ToList();
			_accumulating.Clear();
			_pendingTarget = null;
			_pendingNemesis = null;
			_pendingGreed = false;
			if (list.Count == 0)
			{
				return;
			}
			if (vendettaSettings.NemesisEnabled && !_nemesisReturnedThisRun && waveNumber >= vendettaSettings.NemesisEarliestWave)
			{
				NemesisRecord rec = Roster.FindForPlayers(list.Select((IGamePlayer p) => p.Id), null);
				if (rec != null)
				{
					_pendingNemesis = rec;
					_pendingTarget = list.First((IGamePlayer p) => p.Id == rec.TargetPlayerId);
					return;
				}
			}
			VendettaPick pick = _targeting.Pick(waveNumber, players2);
			_pendingTarget = list.First((IGamePlayer p) => p.Id == pick.Target.PlayerId);
			_pendingGreed = pick.IsGreedWave;
		}

		public void OnMonsterSpawned(IGameMonster monster)
		{
			if (!_bridge.IsHost || !_waveActive || Current != null || _pendingTarget == null || monster == null || monster.Zone == Zone.Mine)
			{
				return;
			}
			_settings();
			IGamePlayer pendingTarget = _pendingTarget;
			NemesisRecord pendingNemesis = _pendingNemesis;
			if (pendingNemesis == null || !_waveTypes.Contains(pendingNemesis.MonsterType) || !(monster.TypeName != pendingNemesis.MonsterType))
			{
				VendettaState vendettaState = (Current = new VendettaState
				{
					Monster = monster,
					Target = pendingTarget,
					IsGreedWave = _pendingGreed,
					IsNemesis = (pendingNemesis != null),
					SourceRecord = pendingNemesis,
					Perk = (pendingNemesis?.Perk ?? NemesisPerk.None),
					MonsterName = ((pendingNemesis != null) ? pendingNemesis.MonsterName : MonsterNames.Generate(_rng)),
					Stacks = new VendettaStacks(_settings, pendingNemesis?.CarriedHits ?? 0f),
					Regen = new VendettaRegen(_settings)
				});
				_pendingTarget = null;
				if (pendingNemesis != null)
				{
					_bridge.Empower(monster, 1.3f, (pendingNemesis.Perk == NemesisPerk.ThickHide) ? 1.5f : 1.2f);
					pendingNemesis.TimesReturned++;
					_nemesisReturnedThisRun = true;
					RaiseRosterChanged();
					Say(vendettaState.MonsterName + " has returned for you. (" + NemesisRecord.PerkLabel(pendingNemesis.Perk) + ")", pendingTarget.Id);
					Say("Nemesis! " + vendettaState.MonsterName + " is back for " + pendingTarget.Name + ".", null);
				}
				else
				{
					Say(vendettaState.MonsterName + " has sworn a vendetta against you!", pendingTarget.Id);
					Say(vendettaState.MonsterName + " hunts " + pendingTarget.Name + (vendettaState.IsGreedWave ? " (Greed)" : "") + ".", null);
				}
				ApplyAttackInterval(vendettaState);
				if (vendettaState.IsGreedWave && pendingTarget.Zone == Zone.Mine)
				{
					vendettaState.MineChaseTimer = 0f;
				}
			}
		}

		public void OnWaveEnded()
		{
			if (_bridge.IsHost)
			{
				VendettaState current = Current;
				if (current != null && current.DownedItsTarget && current.Monster.IsAlive)
				{
					CreateNemesis(current, "escaped");
				}
				FlushSlainGrudge();
				Current = null;
				_waveActive = false;
				_pendingTarget = null;
			}
		}

		public void OnRunEnded()
		{
			VendettaState current = Current;
			if (current != null && current.DownedItsTarget && current.Monster.IsAlive)
			{
				CreateNemesis(current, "triumphed");
			}
			FlushSlainGrudge();
			Current = null;
			_waveActive = false;
			ClearRevive();
		}

		public void RecordDamageDealt(IGamePlayer player, float amount)
		{
			if (player != null && !(amount <= 0f))
			{
				Acc(player).DamageDealt += amount;
			}
		}

		public void RecordOreMined(IGamePlayer player, float amount)
		{
			if (player != null && !(amount <= 0f))
			{
				Acc(player).OreMined += amount;
			}
		}

		public float ModifyHitDamage(IGameMonster monster, IGamePlayer player, bool blocked, float baseDamage)
		{
			VendettaState current = Current;
			if (current == null || monster == null || player == null || monster.Id != current.Monster.Id || player.Id != current.Target.Id)
			{
				return baseDamage;
			}
			if (!blocked)
			{
				return current.Stacks.DamageAgainst(player.MaxHealth, blocked: false);
			}
			return baseDamage;
		}

		public void OnHitLanded(IGameMonster monster, IGamePlayer player, bool blocked)
		{
			VendettaState c = Current;
			if (c != null && monster != null && player != null && monster.Id == c.Monster.Id && !(player.Id != c.Target.Id))
			{
				Grow(c, delegate
				{
					c.Stacks.RegisterHitOnTarget(blocked);
				});
			}
		}

		private void Grow(VendettaState c, Action add)
		{
			bool num = c.Stacks.Hits >= _settings().MaxHits;
			add();
			ApplyAttackInterval(c);
			if (!num && c.Stacks.Hits >= _settings().MaxHits)
			{
				Say(c.MonsterName + " is in a full fury!", null);
			}
		}

		public void OnMonsterDamaged(IGameMonster monster, IGamePlayer byPlayer, float amount)
		{
			RecordDamageDealt(byPlayer, amount);
			VendettaState current = Current;
			if (current != null && monster != null && monster.Id == current.Monster.Id)
			{
				current.Regen.OnDamagedByPlayer();
			}
		}

		public void OnMonsterKilled(IGameMonster monster, IGamePlayer killer)
		{
			VendettaState current = Current;
			if (current == null || monster == null || monster.Id != current.Monster.Id)
			{
				return;
			}
			VendettaSettings vendettaSettings = _settings();
			bool flag = killer != null && killer.Id == current.Target.Id;
			bool flag2 = current.Stacks.Hits < vendettaSettings.MaxHits;
			int num = vendettaSettings.RewardOnWave(vendettaSettings.TargetKillBonusOre, _wave);
			int num2 = vendettaSettings.RewardOnWave(vendettaSettings.GroupKillBonusOre, _wave);
			if (flag && num > 0)
			{
				_bridge.GrantOre(current.Target, num);
				Say(current.Target.Name + " avenged themselves against " + current.MonsterName + "! (+" + num + " ore)", null);
			}
			else
			{
				Say(current.MonsterName + " has fallen.", null);
			}
			if (flag2 && num2 > 0)
			{
				foreach (IGamePlayer player in _players)
				{
					_bridge.GrantOre(player, num2);
				}
				Say("Slain before its full fury: +" + num2 + " ore each.", null);
			}
			if (current.IsNemesis && Roster.Remove(current.MonsterName))
			{
				Say(current.MonsterName + "'s grudge is ended.", null);
				RaiseRosterChanged();
			}
			else if (current.DownedItsTarget)
			{
				_slainGrudge = current;
			}
			this.VendettaSlain?.Invoke(current.MonsterName, current.Target.Name, flag);
			Current = null;
		}

		public void OnPlayerDowned(IGamePlayer player, IGameMonster byMonster)
		{
			VendettaState current = Current;
			if (!_bridge.IsHost || current == null || player == null || player.Id != current.Target.Id || _runLost)
			{
				return;
			}
			if (byMonster != null && byMonster.Id == current.Monster.Id)
			{
				current.DownedItsTarget = true;
				current.KillZone = player.Zone;
			}
			VendettaSettings vendettaSettings = _settings();
			if (vendettaSettings.Loss == LossMode.InstantLoss)
			{
				if (current.DownedItsTarget)
				{
					CreateNemesis(current, "triumphed");
				}
				LoseRun(player.Name + " has fallen. The stronghold is lost.");
			}
			else
			{
				DownedTarget = player;
				ReviveSecured = false;
				ReviveRemaining = vendettaSettings.ReviveWindowSeconds;
				Say(player.Name + " is down! Revive them within " + (int)vendettaSettings.ReviveWindowSeconds + "s or the stronghold falls!", null);
			}
		}

		public void OnRevivePlaced(IGamePlayer player)
		{
			if (DownedTarget != null && player != null && !(player.Id != DownedTarget.Id) && !ReviveSecured)
			{
				ReviveSecured = true;
				Say(player.Name + " is being revived. The clock is stopped!", null);
			}
		}

		public void OnPlayerRevived(IGamePlayer player)
		{
			if (DownedTarget != null && player != null && !(player.Id != DownedTarget.Id))
			{
				Say(player.Name + " is back on their feet!", null);
				ClearRevive();
			}
		}

		public void Tick(float dt)
		{
			if (!_bridge.IsHost || dt <= 0f)
			{
				return;
			}
			VendettaSettings vendettaSettings = _settings();
			_bridge.Tick(dt);
			if (DownedTarget != null && !ReviveSecured && !_runLost)
			{
				ReviveRemaining -= dt;
				if (ReviveRemaining <= 0f)
				{
					VendettaState current = Current;
					if (current != null && current.DownedItsTarget)
					{
						CreateNemesis(current, "triumphed");
					}
					LoseRun(DownedTarget.Name + " was not saved. The stronghold is lost.");
					return;
				}
			}
			VendettaState current2 = Current;
			if (current2 == null)
			{
				return;
			}
			if (!current2.Monster.IsAlive)
			{
				OnMonsterKilled(current2.Monster, null);
				return;
			}
			IGamePlayer target = current2.Target;
			IGameMonster monster = current2.Monster;
			current2.RetargetTimer -= dt;
			if (current2.RetargetTimer <= 0f)
			{
				if (target.IsDowned)
				{
					_bridge.HuntKing(monster);
				}
				else if (current2.WaitingAtMine && current2.HasWaitPoint)
				{
					_bridge.Guard(monster, current2.WaitPoint, current2.ArrivedAtMine);
				}
				else
				{
					_bridge.ForceTarget(monster, target);
				}
				_bridge.SetAttackInterval(monster, target.IsDowned ? vendettaSettings.BaseAttackInterval : current2.Stacks.CurrentAttackInterval);
				current2.RetargetTimer = 0.5f;
			}
			float num = current2.Regen.Tick(dt, monster.MaxHealth);
			if (num > 0f)
			{
				_bridge.Heal(monster, num);
			}
			current2.AtWallOnly = false;
			if (target.IsDowned != current2.HuntingKing)
			{
				SwitchKingHunt(current2, target.IsDowned);
			}
			if (!_bridge.IsLeaping(monster))
			{
				if (!current2.HuntingKing)
				{
					TickMines(current2, vendettaSettings, dt);
				}
				TickWallLeap(current2, vendettaSettings, dt);
			}
			if (!current2.AtWallOnly)
			{
				current2.HasWallPoint = false;
			}
		}

		private static bool IsUp(Zone z)
		{
			if (z != Zone.Wall)
			{
				return z == Zone.Courtyard;
			}
			return true;
		}

		private void SwitchKingHunt(VendettaState c, bool start)
		{
			c.HuntingKing = start;
			c.Sheltered = false;
			c.RetargetTimer = 0f;
			CancelLeap(c);
			if (start)
			{
				StopWaiting(c, handBackToGame: true);
				if (!_runLost)
				{
					Say(c.MonsterName + " turns on the King!", null);
				}
			}
			else
			{
				Say(c.MonsterName + " hunts " + c.Target.Name + " again!", null);
			}
		}

		private bool ReadyAtWall(VendettaState c, Vec3 goal)
		{
			if (c.Monster.Zone != Zone.Field || _bridge.CanWalkTo(c.Monster, goal))
			{
				return false;
			}
			if (!c.HasWallPoint && !_bridge.TryFindWallPoint(c.Monster, out c.WallPoint))
			{
				return _bridge.NeedsLeapTo(c.Monster, goal);
			}
			c.HasWallPoint = true;
			c.AtWallOnly = true;
			c.WallGoal = goal;
			return _bridge.HasReached(c.Monster, c.WallPoint);
		}

		private bool WantsLeapTo(VendettaState c, Vec3 goal)
		{
			if (c.Monster.Zone != Zone.Field)
			{
				return _bridge.NeedsLeapTo(c.Monster, goal);
			}
			return ReadyAtWall(c, goal);
		}

		private bool WantsLeap(VendettaState c, VendettaSettings s)
		{
			Zone zone = c.Target.Zone;
			if (!s.WallJumpEnabled || zone == Zone.Mine)
			{
				return false;
			}
			if (zone == Zone.Courtyard && c.Monster.Zone == Zone.Field)
			{
				if (!_bridge.CanHit(c.Monster, c.Target))
				{
					return ReadyAtWall(c, c.Target.Position);
				}
				return false;
			}
			if (IsUp(zone) || IsUp(c.Monster.Zone))
			{
				return _bridge.NeedsLeap(c.Monster, c.Target);
			}
			return false;
		}

		private void TickWallLeap(VendettaState c, VendettaSettings s, float dt)
		{
			if (c.LeapCooldown > 0f)
			{
				c.LeapCooldown -= dt;
			}
			if (c.TelegraphRemaining > 0f)
			{
				c.TelegraphRemaining -= dt;
				if (c.TelegraphRemaining <= 0f)
				{
					Jump(c);
				}
				return;
			}
			if (c.HuntingKing)
			{
				if (s.WallJumpEnabled && _bridge.TryFindKing(out var position) && WantsLeapTo(c, position) && c.LeapCooldown <= 0f)
				{
					StartLeap(c, s, LeapGoal.King, " is about to leap at the King!", null);
				}
				return;
			}
			bool flag = WantsLeap(c, s);
			if (!StillSheltered(c, s, flag, dt) && flag && !(c.LeapCooldown > 0f))
			{
				Zone zone = c.Target.Zone;
				Zone zone2 = c.Monster.Zone;
				StartLeap(c, s, LeapGoal.Dwarf, (!IsUp(zone)) ? " is about to leap down after you!" : (IsUp(zone2) ? " is about to leap at you!" : ((zone == Zone.Wall) ? " is about to leap onto the wall!" : " is about to leap over the wall!")), c.Target.Id);
			}
		}

		private void StartLeap(VendettaState c, VendettaSettings s, LeapGoal goal, string message, string onlyFor)
		{
			float val = s.WallJumpTelegraphSeconds * ((c.Perk == NemesisPerk.WallBreaker) ? 0.5f : 1f);
			c.TelegraphRemaining = Math.Max(0.05f, val);
			c.LeapGoal = goal;
			_bridge.PlayTelegraph(c.Monster, c.TelegraphRemaining);
			Say(c.MonsterName + message, onlyFor);
		}

		private void Jump(VendettaState c)
		{
			Vec3 point = c.WaitPoint;
			Vec3 position;
			bool flag = ((c.LeapGoal != LeapGoal.Mine) ? ((c.LeapGoal != LeapGoal.King) ? (c.Target.Zone != Zone.Mine && (IsUp(c.Target.Zone) || IsUp(c.Monster.Zone)) && _bridge.TryFindLanding(c.Monster, c.Target.Position, out point)) : (_bridge.TryFindKing(out position) && _bridge.TryFindLanding(c.Monster, position, out point))) : (c.WaitingAtMine && c.HasWaitPoint && !c.ArrivedAtMine));
			if (flag && !_bridge.Leap(c.Monster, point))
			{
				c.TelegraphRemaining = 0.1f;
				return;
			}
			if (!flag)
			{
				_bridge.CancelTelegraph(c.Monster);
			}
			c.LeapGoal = LeapGoal.Dwarf;
			c.LeapCooldown = 6f;
		}

		private void CancelLeap(VendettaState c)
		{
			if (c.TelegraphRemaining > 0f)
			{
				_bridge.CancelTelegraph(c.Monster);
			}
			c.TelegraphRemaining = 0f;
			c.LeapGoal = LeapGoal.Dwarf;
		}

		private bool StillSheltered(VendettaState c, VendettaSettings s, bool wants, float dt)
		{
			c.Sheltered = false;
			float num = s.CourtyardSafeOnWave(_wave);
			if (c.ShelterRemaining < 0f || c.ShelterRemaining > num)
			{
				c.ShelterRemaining = num;
			}
			Zone zone = c.Target.Zone;
			if (zone == Zone.Wall || zone == Zone.Field)
			{
				c.ShelterRemaining = Math.Min(num, c.ShelterRemaining + dt);
				if (c.ShelterRemaining > 6f)
				{
					c.ShelterWarned = false;
				}
				if (c.ShelterRemaining >= num)
				{
					c.ShelterAnnounced = false;
				}
			}
			if (!wants || zone != Zone.Courtyard || c.Monster.Zone != Zone.Field || c.ShelterRemaining <= 0f)
			{
				return false;
			}
			c.ShelterRemaining = Math.Max(0f, c.ShelterRemaining - dt);
			c.Sheltered = true;
			if (!c.ShelterAnnounced)
			{
				c.ShelterAnnounced = true;
				Say("The wall shelters you, but " + c.MonsterName + " won't wait for long...", c.Target.Id);
			}
			else if (!c.ShelterWarned && c.ShelterRemaining <= 5f && num > 7f)
			{
				c.ShelterWarned = true;
				Say(c.MonsterName + " is looking for a way over the wall!", c.Target.Id);
			}
			return true;
		}

		private void TickMines(VendettaState c, VendettaSettings s, float dt)
		{
			if (s.Mines == MineBehavior.Off || c.Target.Zone != Zone.Mine)
			{
				if (c.WaitingAtMine && c.ArrivedAtMine)
				{
					Say(c.MonsterName + " has been waiting for you...", c.Target.Id);
				}
				if (c.LeapGoal == LeapGoal.Mine)
				{
					CancelLeap(c);
				}
				StopWaiting(c, s.Mines == MineBehavior.Off);
				return;
			}
			float num = ((c.Perk == NemesisPerk.TunnelStalker) ? 2f : 1f);
			if (!c.WaitingAtMine)
			{
				if (c.MineChaseTimer < 0f)
				{
					c.MineChaseTimer = s.MineFollowDelaySeconds / num;
				}
				c.MineChaseTimer -= dt;
				if (!(c.MineChaseTimer > 0f))
				{
					c.WaitingAtMine = true;
					c.MineWaitTimer = 0f;
					c.MineTravelTime = 0f;
					c.RetargetTimer = 0f;
					c.HasWaitPoint = _bridge.TryFindMineEntrance(out c.WaitPoint);
					if (!c.HasWaitPoint)
					{
						ArriveAtMine(c);
					}
					else if (!IsThere(c))
					{
						Say(c.MonsterName + " is coming to the mine entrance for you!", c.Target.Id);
					}
				}
			}
			else if (!c.ArrivedAtMine)
			{
				c.MineTravelTime += dt * num;
				bool flag = c.MineTravelTime > 60f;
				if (IsThere(c))
				{
					ArriveAtMine(c);
				}
				else if (!s.WallJumpEnabled)
				{
					if (flag)
					{
						ArriveAtMine(c);
					}
				}
				else if (c.TelegraphRemaining <= 0f && (WantsLeapTo(c, c.WaitPoint) || flag) && c.LeapCooldown <= 0f)
				{
					StartLeap(c, s, LeapGoal.Mine, " is about to leap over the wall to the mine entrance!", c.Target.Id);
				}
			}
			else
			{
				if (s.MineWaitSecondsPerHit <= 0f)
				{
					return;
				}
				c.MineWaitTimer += dt * num;
				while (c.MineWaitTimer >= s.MineWaitSecondsPerHit)
				{
					c.MineWaitTimer -= s.MineWaitSecondsPerHit;
					Grow(c, delegate
					{
						c.Stacks.AddHits(1f);
					});
				}
			}
		}

		private static bool IsThere(VendettaState c)
		{
			return Vec3.Distance(c.Monster.Position, c.WaitPoint) < 3f;
		}

		private void ArriveAtMine(VendettaState c)
		{
			c.ArrivedAtMine = true;
			Say(c.MonsterName + " waits for you at the mine entrance, and its hatred grows...", c.Target.Id);
			Say(c.MonsterName + " is waiting for " + c.Target.Name + " at the mine entrance.", null);
		}

		private void StopWaiting(VendettaState c, bool handBackToGame)
		{
			bool num = c.WaitingAtMine && c.HasWaitPoint;
			c.MineChaseTimer = -1f;
			c.WaitingAtMine = false;
			c.ArrivedAtMine = false;
			c.HasWaitPoint = false;
			if (num)
			{
				c.RetargetTimer = 0f;
			}
			if (num && handBackToGame)
			{
				_bridge.ReleaseTarget(c.Monster);
			}
		}

		private void ApplyAttackInterval(VendettaState c)
		{
			int step = c.Stacks.Step;
			if (step != c.LastAppliedStep)
			{
				c.LastAppliedStep = step;
				_bridge.SetAttackInterval(c.Monster, c.Stacks.CurrentAttackInterval);
			}
		}

		private void FlushSlainGrudge()
		{
			VendettaState slainGrudge = _slainGrudge;
			_slainGrudge = null;
			if (slainGrudge != null)
			{
				CreateNemesis(slainGrudge, null);
			}
		}

		private void CreateNemesis(VendettaState c, string verb)
		{
			VendettaSettings vendettaSettings = _settings();
			if (!vendettaSettings.NemesisEnabled || c.Stacks == null)
			{
				return;
			}
			NemesisRecord sourceRecord = c.SourceRecord;
			string monsterType = ((sourceRecord != null) ? sourceRecord.MonsterType : ((_waveTypes.Count > 0) ? _waveTypes[_rng.Next(_waveTypes.Count)] : c.Monster.TypeName));
			string name = c.MonsterName;
			if (verb == null)
			{
				for (int i = 0; i < 10; i++)
				{
					if (!(name == c.MonsterName) && !Roster.Records.Any((NemesisRecord r) => r.MonsterName == name))
					{
						break;
					}
					name = MonsterNames.Generate(_rng);
				}
			}
			NemesisRecord record = new NemesisRecord
			{
				MonsterName = name,
				MonsterType = monsterType,
				TargetPlayerId = c.Target.Id,
				TargetPlayerName = c.Target.Name,
				CarriedHits = c.Stacks.NemesisCarryOverHits(),
				Perk = (sourceRecord?.Perk ?? NemesisRecord.PerkForKillZone(c.KillZone)),
				TimesReturned = (sourceRecord?.TimesReturned ?? 0),
				CreatedUtcTicks = (sourceRecord?.CreatedUtcTicks ?? DateTime.UtcNow.Ticks)
			};
			Roster.Add(record, vendettaSettings.MaxActiveNemeses);
			c.DownedItsTarget = false;
			RaiseRosterChanged();
			Say((verb != null) ? (name + " " + verb + " and will remember " + c.Target.Name + "...") : (name + " takes up " + c.MonsterName + "'s grudge against " + c.Target.Name + "..."), null);
		}

		private void LoseRun(string message)
		{
			_runLost = true;
			ClearRevive();
			Say(message, null);
			_bridge.LoseRun();
		}

		private void ClearRevive()
		{
			DownedTarget = null;
			ReviveSecured = false;
			ReviveRemaining = 0f;
		}

		private PlayerWaveStats Acc(IGamePlayer p)
		{
			if (!_accumulating.TryGetValue(p.Id, out var value))
			{
				value = new PlayerWaveStats
				{
					PlayerId = p.Id,
					DisplayName = p.Name
				};
				_accumulating[p.Id] = value;
			}
			return value;
		}

		private void Say(string message, string onlyForPlayerId)
		{
			this.Announce?.Invoke(message, onlyForPlayerId);
		}

		private void RaiseRosterChanged()
		{
			this.RosterChanged?.Invoke();
		}
	}
	public class VendettaStacks
	{
		private readonly Func<VendettaSettings> _settings;

		public float Hits { get; private set; }

		public int Step
		{
			get
			{
				VendettaSettings vendettaSettings = _settings();
				if (vendettaSettings.HitsPerStep <= 0f)
				{
					return 0;
				}
				return (int)Math.Floor((Hits + 0.0001f) / vendettaSettings.HitsPerStep);
			}
		}

		public float CurrentDamage
		{
			get
			{
				VendettaSettings vendettaSettings = _settings();
				return Math.Min(vendettaSettings.BaseDamage * (float)Math.Pow(vendettaSettings.DamageGrowthPerStep, Step), vendettaSettings.MaxDamage);
			}
		}

		public float CurrentAttackInterval
		{
			get
			{
				VendettaSettings vendettaSettings = _settings();
				return vendettaSettings.BaseAttackInterval + vendettaSettings.IntervalPerStep * (float)Step;
			}
		}

		public VendettaStacks(Func<VendettaSettings> settings, float startingHits = 0f)
		{
			_settings = settings;
			Hits = Math.Min(Math.Max(0f, startingHits), settings().MaxHits);
		}

		public void RegisterHitOnTarget(bool blocked)
		{
			VendettaSettings vendettaSettings = _settings();
			Hits = Math.Min(Hits + (blocked ? vendettaSettings.BlockedHitValue : 1f), vendettaSettings.MaxHits);
		}

		public void AddHits(float hits)
		{
			Hits = Math.Min(Hits + Math.Max(0f, hits), _settings().MaxHits);
		}

		public float DamageAgainst(float targetMaxHp, bool blocked)
		{
			if (blocked)
			{
				return 0f;
			}
			float val = targetMaxHp * _settings().MaxHitPercentOfTargetHp / 100f;
			return Math.Min(CurrentDamage, val);
		}

		public float NemesisCarryOverHits()
		{
			return Hits * _settings().NemesisStackCarryOverPercent / 100f;
		}
	}
	public class VendettaRegen
	{
		private readonly Func<VendettaSettings> _settings;

		public float SecondsSinceDamaged { get; private set; }

		public VendettaRegen(Func<VendettaSettings> settings)
		{
			_settings = settings;
		}

		public void OnDamagedByPlayer()
		{
			SecondsSinceDamaged = 0f;
		}

		public float Tick(float deltaTime, float monsterMaxHp)
		{
			VendettaSettings vendettaSettings = _settings();
			float secondsSinceDamaged = SecondsSinceDamaged;
			SecondsSinceDamaged += deltaTime;
			float num = SecondsSinceDamaged - Math.Max(secondsSinceDamaged, vendettaSettings.HealDelaySeconds);
			if (num <= 0f)
			{
				return 0f;
			}
			return monsterMaxHp * vendettaSettings.HealPercentPerSecond / 100f * num;
		}
	}
	public class PlayerWaveStats
	{
		public string PlayerId;

		public string DisplayName;

		public float DamageDealt;

		public float OreMined;
	}
	public struct VendettaPick
	{
		public PlayerWaveStats Target;

		public bool IsGreedWave;
	}
	public class VendettaTargeting
	{
		private readonly Func<VendettaSettings> _settings;

		private readonly Random _rng;

		private readonly List<string> _history = new List<string>();

		public VendettaTargeting(Func<VendettaSettings> settings, Random rng = null)
		{
			_settings = settings;
			_rng = rng ?? new Random();
		}

		public bool IsGreedWave(int waveNumber)
		{
			int greedEveryNWaves = _settings().GreedEveryNWaves;
			if (greedEveryNWaves > 0 && waveNumber > 0)
			{
				return waveNumber % greedEveryNWaves == 0;
			}
			return false;
		}

		public VendettaPick Pick(int waveNumber, IList<PlayerWaveStats> players)
		{
			if (players == null || players.Count == 0)
			{
				return default(VendettaPick);
			}
			VendettaSettings s = _settings();
			bool flag = IsGreedWave(waveNumber);
			List<PlayerWaveStats> list = (flag ? players.OrderByDescending((PlayerWaveStats p) => p.OreMined).ThenBy((PlayerWaveStats _) => _rng.Next()).ToList() : ((s.BloodTarget == BloodTargetMode.MostDamage) ? players.OrderByDescending((PlayerWaveStats p) => p.DamageDealt).ThenBy((PlayerWaveStats _) => _rng.Next()).ToList() : ((s.BloodTarget != BloodTargetMode.Rotating) ? players.OrderBy((PlayerWaveStats _) => _rng.Next()).ToList() : RotationOrder(players))));
			if ((flag ? players.All((PlayerWaveStats p) => p.OreMined <= 0f) : players.All((PlayerWaveStats p) => p.DamageDealt <= 0f)) && s.BloodTarget != BloodTargetMode.Rotating)
			{
				list = players.OrderBy((PlayerWaveStats _) => _rng.Next()).ToList();
			}
			PlayerWaveStats playerWaveStats = list.FirstOrDefault((PlayerWaveStats p) => !HitConsecutiveLimit(p.PlayerId, s)) ?? list[0];
			_history.Add(playerWaveStats.PlayerId);
			return new VendettaPick
			{
				Target = playerWaveStats,
				IsGreedWave = flag
			};
		}

		private bool HitConsecutiveLimit(string playerId, VendettaSettings s)
		{
			int maxConsecutiveTargetWaves = s.MaxConsecutiveTargetWaves;
			if (maxConsecutiveTargetWaves <= 0 || _history.Count < maxConsecutiveTargetWaves)
			{
				return false;
			}
			for (int i = _history.Count - maxConsecutiveTargetWaves; i < _history.Count; i++)
			{
				if (_history[i] != playerId)
				{
					return false;
				}
			}
			return true;
		}

		private List<PlayerWaveStats> RotationOrder(IList<PlayerWaveStats> players)
		{
			List<PlayerWaveStats> list = players.OrderBy<PlayerWaveStats, string>((PlayerWaveStats p) => p.PlayerId, StringComparer.Ordinal).ToList();
			string last = ((_history.Count > 0) ? _history[_history.Count - 1] : null);
			int num = list.FindIndex((PlayerWaveStats p) => p.PlayerId == last);
			int num2 = ((num >= 0) ? (num + 1) : 0);
			List<PlayerWaveStats> list2 = new List<PlayerWaveStats>();
			for (int num3 = 0; num3 < list.Count; num3++)
			{
				list2.Add(list[(num2 + num3) % list.Count]);
			}
			return list2;
		}

		public void ResetForNewRun()
		{
			_history.Clear();
		}
	}
	public enum Preset
	{
		Casual,
		Standard,
		Brutal,
		Custom
	}
	public enum BloodTargetMode
	{
		MostDamage,
		Random,
		Rotating
	}
	public enum MineBehavior
	{
		WaitAtEntrance,
		Off
	}
	public enum LossMode
	{
		ReviveOrLose,
		InstantLoss
	}
	[Serializable]
	public class VendettaSettings
	{
		public BloodTargetMode BloodTarget;

		public int GreedEveryNWaves = 3;

		public int MaxConsecutiveTargetWaves = 2;

		public float HitsPerStep = 2f;

		public float MaxHits = 6f;

		public float BaseDamage = 10f;

		public float DamageGrowthPerStep = 1.65f;

		public float MaxDamage = 45f;

		public float BaseAttackInterval = 1f;

		public float IntervalPerStep = 0.75f;

		public float BlockedHitValue = 0.5f;

		public float MaxHitPercentOfTargetHp = 60f;

		public float HealDelaySeconds = 8f;

		public float HealPercentPerSecond = 5f;

		public bool WallJumpEnabled = true;

		public float WallJumpTelegraphSeconds = 1f;

		public float CourtyardSafeSeconds = 15f;

		public float CourtyardSafeLossPerWave = 1f;

		public float CourtyardSafeMinSeconds = 5f;

		public MineBehavior Mines;

		public float MineFollowDelaySeconds = 4f;

		public float MineWaitSecondsPerHit = 10f;

		public LossMode Loss;

		public float ReviveWindowSeconds = 25f;

		public bool NemesisEnabled = true;

		public float NemesisStackCarryOverPercent = 50f;

		public int MaxActiveNemeses = 3;

		public int NemesisEarliestWave = 3;

		public int TargetKillBonusOre = 8;

		public int GroupKillBonusOre = 4;

		public float RewardGrowthPercent = 50f;

		public int RewardGrowthEveryNWaves = 2;

		public float CourtyardSafeOnWave(int wave)
		{
			return Math.Max(CourtyardSafeSeconds - CourtyardSafeLossPerWave * (float)Math.Max(0, wave - 1), Math.Min(CourtyardSafeSeconds, CourtyardSafeMinSeconds));
		}

		public int RewardOnWave(int baseAmount, int wave)
		{
			int num = ((RewardGrowthEveryNWaves > 0) ? (Math.Max(0, wave - 1) / RewardGrowthEveryNWaves) : 0);
			return (int)Math.Round((double)baseAmount * (1.0 + (double)((float)num * RewardGrowthPercent) / 100.0), MidpointRounding.AwayFromZero);
		}

		public static VendettaSettings ForPreset(Preset preset)
		{
			VendettaSettings vendettaSettings = new VendettaSettings();
			switch (preset)
			{
			case Preset.Casual:
				vendettaSettings.GreedEveryNWaves = 4;
				vendettaSettings.DamageGrowthPerStep = 1.5f;
				vendettaSettings.MaxDamage = 35f;
				vendettaSettings.BlockedHitValue = 0f;
				vendettaSettings.MaxHitPercentOfTargetHp = 45f;
				vendettaSettings.HealDelaySeconds = 12f;
				vendettaSettings.HealPercentPerSecond = 3f;
				vendettaSettings.WallJumpTelegraphSeconds = 1.5f;
				vendettaSettings.CourtyardSafeSeconds = 25f;
				vendettaSettings.CourtyardSafeMinSeconds = 10f;
				vendettaSettings.ReviveWindowSeconds = 35f;
				vendettaSettings.NemesisStackCarryOverPercent = 25f;
				vendettaSettings.MineFollowDelaySeconds = 6f;
				vendettaSettings.NemesisEarliestWave = 4;
				vendettaSettings.MineWaitSecondsPerHit = 15f;
				vendettaSettings.TargetKillBonusOre = 12;
				vendettaSettings.GroupKillBonusOre = 6;
				break;
			case Preset.Brutal:
				vendettaSettings.GreedEveryNWaves = 2;
				vendettaSettings.MaxConsecutiveTargetWaves = 3;
				vendettaSettings.DamageGrowthPerStep = 1.8f;
				vendettaSettings.MaxDamage = 60f;
				vendettaSettings.BlockedHitValue = 1f;
				vendettaSettings.MaxHitPercentOfTargetHp = 75f;
				vendettaSettings.HealDelaySeconds = 5f;
				vendettaSettings.HealPercentPerSecond = 8f;
				vendettaSettings.WallJumpTelegraphSeconds = 0.7f;
				vendettaSettings.CourtyardSafeSeconds = 8f;
				vendettaSettings.CourtyardSafeMinSeconds = 3f;
				vendettaSettings.ReviveWindowSeconds = 15f;
				vendettaSettings.NemesisStackCarryOverPercent = 75f;
				vendettaSettings.MaxActiveNemeses = 5;
				vendettaSettings.MineFollowDelaySeconds = 2f;
				vendettaSettings.NemesisEarliestWave = 2;
				vendettaSettings.MineWaitSecondsPerHit = 6f;
				vendettaSettings.TargetKillBonusOre = 6;
				vendettaSettings.GroupKillBonusOre = 2;
				break;
			}
			return vendettaSettings;
		}

		public VendettaSettings Clone()
		{
			return (VendettaSettings)MemberwiseClone();
		}
	}
	public class VendettaView
	{
		private const char Separator = '\u001f';

		private const int FieldCount = 14;

		public uint MonsterNetId;

		public string MonsterName = "";

		public string TargetName = "";

		public string Perk = "";

		public string Status = "";

		public bool IsNemesis;

		public bool IsGreed;

		public bool HuntingKing;

		public int Hits;

		public int MaxHits = 1;

		public float LeapsIn;

		public string DownedName = "";

		public bool ReviveSecured;

		public float ReviveRemaining;

		public bool HasMonster => MonsterName.Length > 0;

		public static VendettaView From(VendettaDirector d, VendettaSettings s, Func<IGameMonster, uint> netId)
		{
			VendettaView vendettaView = new VendettaView();
			if (d.DownedTarget != null)
			{
				vendettaView.DownedName = d.DownedTarget.Name;
				vendettaView.ReviveSecured = d.ReviveSecured;
				vendettaView.ReviveRemaining = Math.Max(0f, d.ReviveRemaining);
			}
			VendettaState current = d.Current;
			if (current == null)
			{
				return vendettaView;
			}
			vendettaView.MonsterNetId = netId(current.Monster);
			vendettaView.MonsterName = current.MonsterName;
			vendettaView.TargetName = current.Target.Name;
			vendettaView.IsNemesis = current.IsNemesis;
			vendettaView.IsGreed = current.IsGreedWave;
			vendettaView.HuntingKing = current.HuntingKing;
			vendettaView.Perk = ((current.IsNemesis && current.Perk != NemesisPerk.None) ? NemesisRecord.PerkLabel(current.Perk) : "");
			vendettaView.MaxHits = Math.Max(1, (int)Math.Ceiling(s.MaxHits));
			vendettaView.Hits = Math.Min(vendettaView.MaxHits, (int)current.Stacks.Hits);
			vendettaView.Status = ((current.TelegraphRemaining > 0f) ? "LEAPING!" : ((!current.WaitingAtMine) ? "" : (current.ArrivedAtMine ? "WAITING AT THE MINES" : "HEADING TO THE MINES")));
			vendettaView.LeapsIn = ((vendettaView.Status.Length == 0 && current.Sheltered) ? current.ShelterRemaining : 0f);
			return vendettaView;
		}

		public void Age(float dt)
		{
			if (LeapsIn > 0f)
			{
				LeapsIn = Math.Max(0.01f, LeapsIn - dt);
			}
			if (!ReviveSecured)
			{
				ReviveRemaining = Math.Max(0f, ReviveRemaining - dt);
			}
		}

		public string ChangeKey()
		{
			return Write((LeapsIn > 0f) ? "1" : "0", "");
		}

		public string Serialize()
		{
			return Write(Num(LeapsIn), Num(ReviveRemaining));
		}

		private string Write(string leapsIn, string revive)
		{
			return string.Join('\u001f'.ToString(), MonsterNetId.ToString(CultureInfo.InvariantCulture), Clean(MonsterName), Clean(TargetName), Clean(Perk), Clean(Status), IsNemesis ? "1" : "0", IsGreed ? "1" : "0", HuntingKing ? "1" : "0", Hits.ToString(CultureInfo.InvariantCulture), MaxHits.ToString(CultureInfo.InvariantCulture), leapsIn, Clean(DownedName), ReviveSecured ? "1" : "0", revive);
		}

		public static VendettaView Parse(string text)
		{
			string[] array = ((text != null) ? text.Split('\u001f') : new string[0]);
			if (array.Length < 14)
			{
				return null;
			}
			VendettaView vendettaView = new VendettaView
			{
				MonsterName = array[1],
				TargetName = array[2],
				Perk = array[3],
				Status = array[4],
				IsNemesis = (array[5] == "1"),
				IsGreed = (array[6] == "1"),
				HuntingKing = (array[7] == "1"),
				DownedName = array[11],
				ReviveSecured = (array[12] == "1")
			};
			if (!uint.TryParse(array[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out vendettaView.MonsterNetId) || !int.TryParse(array[8], NumberStyles.Integer, CultureInfo.InvariantCulture, out vendettaView.Hits) || !int.TryParse(array[9], NumberStyles.Integer, CultureInfo.InvariantCulture, out vendettaView.MaxHits) || !float.TryParse(array[10], NumberStyles.Float, CultureInfo.InvariantCulture, out vendettaView.LeapsIn) || !float.TryParse(array[13], NumberStyles.Float, CultureInfo.InvariantCulture, out vendettaView.ReviveRemaining))
			{
				return null;
			}
			vendettaView.MaxHits = Math.Min(50, Math.Max(1, vendettaView.MaxHits));
			return vendettaView;
		}

		private static string Num(float f)
		{
			return f.ToString("0.00", CultureInfo.InvariantCulture);
		}

		private static string Clean(string s)
		{
			return (s ?? "").Replace('\u001f', ' ');
		}
	}
	public static class SyncText
	{
		private const string Magic = "VNDT1";

		public const int MaxBytes = 4000;

		public static string State(VendettaView v)
		{
			return "VNDT1S" + v.Serialize();
		}

		public static string Message(string text, string onlyFor)
		{
			if (text != null && text.Length > 300)
			{
				text = text.Substring(0, 300);
			}
			return "VNDT1M" + onlyFor + "\n" + text;
		}

		public static bool TryRead(string raw, out VendettaView view, out string message, out string onlyFor)
		{
			view = null;
			message = null;
			onlyFor = null;
			if (raw == null || raw.Length <= "VNDT1".Length || !raw.StartsWith("VNDT1", StringComparison.Ordinal))
			{
				return false;
			}
			string text = raw.Substring("VNDT1".Length + 1);
			switch (raw["VNDT1".Length])
			{
			case 'S':
				view = VendettaView.Parse(text);
				return view != null;
			case 'M':
			{
				int num = text.IndexOf('\n');
				if (num < 0)
				{
					return false;
				}
				onlyFor = ((num > 0) ? text.Substring(0, num) : null);
				message = text.Substring(num + 1);
				return true;
			}
			default:
				return false;
			}
		}
	}
	public class LobbySync
	{
		private const float Heartbeat = 2f;

		private const float MinGap = 0.25f;

		private const float ExpireAfter = 8f;

		private readonly ManualLogSource _log;

		private readonly StonewardsBridge _bridge;

		private readonly byte[] _buffer = new byte[4096];

		private Callback<LobbyChatMsg_t> _callback;

		private string _lastKey = "";

		private float _sinceSent;

		private float _sinceReceived;

		private bool _idleSent = true;

		private bool _echoLogged;

		private bool _receivedLogged;

		private bool _failedLogged;

		public VendettaView Received { get; private set; }

		private ulong Lobby => _bridge.LobbyId;

		public event Action<string, string> MessageReceived;

		public LobbySync(ManualLogSource log, StonewardsBridge bridge)
		{
			_log = log;
			_bridge = bridge;
		}

		public void Tick(float dt, VendettaView hostView)
		{
			ulong lobby = Lobby;
			if (lobby == 0L)
			{
				Received = null;
				return;
			}
			if (_callback == null)
			{
				_callback = Callback<LobbyChatMsg_t>.Create((DispatchDelegate<LobbyChatMsg_t>)OnLobbyMessage);
			}
			if (hostView == null)
			{
				if (Received != null)
				{
					Received.Age(dt);
					_sinceReceived += dt;
					if (_sinceReceived > 8f)
					{
						Received = null;
					}
				}
				return;
			}
			Received = null;
			_sinceSent += dt;
			bool flag = !hostView.HasMonster && hostView.DownedName.Length == 0;
			string text = hostView.ChangeKey();
			bool num;
			if (!(text != _lastKey))
			{
				if (!(_sinceSent >= 2f))
				{
					return;
				}
				if (!flag)
				{
					goto IL_00e4;
				}
				num = !_idleSent;
			}
			else
			{
				num = _sinceSent >= 0.25f;
			}
			if (!num)
			{
				return;
			}
			goto IL_00e4;
			IL_00e4:
			Send(lobby, SyncText.State(hostView));
			_idleSent = flag && text == _lastKey;
			_lastKey = text;
			_sinceSent = 0f;
		}

		public void SendMessage(string text, string onlyFor)
		{
			ulong lobby = Lobby;
			if (lobby != 0L)
			{
				Send(lobby, SyncText.Message(text, onlyFor));
			}
		}

		private void Send(ulong lobby, string text)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			byte[] bytes = Encoding.UTF8.GetBytes(text);
			if (bytes.Length <= 4000 && !SteamMatchmaking.SendLobbyChatMsg(new CSteamID(lobby), bytes, bytes.Length) && !_failedLogged)
			{
				_failedLogged = true;
				_log.LogWarning((object)"Vendetta: Steam didn't accept a lobby message, so other players may not see the marker (shown once).");
			}
		}

		private void OnLobbyMessage(LobbyChatMsg_t m)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Read(m);
			}
			catch (Exception e)
			{
				Plugin.LogOnce("LobbySync", e);
			}
		}

		private void Read(LobbyChatMsg_t m)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Invalid comparison between Unknown and I4
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			ulong lobby = Lobby;
			if (lobby == 0L || m.m_ulSteamIDLobby != lobby)
			{
				return;
			}
			CSteamID val = default(CSteamID);
			EChatEntryType val2 = default(EChatEntryType);
			int lobbyChatEntry = SteamMatchmaking.GetLobbyChatEntry(new CSteamID(lobby), (int)m.m_iChatID, ref val, _buffer, _buffer.Length, ref val2);
			if (lobbyChatEntry <= 0 || (int)val2 != 1 || !SyncText.TryRead(Encoding.UTF8.GetString(_buffer, 0, lobbyChatEntry), out var view, out var message, out var onlyFor))
			{
				return;
			}
			if (_bridge.IsHost)
			{
				if (!_echoLogged && !(val != SteamUser.GetSteamID()))
				{
					_echoLogged = true;
					_log.LogInfo((object)"Multiplayer sync: working (Steam sent the host's own update back).");
				}
			}
			else if (!(val.m_SteamID.ToString() != SteamMatchmaking.GetLobbyData(new CSteamID(lobby), "HostAdress")))
			{
				if (!_receivedLogged)
				{
					_receivedLogged = true;
					_log.LogInfo((object)"Multiplayer sync: receiving from the host.");
				}
				if (view != null)
				{
					Received = view;
					_sinceReceived = 0f;
				}
				else if (this.MessageReceived != null)
				{
					this.MessageReceived(message, onlyFor);
				}
			}
		}
	}
	[BepInPlugin("baranmods.stonewards.vendetta", "Vendetta", "0.2.1")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "baranmods.stonewards.vendetta";

		public const string PluginName = "Vendetta";

		public const string PluginVersion = "0.2.1";

		private static readonly HashSet<string> _loggedOnce = new HashSet<string>();

		private string _rosterPath;

		public static Plugin Instance { get; private set; }

		public static ManualLogSource Log => ((BaseUnityPlugin)Instance).Logger;

		public static VendettaConfig Settings { get; private set; }

		public static ConfigEntry<bool> DebugOverlay { get; private set; }

		public static StonewardsBridge Bridge { get; private set; }

		public static VendettaDirector Director { get; private set; }

		public static List<GameHooks.HookStatus> Hooks { get; private set; }

		public static VendettaSettings Active => Settings.Local;

		private void Awake()
		{
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			//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_010c: Expected O, but got Unknown
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Settings = new VendettaConfig(((BaseUnityPlugin)this).Config);
			DebugOverlay = ((BaseUnityPlugin)this).Config.Bind<bool>("9. Debug", "Show debug overlay", false, "Shows hook status, player positions/zones and the live vendetta. Use it while filling in GameNames.");
			_rosterPath = Path.Combine(Paths.ConfigPath, "baranmods.stonewards.vendetta.nemeses.txt");
			NemesisRoster roster = NemesisRoster.Load(File.Exists(_rosterPath) ? File.ReadAllText(_rosterPath) : null);
			Bridge = new StonewardsBridge(((BaseUnityPlugin)this).Logger);
			Director = new VendettaDirector(Bridge, () => Active, roster);
			Director.RosterChanged += SaveRoster;
			Director.Announce += delegate(string text, string who)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("[Vendetta] " + text));
			};
			Hooks = GameHooks.Apply(new Harmony("baranmods.stonewards.vendetta"), ((BaseUnityPlugin)this).Logger, Bridge, Director);
			GameObject val = new GameObject("Vendetta");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<VendettaRunner>();
			int count = Hooks.FindAll((GameHooks.HookStatus h) => h.Attached).Count;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Vendetta 0.2.1 loaded. Preset: " + Settings.PresetEntry.Value.ToString() + ". Hooks attached: " + count + "/" + Hooks.Count + (Bridge.IsReady ? "" : ". GameNames not filled in yet, so the mechanics are inactive.")));
		}

		private void SaveRoster()
		{
			try
			{
				File.WriteAllText(_rosterPath, Director.Roster.Save());
			}
			catch (Exception e)
			{
				LogOnce("SaveRoster", e);
			}
		}

		public static void LogOnce(string key, Exception e)
		{
			if ((Object)(object)Instance != (Object)null && _loggedOnce.Add(key))
			{
				((BaseUnityPlugin)Instance).Logger.LogError((object)("Vendetta " + key + " error (shown once): " + e));
			}
		}
	}
	internal sealed class ConfigurationManagerAttributes
	{
		public int? Order;
	}
	public class VendettaConfig
	{
		private readonly List<Action<VendettaSettings>> _readEntriesInto = new List<Action<VendettaSettings>>();

		private readonly List<Action<VendettaSettings>> _writeEntriesFrom = new List<Action<VendettaSettings>>();

		private bool _applyingPreset;

		private int _order = 1000;

		public ConfigEntry<Preset> PresetEntry { get; private set; }

		public VendettaSettings Local { get; private set; }

		public VendettaConfig(ConfigFile cfg)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			PresetEntry = cfg.Bind<Preset>("1. Preset", "Preset", Preset.Standard, new ConfigDescription("Casual / Standard / Brutal overwrite every value below. Changing any single value switches to Custom.", (AcceptableValueBase)null, Array.Empty<object>()));
			Bind(cfg, "2. Targeting", "Blood vendetta target", "Who is hunted on normal waves.", null, (VendettaSettings s) => s.BloodTarget, delegate(VendettaSettings s, BloodTargetMode v)
			{
				s.BloodTarget = v;
			});
			Bind(cfg, "2. Targeting", "Greed vendetta every N waves", "Targets the top ore miner, and goes straight to the mine entrance if they're underground. 0 = off.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), (VendettaSettings s) => s.GreedEveryNWaves, delegate(VendettaSettings s, int v)
			{
				s.GreedEveryNWaves = v;
			});
			Bind(cfg, "2. Targeting", "Max waves in a row for one target", "Same dwarf can't be hunted more than this many waves running. 0 = no limit.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 5), (VendettaSettings s) => s.MaxConsecutiveTargetWaves, delegate(VendettaSettings s, int v)
			{
				s.MaxConsecutiveTargetWaves = v;
			});
			Bind(cfg, "3. Scaling", "Hits per stack step", "Hits on the target needed for each damage/speed step.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), (VendettaSettings s) => s.HitsPerStep, delegate(VendettaSettings s, float v)
			{
				s.HitsPerStep = v;
			});
			Bind(cfg, "3. Scaling", "Max hits", "Hits stop counting past this.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 20f), (VendettaSettings s) => s.MaxHits, delegate(VendettaSettings s, float v)
			{
				s.MaxHits = v;
			});
			Bind(cfg, "3. Scaling", "Base damage", "Damage per hit at 0 stacks.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 100f), (VendettaSettings s) => s.BaseDamage, delegate(VendettaSettings s, float v)
			{
				s.BaseDamage = v;
			});
			Bind(cfg, "3. Scaling", "Damage growth per step", "Damage is multiplied by this each step.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 3f), (VendettaSettings s) => s.DamageGrowthPerStep, delegate(VendettaSettings s, float v)
			{
				s.DamageGrowthPerStep = v;
			});
			Bind(cfg, "3. Scaling", "Max damage", "Damage per hit never goes above this.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 200f), (VendettaSettings s) => s.MaxDamage, delegate(VendettaSettings s, float v)
			{
				s.MaxDamage = v;
			});
			Bind(cfg, "3. Scaling", "Base attack interval (s)", "Seconds between attacks at 0 stacks.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.3f, 5f), (VendettaSettings s) => s.BaseAttackInterval, delegate(VendettaSettings s, float v)
			{
				s.BaseAttackInterval = v;
			});
			Bind(cfg, "3. Scaling", "Attack interval added per step (s)", "Each step slows its attacks by this much.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), (VendettaSettings s) => s.IntervalPerStep, delegate(VendettaSettings s, float v)
			{
				s.IntervalPerStep = v;
			});
			Bind(cfg, "3. Scaling", "Blocked hit value", "How much a blocked hit counts toward stacks. 0 = blocking stops growth, 1 = counts fully.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), (VendettaSettings s) => s.BlockedHitValue, delegate(VendettaSettings s, float v)
			{
				s.BlockedHitValue = v;
			});
			Bind(cfg, "3. Scaling", "Max single hit (% of target HP)", "No hit can do more than this share of the target's max HP.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 100f), (VendettaSettings s) => s.MaxHitPercentOfTargetHp, delegate(VendettaSettings s, float v)
			{
				s.MaxHitPercentOfTargetHp = v;
			});
			Bind(cfg, "4. Healing", "Heal delay (s)", "Seconds without being damaged before the monster starts healing.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 30f), (VendettaSettings s) => s.HealDelaySeconds, delegate(VendettaSettings s, float v)
			{
				s.HealDelaySeconds = v;
			});
			Bind(cfg, "4. Healing", "Heal rate (% max HP per second)", "0 = no healing.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20f), (VendettaSettings s) => s.HealPercentPerSecond, delegate(VendettaSettings s, float v)
			{
				s.HealPercentPerSecond = v;
			});
			Bind(cfg, "5. Movement", "Wall jump", "Monster can leap onto the walls after its target, and back down when they jump off.", null, (VendettaSettings s) => s.WallJumpEnabled, delegate(VendettaSettings s, bool v)
			{
				s.WallJumpEnabled = v;
			});
			Bind(cfg, "5. Movement", "Wall jump telegraph (s)", "Crouch-and-roar warning before it leaps.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 3f), (VendettaSettings s) => s.WallJumpTelegraphSeconds, delegate(VendettaSettings s, float v)
			{
				s.WallJumpTelegraphSeconds = v;
			});
			Bind(cfg, "5. Movement", "Courtyard safe time (s)", "Wave 1: how long its target is safe in the courtyard or on the stairs once the monster is at the wall, before it leaps over. The time comes back while they're outside or on the wall. 0 = never safe.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), (VendettaSettings s) => s.CourtyardSafeSeconds, delegate(VendettaSettings s, float v)
			{
				s.CourtyardSafeSeconds = v;
			});
			Bind(cfg, "5. Movement", "Courtyard safe time lost per wave (s)", "The safe time gets this much shorter every wave. 0 = stays the same.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), (VendettaSettings s) => s.CourtyardSafeLossPerWave, delegate(VendettaSettings s, float v)
			{
				s.CourtyardSafeLossPerWave = v;
			});
			Bind(cfg, "5. Movement", "Courtyard safe time minimum (s)", "The safe time never gets shorter than this.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), (VendettaSettings s) => s.CourtyardSafeMinSeconds, delegate(VendettaSettings s, float v)
			{
				s.CourtyardSafeMinSeconds = v;
			});
			Bind(cfg, "5. Movement", "Mine behavior", "WaitAtEntrance: while its target is in the mines, it waits at the entrance and gets stronger. Off: it ignores them until they come out.", null, (VendettaSettings s) => s.Mines, delegate(VendettaSettings s, MineBehavior v)
			{
				s.Mines = v;
			});
			Bind(cfg, "5. Movement", "Mine follow delay (s)", "How long after its target enters the mines before it sets off for the entrance.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 15f), (VendettaSettings s) => s.MineFollowDelaySeconds, delegate(VendettaSettings s, float v)
			{
				s.MineFollowDelaySeconds = v;
			});
			Bind(cfg, "5. Movement", "Mine wait growth (s per hit)", "While it waits at the mines, it gains one hit toward stacks every this many seconds. 0 = no growth.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), (VendettaSettings s) => s.MineWaitSecondsPerHit, delegate(VendettaSettings s, float v)
			{
				s.MineWaitSecondsPerHit = v;
			});
			Bind(cfg, "6. Losing", "Loss mode", "ReviveOrLose: the target goes down and can be revived. InstantLoss: the target's death ends the run.", null, (VendettaSettings s) => s.Loss, delegate(VendettaSettings s, LossMode v)
			{
				s.Loss = v;
			});
			Bind(cfg, "6. Losing", "Revive window (s)", "Time the group has to revive the downed target. The clock stops once the body is on a revive spot.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(3f, 60f), (VendettaSettings s) => s.ReviveWindowSeconds, delegate(VendettaSettings s, float v)
			{
				s.ReviveWindowSeconds = v;
			});
			Bind(cfg, "7. Nemesis", "Nemesis enabled", "When a vendetta monster downs its target, a random monster type from that wave returns as a Nemesis in a later run.", null, (VendettaSettings s) => s.NemesisEnabled, delegate(VendettaSettings s, bool v)
			{
				s.NemesisEnabled = v;
			});
			Bind(cfg, "7. Nemesis", "Stack carry-over (%)", "Share of its stacks a Nemesis keeps when it returns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), (VendettaSettings s) => s.NemesisStackCarryOverPercent, delegate(VendettaSettings s, float v)
			{
				s.NemesisStackCarryOverPercent = v;
			});
			Bind(cfg, "7. Nemesis", "Max active nemeses", "Oldest is dropped when a new one would go over this.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 10), (VendettaSettings s) => s.MaxActiveNemeses, delegate(VendettaSettings s, int v)
			{
				s.MaxActiveNemeses = v;
			});
			Bind(cfg, "7. Nemesis", "Earliest return wave", "A returning Nemesis appears on this wave or later (once per run).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 15), (VendettaSettings s) => s.NemesisEarliestWave, delegate(VendettaSettings s, int v)
			{
				s.NemesisEarliestWave = v;
			});
			Bind(cfg, "8. Rewards", "Target kill bonus (ore)", "Iron on wave 1 for the hunted dwarf when they land the killing blow. 8 = one stack.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 500), (VendettaSettings s) => s.TargetKillBonusOre, delegate(VendettaSettings s, int v)
			{
				s.TargetKillBonusOre = v;
			});
			Bind(cfg, "8. Rewards", "Early kill bonus (ore each)", "Iron on wave 1 for every player if it dies before reaching max stacks.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 500), (VendettaSettings s) => s.GroupKillBonusOre, delegate(VendettaSettings s, int v)
			{
				s.GroupKillBonusOre = v;
			});
			Bind(cfg, "8. Rewards", "Reward growth (%)", "Both rewards grow by this share of their wave 1 size each time they step up.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 200f), (VendettaSettings s) => s.RewardGrowthPercent, delegate(VendettaSettings s, float v)
			{
				s.RewardGrowthPercent = v;
			});
			Bind(cfg, "8. Rewards", "Reward growth every N waves", "How often the rewards step up. 2 = every other wave, 1 = every wave, 0 = never.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), (VendettaSettings s) => s.RewardGrowthEveryNWaves, delegate(VendettaSettings s, int v)
			{
				s.RewardGrowthEveryNWaves = v;
			});
			PresetEntry.SettingChanged += delegate
			{
				ApplyPreset(PresetEntry.Value);
			};
			ApplyPreset(PresetEntry.Value);
		}

		private void Bind<TValue>(ConfigFile cfg, string section, string key, string description, AcceptableValueBase range, Func<VendettaSettings, TValue> get, Action<VendettaSettings, TValue> set)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			TValue val = get(VendettaSettings.ForPreset(Preset.Standard));
			ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes
			{
				Order = _order--
			};
			ConfigEntry<TValue> entry = cfg.Bind<TValue>(section, key, val, new ConfigDescription(description, range, new object[1] { configurationManagerAttributes }));
			_readEntriesInto.Add(delegate(VendettaSettings s)
			{
				set(s, entry.Value);
			});
			_writeEntriesFrom.Add(delegate(VendettaSettings s)
			{
				entry.Value = get(s);
			});
			entry.SettingChanged += delegate
			{
				if (!_applyingPreset && PresetEntry.Value != Preset.Custom)
				{
					_applyingPreset = true;
					PresetEntry.Value = Preset.Custom;
					_applyingPreset = false;
				}
				if (!_applyingPreset)
				{
					Rebuild();
				}
			};
		}

		private void ApplyPreset(Preset preset)
		{
			if (_applyingPreset)
			{
				return;
			}
			if (preset != Preset.Custom)
			{
				_applyingPreset = true;
				VendettaSettings obj = VendettaSettings.ForPreset(preset);
				foreach (Action<VendettaSettings> item in _writeEntriesFrom)
				{
					item(obj);
				}
				_applyingPreset = false;
			}
			Rebuild();
		}

		private void Rebuild()
		{
			VendettaSettings vendettaSettings = new VendettaSettings();
			foreach (Action<VendettaSettings> item in _readEntriesInto)
			{
				item(vendettaSettings);
			}
			Local = vendettaSettings;
		}
	}
	public class VendettaRunner : MonoBehaviour
	{
		private struct Message
		{
			public string Text;

			public float Until;
		}

		private const float MessageSeconds = 5f;

		private const int MaxMessages = 4;

		private const float MarkerHeight = 2.6f;

		private readonly List<Message> _messages = new List<Message>();

		private GUIStyle _name;

		private GUIStyle _target;

		private GUIStyle _pips;

		private GUIStyle _banner;

		private GUIStyle _revive;

		private GUIStyle _debug;

		private LobbySync _sync;

		private VendettaView _view;

		private void Start()
		{
			Plugin.Director.Announce += OnHostAnnounce;
			try
			{
				StartSync();
			}
			catch (Exception e)
			{
				Plugin.LogOnce("Multiplayer sync", e);
			}
		}

		private void StartSync()
		{
			_sync = new LobbySync(Plugin.Log, Plugin.Bridge);
			_sync.MessageReceived += delegate(string text, string onlyFor)
			{
				Plugin.Log.LogInfo((object)("[Vendetta, from host] " + text));
				OnAnnounce(text, onlyFor);
			};
		}

		private void OnDestroy()
		{
			if (Plugin.Director != null)
			{
				Plugin.Director.Announce -= OnHostAnnounce;
			}
		}

		private void OnHostAnnounce(string text, string onlyForPlayerId)
		{
			OnAnnounce(text, onlyForPlayerId);
			if (_sync == null)
			{
				return;
			}
			try
			{
				_sync.SendMessage(text, onlyForPlayerId);
			}
			catch (Exception e)
			{
				Plugin.LogOnce("Multiplayer sync", e);
			}
		}

		private void OnAnnounce(string text, string onlyForPlayerId)
		{
			if (onlyForPlayerId != null)
			{
				PlayerHandle localPlayer = Plugin.Bridge.LocalPlayer;
				if (localPlayer != null && localPlayer.Id != onlyForPlayerId)
				{
					return;
				}
			}
			_messages.Add(new Message
			{
				Text = text,
				Until = Time.time + 5f
			});
			if (_messages.Count > 4)
			{
				_messages.RemoveAt(0);
			}
		}

		private void Update()
		{
			try
			{
				Plugin.Director.Tick(Time.deltaTime);
			}
			catch (Exception e)
			{
				Plugin.LogOnce("Tick", e);
			}
			try
			{
				UpdateView();
			}
			catch (Exception e2)
			{
				Plugin.LogOnce("View", e2);
			}
		}

		private void UpdateView()
		{
			bool isHost = Plugin.Bridge.IsHost;
			_view = (isHost ? VendettaView.From(Plugin.Director, Plugin.Active, Plugin.Bridge.NetIdOf) : null);
			if (_sync != null)
			{
				try
				{
					_sync.Tick(Time.unscaledDeltaTime, _view);
				}
				catch (Exception e)
				{
					Plugin.LogOnce("Multiplayer sync", e);
				}
				if (!isHost)
				{
					_view = _sync.Received;
				}
			}
		}

		private Transform MonsterTransform()
		{
			VendettaState current = Plugin.Director.Current;
			Component val = ((!Plugin.Bridge.IsHost) ? Plugin.Bridge.FindByNetId(_view.MonsterNetId) : ((current != null) ? ((MonsterHandle)current.Monster).C : null));
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			return val.transform;
		}

		private void OnGUI()
		{
			try
			{
				EnsureStyles();
				DrawMarker();
				DrawRevive();
				DrawMessages();
				if (Plugin.DebugOverlay.Value)
				{
					DrawDebug();
				}
			}
			catch (Exception e)
			{
				Plugin.LogOnce("OnGUI", e);
			}
		}

		private void DrawMarker()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: 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_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: 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_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: 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_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			VendettaView view = _view;
			Camera main = Camera.main;
			if (view == null || !view.HasMonster || (Object)(object)main == (Object)null)
			{
				return;
			}
			Transform val = MonsterTransform();
			if (!Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			Vector3 val2 = main.WorldToScreenPoint(val.position + Vector3.up * 2.6f * val.localScale.y);
			if (!(val2.z <= 0f))
			{
				float x = val2.x;
				float num = (float)Screen.height - val2.y;
				string text = (view.IsNemesis ? ("NEMESIS  " + view.MonsterName) : view.MonsterName);
				if (view.Perk.Length > 0)
				{
					text = text + "  [" + view.Perk + "]";
				}
				Shadowed(new Rect(x - 160f, num - 62f, 320f, 24f), text, _name);
				Shadowed(new Rect(x - 160f, num - 40f, 320f, 22f), (view.IsGreed ? "GREED VENDETTA: " : "VENDETTA: ") + (view.HuntingKing ? "THE KING" : view.TargetName), _target);
				StringBuilder stringBuilder = new StringBuilder();
				for (int i = 0; i < view.MaxHits; i++)
				{
					stringBuilder.Append((i < view.Hits) ? "●" : "○");
				}
				string text2 = ((view.LeapsIn > 0f) ? ("LEAPS IN " + (int)Math.Ceiling(view.LeapsIn) + "s") : view.Status);
				if (text2.Length > 0)
				{
					stringBuilder.Append("   ").Append(text2);
				}
				Shadowed(new Rect(x - 160f, num - 20f, 320f, 22f), stringBuilder.ToString(), _pips);
			}
		}

		private void DrawRevive()
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			VendettaView view = _view;
			if (view != null && view.DownedName.Length != 0)
			{
				string text = view.DownedName.ToUpperInvariant();
				string text2 = (view.ReviveSecured ? (text + " IS BEING REVIVED") : ("REVIVE " + text + "  " + view.ReviveRemaining.ToString("0.0") + "s"));
				Shadowed(new Rect(0f, (float)Screen.height * 0.22f, (float)Screen.width, 40f), text2, _revive);
			}
		}

		private void DrawMessages()
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			_messages.RemoveAll((Message m) => m.Until < Time.time);
			for (int num = 0; num < _messages.Count; num++)
			{
				Shadowed(new Rect(0f, (float)(70 + num * 30), (float)Screen.width, 28f), _messages[num].Text, _banner);
			}
		}

		private void DrawDebug()
		{
			//IL_0371: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("VENDETTA DEBUG   (turn off: F1 > 9. Debug)");
			stringBuilder.AppendLine("Player class: " + Name(Plugin.Bridge.PlayerType, GameNames.PlayerClass) + "   Monster class: " + Name(Plugin.Bridge.MonsterType, GameNames.MonsterClass));
			stringBuilder.AppendLine("Host: " + Plugin.Bridge.IsHost + "   Wave: " + GameHooks.WaveNumber);
			foreach (GameHooks.HookStatus hook in Plugin.Hooks)
			{
				stringBuilder.AppendLine((hook.Attached ? "[OK] " : "[--] ") + hook.Name + "  " + hook.Target);
			}
			IList<IGamePlayer> players = Plugin.Bridge.GetPlayers();
			stringBuilder.AppendLine("Players: " + players.Count);
			foreach (PlayerHandle item in players)
			{
				Vec3 position = item.Position;
				stringBuilder.AppendLine("  " + item.Name + (item.IsLocal ? " (you)" : "") + "  Y=" + position.Y.ToString("0.0") + "  zone=" + item.Zone.ToString() + "  hp=" + Reflect.GetFloat(item.C, GameNames.PlayerHealth, -1f).ToString("0") + "/" + item.MaxHealth.ToString("0") + (item.IsBlocking ? "  BLOCKING" : "") + (item.IsDowned ? "  DOWNED" : ""));
			}
			VendettaState current2 = Plugin.Director.Current;
			if (current2 != null)
			{
				stringBuilder.AppendLine("Vendetta: " + current2.MonsterName + " -> " + current2.Target.Name + "  hits " + current2.Stacks.Hits.ToString("0.0") + "  dmg " + current2.Stacks.CurrentDamage.ToString("0.0") + "  every " + current2.Stacks.CurrentAttackInterval.ToString("0.00") + "s  monster zone=" + current2.Monster.Zone);
			}
			stringBuilder.AppendLine("Nemeses saved: " + Plugin.Director.Roster.Records.Count);
			GUI.Label(new Rect(12f, 12f, 900f, 600f), stringBuilder.ToString(), _debug);
		}

		private static string Name(Type found, string configured)
		{
			if (string.IsNullOrEmpty(configured))
			{
				return "(not set)";
			}
			if (!(found != null))
			{
				return "NOT FOUND '" + configured + "'";
			}
			return found.Name;
		}

		private void EnsureStyles()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			if (_name == null)
			{
				_name = Style(18, (FontStyle)1, new Color(1f, 0.84f, 0.35f));
				_target = Style(16, (FontStyle)1, new Color(1f, 0.3f, 0.25f));
				_pips = Style(16, (FontStyle)0, new Color(1f, 0.55f, 0.3f));
				_banner = Style(20, (FontStyle)1, new Color(1f, 0.9f, 0.75f));
				_revive = Style(30, (FontStyle)1, new Color(1f, 0.25f, 0.2f));
				_debug = Style(13, (FontStyle)0, Color.white);
				_debug.alignment = (TextAnchor)0;
			}
		}

		private static GUIStyle Style(int size, FontStyle fontStyle, Color color)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			GUIStyle val = new GUIStyle(GUI.skin.label)
			{
				fontSize = size,
				fontStyle = fontStyle,
				alignment = (TextAnchor)4
			};
			val.normal.textColor = color;
			return val;
		}

		private static void Shadowed(Rect r, string text, GUIStyle style)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			Color textColor = style.normal.textColor;
			style.normal.textColor = new Color(0f, 0f, 0f, 0.85f);
			GUI.Label(new Rect(((Rect)(ref r)).x + 2f, ((Rect)(ref r)).y + 2f, ((Rect)(ref r)).width, ((Rect)(ref r)).height), text, style);
			style.normal.textColor = textColor;
			GUI.Label(r, text, style);
		}
	}
}
namespace Vendetta.Game
{
	public static class GameHooks
	{
		public class HookStatus
		{
			public string Name;

			public string Target;

			public bool Attached;
		}

		private class Hit
		{
			public PlayerHandle Player;

			public MonsterHandle Monster;

			public string AttackerName = "nobody (no attacker given)";

			public float HealthBefore;

			public bool Blocked;

			public bool WasAlive;

			public Hit Outer;
		}

		private static StonewardsBridge _bridge;

		private static VendettaDirector _director;

		private static ManualLogSource _log;

		private static readonly HashSet<string> _errored = new HashSet<string>();

		private static Hit _playerHit;

		private static Hit _monsterHit;

		public static int WaveNumber { get; private set; }

		public static List<HookStatus> Apply(Harmony harmony, ManualLogSource log, StonewardsBridge bridge, VendettaDirector director)
		{
			_bridge = bridge;
			_director = director;
			_log = log;
			List<HookStatus> list = new List<HookStatus>();
			Hook(harmony, list, "Run started", GameNames.RunStarted, null, "RunStarted_Post");
			Hook(harmony, list, "Run ended", GameNames.RunEnded, null, "RunEnded_Post");
			Hook(harmony, list, "Run left", GameNames.RunLeft, "RunLeft_Pre", null);
			Hook(harmony, list, "Wave started", GameNames.WaveStarted, null, "WaveStarted_Post");
			Hook(harmony, list, "Wave ended", GameNames.WaveEnded, null, "WaveEnded_Post");
			Hook(harmony, list, "Monster spawned", GameNames.MonsterSpawned, null, "MonsterSpawned_Post");
			Hook(harmony, list, "Player takes damage", GameNames.PlayerTakeDamage, "PlayerTakeDamage_Pre", "PlayerTakeDamage_Post");
			Hook(harmony, list, "Monster takes damage", GameNames.MonsterTakeDamage, "MonsterTakeDamage_Pre", "MonsterTakeDamage_Post");
			Hook(harmony, list, "Monster picks target", GameNames.BehaviourSetTarget, "SetTarget_Pre", null);
			Hook(harmony, list, "Monster thinks", GameNames.BehaviourExecute, "Execute_Pre", null);
			Hook(harmony, list, "Exploder thinks", GameNames.BehaviourExecuteExploder, "Execute_Pre", null);
			Hook(harmony, list, "Monster knocked back", GameNames.MonsterKnockback, "Knockback_Pre", null);
			Hook(harmony, list, "Monster died", GameNames.MonsterDied, null, "MonsterDied_Post");
			Hook(harmony, list, "Player downed", GameNames.PlayerDowned, null, "PlayerDowned_Post");
			Hook(harmony, list, "Body on revive spot", GameNames.RevivePlaced, null, "RevivePlaced_Post");
			Hook(harmony, list, "Player revived", GameNames.PlayerRevived, null, "PlayerRevived_Post");
			Hook(harmony, list, "Ore mined", GameNames.OreMined, null, "OreMined_Post");
			return list;
		}

		private static void Hook(Harmony harmony, List<HookStatus> status, string label, string target, string prefix, string postfix)
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			HookStatus hookStatus = new HookStatus
			{
				Name = label,
				Target = (string.IsNullOrEmpty(target) ? "(not set)" : target)
			};
			status.Add(hookStatus);
			if (string.IsNullOrEmpty(target))
			{
				return;
			}
			MethodInfo methodInfo = Reflect.FindMethod(target);
			if (methodInfo == null)
			{
				_log.LogWarning((object)("Vendetta hook '" + label + "': method not found: " + target));
				return;
			}
			try
			{
				harmony.Patch((MethodBase)methodInfo, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(GameHooks).GetMethod(prefix, BindingFlags.Static | BindingFlags.NonPublic)), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(GameHooks).GetMethod(postfix, BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				hookStatus.Attached = true;
				_log.LogInfo((object)("Vendetta hook '" + label + "' attached to " + target));
			}
			catch (Exception ex)
			{
				_log.LogError((object)("Vendetta hook '" + label + "' failed to attach: " + ex.Message));
			}
		}

		private static void RunStarted_Post()
		{
			Safe("RunStarted", delegate
			{
				WaveNumber = 0;
				_bridge.Prune();
				_director.OnRunStarted();
			});
		}

		private static void RunEnded_Post()
		{
			Safe("RunEnded", delegate
			{
				_director.OnRunEnded();
			});
		}

		private static void RunLeft_Pre()
		{
			Safe("RunLeft", delegate
			{
				_director.OnRunEnded();
			});
		}

		private static void WaveStarted_Post(object[] __args)
		{
			Safe("WaveStarted", delegate
			{
				List<string> list = new List<string>();
				if (Arg(__args, GameNames.WaveStarted_MonstersArg) is IEnumerable enumerable)
				{
					foreach (object item in enumerable)
					{
						string text = Reflect.Get(item, GameNames.WaveEntryTypeId) as string;
						if (!string.IsNullOrEmpty(text) && !list.Contains(text))
						{
							list.Add(text);
						}
					}
				}
				WaveNumber++;
				_director.OnWaveStarted(WaveNumber, _bridge.GetPlayers(), list);
			});
		}

		private static void WaveEnded_Post()
		{
			Safe("WaveEnded", delegate
			{
				_director.OnWaveEnded();
			});
		}

		private static void MonsterSpawned_Post(object __instance)
		{
			Safe("MonsterSpawned", delegate
			{
				_director.OnMonsterSpawned(_bridge.ResolveMonster(__instance));
			});
		}

		private static void PlayerTakeDamage_Pre(object __instance, ref object __0, object[] __args, out object __state)
		{
			Hit hit = new Hit
			{
				Outer = _playerHit
			};
			__state = hit;
			_playerHit = hit;
			object damageArg = __0;
			Safe("PlayerTakeDamage", delegate
			{
				hit.Player = _bridge.ResolvePlayer(__instance);
				hit.Monster = _bridge.ResolveMonster(Arg(__args, GameNames.PlayerTakeDamage_SourceArg));
				if (hit.Player != null && hit.Monster != null)
				{
					hit.HealthBefore = hit.Player.Health;
					hit.Blocked = hit.Player.IsBlocking;
					if (ReadDamage(damageArg, out var damage))
					{
						float num = _director.ModifyHitDamage(hit.Monster, hit.Player, hit.Blocked, damage);
						if (Math.Abs(num - damage) > 0.001f)
						{
							damageArg = WithDamage(damageArg, num);
						}
					}
				}
			});
			__0 = damageArg;
		}

		private static void PlayerTakeDamage_Post(object __state)
		{
			Hit hit = __state as Hit;
			if (hit == null)
			{
				return;
			}
			_playerHit = hit.Outer;
			Safe("PlayerTakeDamage", delegate
			{
				if (hit.Player != null && hit.Monster != null && !(hit.HealthBefore <= 0f))
				{
					bool flag = hit.Player.Health < hit.HealthBefore - 0.001f;
					if (hit.Blocked || flag)
					{
						_director.OnHitLanded(hit.Monster, hit.Player, hit.Blocked);
					}
					IGamePlayer downedTarget = _director.DownedTarget;
					if (hit.Player.IsDowned && (downedTarget == null || downedTarget.Id != hit.Player.Id))
					{
						_director.OnPlayerDowned(hit.Player, hit.Monster);
					}
				}
			});
		}

		private static void MonsterTakeDamage_Pre(object __instance, object[] __args, out object __state)
		{
			Hit hit = new Hit
			{
				Outer = _monsterHit
			};
			__state = hit;
			_monsterHit = hit;
			Safe("MonsterTakeDamage", delegate
			{
				hit.Monster = _bridge.ResolveMonster(__instance);
				object obj = Arg(__args, GameNames.MonsterTakeDamage_SourceArg);
				Component val = (Component)((obj is Component) ? obj : null);
				hit.Player = _bridge.ResolvePlayer(val);
				if (hit.Player != null)
				{
					hit.AttackerName = hit.Player.Name;
				}
				else if (Object.op_Implicit((Object)(object)val))
				{
					hit.AttackerName = ((Object)val.gameObject).name;
				}
				if (hit.Monster != null)
				{
					hit.HealthBefore = hit.Monster.Health;
					hit.WasAlive = hit.Monster.IsAlive;
				}
			});
		}

		private static void MonsterTakeDamage_Post(object __state)
		{
			Hit hit = __state as Hit;
			if (hit == null)
			{
				return;
			}
			_monsterHit = hit.Outer;
			Safe("MonsterTakeDamage", delegate
			{
				if (hit.Monster != null)
				{
					float num = hit.HealthBefore - hit.Monster.Health;
					if (num > 0f)
					{
						_director.OnMonsterDamaged(hit.Monster, hit.Player, num);
					}
					if (hit.WasAlive && !hit.Monster.IsAlive)
					{
						MonsterKilled(hit.Monster, hit);
					}
				}
			});
		}

		private static void SetTarget_Pre(object __instance, ref object __0)
		{
			object target = __0;
			Safe("SetTarget", delegate
			{
				VendettaState current = _director.Current;
				if (current != null)
				{
					MonsterHandle monsterHandle = _bridge.MonsterOf(__instance);
					PlayerHandle p = current.Target as PlayerHandle;
					if (monsterHandle != null && monsterHandle.Id == current.Monster.Id)
					{
						if (current.Target.IsDowned)
						{
							target = _bridge.MakeKingTarget(__instance) ?? target;
						}
						else if (_bridge.CanHunt(p))
						{
							target = _bridge.MakeTarget(__instance, p) ?? target;
						}
						else if (current.WaitingAtMine && current.HasWaitPoint && (!current.ArrivedAtMine || !_bridge.IsSomeone(target)))
						{
							target = _bridge.MakeGuardTarget(__instance, current.WaitPoint) ?? target;
						}
					}
				}
			});
			__0 = target;
		}

		private static bool Knockback_Pre(object __instance)
		{
			return !_bridge.IsInAir(__instance);
		}

		private static bool Execute_Pre(object __instance)
		{
			if (_bridge.LeapRules(__instance))
			{
				return false;
			}
			VendettaState c = _director.Current;
			if (c == null || (!c.AtWallOnly && (!c.WaitingAtMine || !c.HasWaitPoint)))
			{
				return true;
			}
			bool held = false;
			Safe("Hold", delegate
			{
				if (c.Monster is MonsterHandle monsterHandle && Object.op_Implicit((Object)(object)monsterHandle.C) && Reflect.Get(monsterHandle.C, GameNames.MonsterBehaviour) == __instance)
				{
					held = (c.AtWallOnly ? _bridge.Hold(monsterHandle, __instance, c.WallPoint, fight: false, c.WallGoal) : _bridge.Hold(monsterHandle, __instance, c.WaitPoint, c.ArrivedAtMine, null));
				}
			});
			return !held;
		}

		private static void MonsterDied_Post(object __instance)
		{
			Safe("MonsterDied", delegate
			{
				MonsterHandle monsterHandle = _bridge.ResolveMonster(__instance);
				bool flag = _monsterHit != null && monsterHandle != null && _monsterHit.Monster != null && _monsterHit.Monster.Id == monsterHandle.Id;
				MonsterKilled(monsterHandle, flag ? _monsterHit : null);
			});
		}

		private static void MonsterKilled(MonsterHandle monster, Hit hit)
		{
			VendettaState current = _director.Current;
			if (current != null && monster != null && monster.Id == current.Monster.Id)
			{
				_log.LogInfo((object)("Vendetta monster (" + monster.TypeName + ") killed by: " + ((hit != null) ? hit.AttackerName : "unknown, outside the damage hook")));
			}
			_director.OnMonsterKilled(monster, hit?.Player);
		}

		private static void PlayerDowned_Post(object __instance)
		{
			Safe("PlayerDowned", delegate
			{
				PlayerHandle playerHandle = _bridge.ResolvePlayer(__instance);
				bool flag = _playerHit != null && playerHandle != null && _playerHit.Player != null && _playerHit.Player.Id == playerHandle.Id;
				_director.OnPlayerDowned(playerHandle, flag ? _playerHit.Monster : null);
			});
		}

		private static void RevivePlaced_Post(object __instance)
		{
			Safe("RevivePlaced", delegate
			{
				_director.OnRevivePlaced(_bridge.ResolvePlayer(__instance));
			});
		}

		private static void PlayerRevived_Post(object __instance)
		{
			Safe("PlayerRevived", delegate
			{
				_director.OnPlayerRevived(_bridge.ResolvePlayer(__instance));
			});
		}

		private static void OreMined_Post(object __instance, object[] __args)
		{
			Safe("OreMined", delegate
			{
				object o = ((GameNames.OreMined_PlayerArg < 0) ? __instance : Arg(__args, GameNames.OreMined_PlayerArg));
				object obj = Arg(__args, GameNames.OreMined_AmountArg);
				_director.RecordOreMined(_bridge.ResolvePlayer(o), IsNumber(obj) ? Convert.ToSingle(obj) : 1f);
			});
		}

		private static object Arg(object[] args, int index)
		{
			if (args == null || index < 0 || index >= args.Length)
			{
				return null;
			}
			return args[index];
		}

		private static bool ReadDamage(object arg, out float damage)
		{
			object obj = (string.IsNullOrEmpty(GameNames.DamageAmount) ? arg : Reflect.Get(arg, GameNames.DamageAmount));
			damage = (IsNumber(obj) ? Convert.ToSingle(obj) : 0f);
			return IsNumber(obj);
		}

		private static object WithDamage(object arg, float damage)
		{
			if (string.IsNullOrEmpty(GameNames.DamageAmount))
			{
				return Convert.ChangeType(damage, arg.GetType());
			}
			Reflect.Set(arg, GameNames.DamageAmount, damage);
			return arg;
		}

		private static bool IsNumber(object o)
		{
			if (!(o is float) && !(o is int) && !(o is double) && !(o is long) && !(o is short))
			{
				return o is uint;
			}
			return true;
		}

		private static void Safe(string hook, Action action)
		{
			try
			{
				action();
			}
			catch (Exception ex)
			{
				if (_errored.Add(hook))
				{
					_log.LogError((object)("Vendetta hook " + hook + " error (shown once): " + ex));
				}
			}
		}
	}
	public static class GameNames
	{
		public static string PlayerClass = "FirstPersonController";

		public static string MonsterClass = "EnemyController";

		public static string PlayerName = "playerName";

		public static string PlayerSteamId = "playerID";

		public static string PlayerHealth = "PlayerStats.syncCurrentHealth";

		public static string PlayerMaxHealth = "PlayerStats.syncMaxHealth";

		public static string PlayerIsDowned = "PlayerStats.isDead";

		public static string PlayerIsBlocking = "PlayerStats.syncIsDefending";

		public static string PlayerIsLocal = "isLocalPlayer";

		public static string MonsterHealth = "NetworkcurrentHealth";

		public static string MonsterMaxHealth = "currentMaxHealth";

		public static string MonsterIsDead = "isDead";

		public static string MonsterBehaviour = "currentEnemyBehaviour";

		public static string MonsterTypeId = "syncID";

		public static string MonsterCanMove = "CanMove";

		public static string MonsterMoveTo = "MoveTo";

		public static string MonsterStop = "StopMovement";

		public static string MonsterFindPath = "TryGetValidPathPosition";

		public static string BehaviourController = "controller";

		public static string BehaviourTargetPlayer = "currentTarget.Player";

		public static string BehaviourLastAttacker = "lastAttacker";

		public static string BehaviourMakeTarget = "GetTargetPlayer";

		public static string BehaviourMakeWallTarget = "GetTargetWallPart";

		public static string BehaviourMakeKingTarget = "GetTargetKing";

		public static string BehaviourPickTarget = "SelectTarget";

		public static string BehaviourIsBusy = "IsSpecialState";

		public static string BehaviourCanWalk = "CanMoveTowardsTarget";

		public static string BehaviourInRange = "IsTargetInRange";

		public static string BehaviourTarget = "currentTarget";

		public static string TargetPosition = "WorldPosition";

		public static string TargetPlayer = "Player";

		public static string TargetType = "Type";

		public static string BehaviourSetTarget = "BaseEnemyBehaviour:SetTarget";

		public static string BehaviourExecute = "BaseEnemyBehaviour:ExecuteBehaviour";

		public static string BehaviourExecuteExploder = "ExplodeEnemyBehavior:ExecuteBehaviour";

		public static string MonsterKnockback = "EnemyNavMeshController:UserCode_CmdApplyKnockback__Vector3";

		public static string BehaviourAttackStats = "attackStats";

		public static string AttackStatsInterval = "attackCooldown";

		public static string RunStarted = "EnemyManager:ServerInit";

		public static string RunEnded = "NetworkHelper:RPCEndGame";

		public static string RunLeft = "LevelManager:OnDestroy";

		public static string WaveStarted = "EnemyManager:SpawnCurrentWave";

		public static int WaveStarted_MonstersArg = 0;

		public static string WaveEntryTypeId = "enemy.ID";

		public static string WaveEnded = "NetworkHelper:ServerOnEndWave";

		public static string MonsterSpawned = "EnemyController:ServerInit";

		public static string PlayerTakeDamage = "PlayerStats:UserCode_ServerApplyDamage__DamageResult__WeaponType__NetworkIdentity";

		public static string DamageAmount = "Damage";

		public static int PlayerTakeDamage_SourceArg = 2;

		public static string MonsterTakeDamage = "EnemyController:UserCode_ServerApplyDamage__DamageResult__WeaponType__NetworkIdentity";

		public static int MonsterTakeDamage_SourceArg = 2;

		public static string MonsterDied = "EnemyController:DeathCo";

		public static string PlayerDowned = "PlayerCarryHandler:OnPlayerDeath";

		public static string RevivePlaced = "FirstPersonController:ServerPlaceOnReviveSpot";

		public static string PlayerRevived = "PlayerStats:ServerRevive";

		public static string OreMined = "DiggingManager:ServerTrySpawnResource";

		public static int OreMined_PlayerArg = 0;

		public static int OreMined_AmountArg = -1;

		public static string OreItemId = "IRON";

		public static string ItemManager = "ItemManager:Instance";

		public static string ItemById = "GetItemDataSoByID";

		public static string ItemDrop = "ServerInstantiatePickableItem";

		public static string PlayerInventory = "InventorySystem";

		public static string InventoryAdd = "ServerAddItem";

		public static string LoseRun = "LevelManager:KillAllPlayers";

		public static string Lobby = "SteamLobby:Instance";

		public static string LobbyId = "currentLobbyID";

		public static string NetId = "netId";

		public static string SpawnedObjects = "Mirror.NetworkClient:spawned";

		public static string HostCheck = "Mirror.NetworkServer:active";

		public static string CaveEntrance = "DiggingManager:Instance.CaveLevelGenerator.StartingCavePosition";

		public static string Wall = "LevelManager:Instance.Wall";

		public static string King = "LevelManager:Instance.King";

		public static string WallHitBoxes = "Stats.wallHitBoxes";

		public static string WallWalkObject = "GroundColliders";

		public static float MineBelowY = -5f;

		public static float WallAboveY = 5f;
	}
	public class LeapMotion
	{
		private enum Phase
		{
			Crouch,
			Air,
			Land
		}

		private const float LandSeconds = 0.6f;

		private const float CrouchHeight = 0.7f;

		private const float AirHeight = 1.12f;

		public readonly Component C;

		private readonly Vector3 _scale;

		private readonly Component _agent;

		private readonly Component _body;

		private readonly Func<bool> _alive;

		private readonly Action<Vector3> _placed;

		private Phase _phase;

		private float _time;

		private float _length;

		private float _peak;

		private float _yaw;

		private Vector3 _from;

		private Vector3 _to;

		private bool _wasKinematic;

		public bool Done { get; private set; }

		public bool InAir
		{
			get
			{
				if (!Done)
				{
					return _phase == Phase.Air;
				}
				return false;
			}
		}

		public bool Moving
		{
			get
			{
				if (!Done)
				{
					return _phase != Phase.Crouch;
				}
				return false;
			}
		}

		public bool CanJump
		{
			get
			{
				if (Object.op_Implicit((Object)(object)_agent))
				{
					return Reflect.GetBool(_agent, "enabled", fallback: true);
				}
				return true;
			}
		}

		public LeapMotion(Component monster, float crouchSeconds, Func<bool> alive, Action<Vector3> placed)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			C = monster;
			_alive = alive;
			_placed = placed;
			_scale = monster.transform.localScale;
			_agent = Get("UnityEngine.AI.NavMeshAgent");
			_body = Get("UnityEngine.Rigidbody");
			_length = Math.Max(0.05f, crouchSeconds);
		}

		private Component Get(string type)
		{
			Type type2 = Reflect.FindType(type);
			if (!(type2 != null))
			{
				return null;
			}
			return C.GetComponent(type2);
		}

		public void Jump(Vector3 to)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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_0094: Unknown result type (might be due to invalid IL or missing references)
			_phase = Phase.Air;
			_time = 0f;
			_from = C.transform.position;
			_to = to;
			float num = to.x - _from.x;
			float num2 = to.z - _from.z;
			float num3 = (float)Math.Sqrt(num * num + num2 * num2);
			_yaw = (float)(Math.Atan2(num, num2) * 180.0 / Math.PI);
			_peak = Math.Max(_from.y, to.y) + 2.5f + num3 * 0.08f;
			_length = Math.Min(1.5f, Math.Max(0.75f, 0.7f + num3 * 0.02f));
			if (Object.op_Implicit((Object)(object)_agent))
			{
				Reflect.Set(_agent, "enabled", false);
			}
			if (Object.op_Implicit((Object)(object)_body))
			{
				_wasKinematic = Reflect.GetBool(_body, "isKinematic", fallback: true);
				Reflect.Set(_body, "isKinematic", true);
			}
		}

		public void Cancel()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (!Done && _phase != Phase.Air)
			{
				if (Object.op_Implicit((Object)(object)C))
				{
					C.transform.localScale = _scale;
				}
				Done = true;
			}
		}

		public void Tick(float dt)
		{
			//IL_00a6: 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_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			if (Done)
			{
				return;
			}
			if (!Object.op_Implicit((Object)(object)C))
			{
				Done = true;
				return;
			}
			_time += dt;
			float num = Math.Min(1f, _time / _length);
			switch (_phase)
			{
			case Phase.Crouch:
				if (!_alive() || _time > _length + 3f)
				{
					Cancel();
				}
				else
				{
					Stretch(1f + -0.3f * num);
				}
				break;
			case Phase.Air:
				C.transform.position = PointAt(_from, _to, _peak, num);
				C.transform.rotation = Quaternion.Euler(-25f + 50f * num, _yaw, 0f);
				Stretch(1.12f);
				if (num >= 1f)
				{
					Land();
				}
				break;
			case Phase.Land:
				Stretch(0.7f + 0.3f * num);
				if (num >= 1f)
				{
					C.transform.localScale = _scale;
					Done = true;
				}
				break;
			}
		}

		private void Land()
		{
			//IL_000c: 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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result typ