Decompiled source of ForgeReplay v1.0.1

plugins/ForgeReplay/ForgeReplay.dll

Decompiled a day ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using AIGraph;
using AK;
using Agents;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Unity.IL2CPP;
using BoosterImplants;
using CellMenu;
using ChainedPuzzles;
using Enemies;
using ForgeAudio;
using ForgeCore;
using ForgeUI;
using ForgeVisual;
using GTFO.API;
using GameData;
using Gear;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using LevelGeneration;
using Localization;
using Microsoft.CodeAnalysis;
using Player;
using RootMotion.FinalIK;
using SNetwork;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ForgeReplay")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("ForgeReplay")]
[assembly: AssemblyTitle("ForgeReplay")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 ForgeReplay
{
	internal enum MarkerKind : byte
	{
		Kill,
		Down,
		Revive,
		Door,
		Alarm,
		Wave,
		Scan,
		Terminal,
		Checkpoint,
		Chat,
		Reactor,
		WorldEvent,
		Ping,
		Note
	}
	internal readonly record struct Marker(uint TimeMs, MarkerKind Kind, int Slot, int Near = -1);
	internal readonly record struct RescueLine(uint TimeMs, int Revived, int Reviver, float Health);
	internal readonly record struct ChatLine(uint TimeMs, int Slot, string Text);
	internal readonly record struct NoteLine(uint TimeMs, string ModId, string Kind, string Payload, bool Mark);
	internal readonly record struct GameLine(uint TimeMs, string Text);
	internal readonly record struct TerminalText(uint TimeMs, ulong Terminal, string Text, bool Typed, string? Column = null);
	internal readonly record struct TerminalUse(uint TimeMs, int Slot, ulong Terminal);
	internal readonly record struct ObjectiveLine(uint TimeMs, int Layer, ulong Status);
	internal readonly record struct PingMark(uint TimeMs, int Slot, float X, float Y, float Z);
	internal sealed class PlayerStats
	{
		internal int Rays;

		internal int RayHits;

		internal int BulletHits;

		internal int Kills;

		internal int Downs;

		internal int Revives;

		internal int Packs;

		internal int Landed;

		internal int Weak;

		internal int Backstabs;

		internal float BulletDamage;

		internal float MeleeDamage;

		internal float ExplosionDamage;

		internal float DamageTaken;

		internal float TakenShare;

		internal int Rescues;

		internal int Supplied;

		internal int Woken;

		internal int Mines;

		internal int Dodges;

		internal uint EstimatedKinds;

		internal bool Estimated(StatKind kind)
		{
			return (EstimatedKinds & (uint)(1 << (int)kind)) != 0;
		}
	}
	internal enum StatKind : byte
	{
		Ray,
		RayHit,
		Bullet,
		Melee,
		Explosion,
		Taken,
		Kill,
		Down,
		Revive,
		Pack,
		TakenShare,
		Rescue,
		Supplied,
		Woken,
		Mine,
		Dodge,
		BulletHit,
		Landed,
		Weak,
		Backstab
	}
	internal readonly record struct PresenceLine(uint TimeMs, int Slot, bool Joined, string? Name, string? Loadout);
	internal readonly record struct StatDelta(uint TimeMs, int Slot, StatKind Kind, float Amount, bool Estimated = false);
	internal readonly record struct DamageLine(uint TimeMs, int Slot, int Kind, int Wielded, float Amount, bool Estimated, bool WeaponKnown = false);
	internal sealed class StatsClock
	{
		private readonly Analysis _analysis;

		private int _next;

		private uint _last;

		internal PlayerStats[] Players { get; private set; } = new PlayerStats[4]
		{
			new PlayerStats(),
			new PlayerStats(),
			new PlayerStats(),
			new PlayerStats()
		};

		internal StatsClock(Analysis analysis)
		{
			_analysis = analysis;
		}

		internal static void Add(PlayerStats p, StatKind kind, float amount, bool estimated = false)
		{
			if (estimated)
			{
				p.EstimatedKinds |= (uint)(1 << (int)kind);
			}
			switch (kind)
			{
			case StatKind.Ray:
				p.Rays += (int)amount;
				break;
			case StatKind.RayHit:
				p.RayHits += (int)amount;
				break;
			case StatKind.BulletHit:
				p.BulletHits += (int)amount;
				break;
			case StatKind.Bullet:
				p.BulletDamage += amount;
				break;
			case StatKind.Melee:
				p.MeleeDamage += amount;
				break;
			case StatKind.Explosion:
				p.ExplosionDamage += amount;
				break;
			case StatKind.Taken:
				p.DamageTaken += amount;
				break;
			case StatKind.Kill:
				p.Kills += (int)amount;
				break;
			case StatKind.Down:
				p.Downs += (int)amount;
				break;
			case StatKind.Revive:
				p.Revives += (int)amount;
				break;
			case StatKind.Pack:
				p.Packs += (int)amount;
				break;
			case StatKind.TakenShare:
				p.TakenShare += amount;
				break;
			case StatKind.Rescue:
				p.Rescues += (int)amount;
				break;
			case StatKind.Supplied:
				p.Supplied += (int)amount;
				break;
			case StatKind.Woken:
				p.Woken += (int)amount;
				break;
			case StatKind.Mine:
				p.Mines += (int)amount;
				break;
			case StatKind.Dodge:
				p.Dodges += (int)amount;
				break;
			case StatKind.Landed:
				p.Landed += (int)amount;
				break;
			case StatKind.Weak:
				p.Weak += (int)amount;
				break;
			case StatKind.Backstab:
				p.Backstabs += (int)amount;
				break;
			}
		}

		internal bool Advance(uint nowMs)
		{
			bool result = false;
			if (nowMs < _last)
			{
				Players = new PlayerStats[4]
				{
					new PlayerStats(),
					new PlayerStats(),
					new PlayerStats(),
					new PlayerStats()
				};
				_next = 0;
				result = true;
			}
			_last = nowMs;
			List<StatDelta> deltas = _analysis.Deltas;
			while (_next < deltas.Count && deltas[_next].TimeMs <= nowMs)
			{
				StatDelta statDelta = deltas[_next++];
				Add(Players[statDelta.Slot], statDelta.Kind, statDelta.Amount, statDelta.Estimated);
				result = true;
			}
			return result;
		}
	}
	internal sealed class Analysis
	{
		internal const float NearMetres = 30f;

		private WorldState? _state;

		private Timeline? _timeline;

		private Func<ulong, bool>? _notable;

		private readonly Dictionary<int, ulong> _dataOf = new Dictionary<int, ulong>();

		private readonly Dictionary<int, uint> _wokeAt = new Dictionary<int, uint>();

		private readonly Dictionary<int, int> _wakeLine = new Dictionary<int, int>();

		private readonly Dictionary<int, int> _locomotion = new Dictionary<int, int>();

		private const uint WakeSameMs = 3000u;

		private const int WakingState = 15;

		private HitMatch? _match;

		private readonly int[] _wielded = new int[4] { -1, -1, -1, -1 };

		private bool _hostLive;

		private bool _fromHost;

		private bool _hostGap;

		private readonly HostTotals[] _hosted = new HostTotals[4];

		private readonly HostTotals[] _guessed = new HostTotals[4];

		private readonly HashSet<int> _hostKilled = new HashSet<int>();

		private readonly Dictionary<int, (uint TimeMs, ulong Data, uint SpawnMs)> _pendingKills = new Dictionary<int, (uint, ulong, uint)>();

		private readonly List<int> _expired = new List<int>();

		private const uint KillWaitMs = 2000u;

		internal readonly ulong[,] AmmoPeak = new ulong[4, 3];

		private readonly Dictionary<int, int> _lastKind = new Dictionary<int, int>();

		private DamageEstimate? _estimate;

		private Action<uint, uint, int, int, float, int>? _landed;

		private const int HibernateState = 14;

		private readonly Dictionary<ulong, int> _sentryOwners = new Dictionary<ulong, int>();

		private readonly Dictionary<ulong, (int Owner, float X, float Y, float Z)> _mineOwners = new Dictionary<ulong, (int, float, float, float)>();

		private const float MineSameMetres = 1f;

		private readonly string[] _loadouts = new string[4] { "", "", "", "" };

		private uint _otherKillerMs;

		private bool _otherKiller;

		private readonly Dictionary<int, (int Slot, bool Exact)> _killer = new Dictionary<int, (int, bool)>();

		private readonly Dictionary<int, List<(uint TimeMs, int Slot, int Kind, int Wielded, float Damage)>> _readings = new Dictionary<int, List<(uint, int, int, int, float)>>();

		private readonly HashSet<int> _syncedEnemies = new HashSet<int>();

		private readonly Dictionary<int, float> _fullHealth = new Dictionary<int, float>();

		private readonly int[] _matchCounts = new int[4];

		private readonly bool[] _healthSynced = new bool[4];

		private readonly bool[] _wasDown = new bool[4];

		private readonly Dictionary<(ushort, ulong), ulong> _seen = new Dictionary<(ushort, ulong), ulong>();

		internal const float RescueMetres = 3f;

		internal const float MoveMetres = 1.5f;

		private readonly Dictionary<int, uint> _spawnMs = new Dictionary<int, uint>();

		private readonly (float X, float Y, float Z, bool Set)[] _anchor = new(float, float, float, bool)[4];

		private bool _wiped;

		private readonly bool[] _exactPacks = new bool[4];

		private bool _hasKit;

		private bool _hasReviveBy;

		private readonly PlayerKit[] _kits = new PlayerKit[4];

		private readonly uint[] _lastUseMs = new uint[4];

		private readonly uint[] _lastShotMs = new uint[4];

		private readonly bool[] _gave = new bool[4];

		private readonly bool[] _shot = new bool[4];

		private readonly bool[] _hurtSeen = new bool[4];

		private readonly HashSet<ulong> _minesCounted = new HashSet<ulong>();

		private readonly Dictionary<int, int> _wokenBy = new Dictionary<int, int>();

		private readonly List<(int Entity, uint TimeMs)> _wakesPlaced = new List<(int, uint)>();

		private const uint ShotToHitMs = 1000u;

		private const uint PackUseWindowMs = 3000u;

		private readonly List<(uint TimeMs, WakeCause Cause, float X, float Y, float Z)> _wakeSources = new List<(uint, WakeCause, float, float, float)>();

		private readonly Dictionary<ulong, ulong> _doorStatus = new Dictionary<ulong, ulong>();

		private const uint WakeSourceMs = 3000u;

		private const float DoorWakeMetres = 25f;

		private const float BlastWakeMetres = 20f;

		private const float SentryWakeMetres = 35f;

		private const int TerminalWidth = 60;

		private static readonly Regex Spacing = new Regex("<(pos|indent|space)=([0-9.]+)(%|px|em)?>|\\t", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

		internal List<Marker> Markers { get; } = new List<Marker>();

		internal List<ChatLine> Chat { get; } = new List<ChatLine>();

		internal List<GameLine> GameLines { get; } = new List<GameLine>();

		internal List<NoteLine> Notes { get; } = new List<NoteLine>();

		internal List<(uint TimeMs, WorldEventLine Line)> WorldEvents { get; } = new List<(uint, WorldEventLine)>();

		internal List<PingMark> Pings { get; } = new List<PingMark>();

		internal List<TerminalText> TerminalTexts { get; } = new List<TerminalText>();

		internal List<TerminalUse> TerminalUses { get; } = new List<TerminalUse>();

		internal List<(uint TimeMs, TerminalPrint Line)> TerminalPrints { get; } = new List<(uint, TerminalPrint)>();

		internal Dictionary<ulong, (float X, float Y, float Z)> TerminalPlaces { get; } = new Dictionary<ulong, (float, float, float)>();

		internal List<ObjectiveLine> Objectives { get; } = new List<ObjectiveLine>();

		internal PlayerStats[] Players { get; } = new PlayerStats[4]
		{
			new PlayerStats(),
			new PlayerStats(),
			new PlayerStats(),
			new PlayerStats()
		};

		internal bool Exact { get; private set; }

		internal Timeline? Source => _timeline;

		internal List<StatDelta> Deltas { get; } = new List<StatDelta>();

		internal List<DamageLine> Damages { get; } = new List<DamageLine>();

		internal bool TotalsOnly { get; init; }

		internal int RecorderSlot { get; init; } = -1;

		internal List<KillLine> Kills { get; } = new List<KillLine>();

		internal List<WakeLine> Wakes { get; } = new List<WakeLine>();

		internal bool HostSeen { get; private set; }

		internal bool HostWhole
		{
			get
			{
				if (HostSeen)
				{
					return !_hostGap;
				}
				return false;
			}
		}

		internal bool Settled
		{
			get
			{
				if (!Exact)
				{
					return HostWhole;
				}
				return true;
			}
		}

		internal IReadOnlyList<EstimatedHit> EstimatedHits
		{
			get
			{
				IReadOnlyList<EstimatedHit> readOnlyList = _estimate?.Hits;
				return readOnlyList ?? Array.Empty<EstimatedHit>();
			}
		}

		internal bool Synced { get; private set; }

		internal EnemyHealthTrack HealthTrack { get; } = new EnemyHealthTrack();

		internal List<bool> Busy { get; } = new List<bool>();

		internal List<RescueLine> Rescues { get; } = new List<RescueLine>();

		internal List<uint> Wipes { get; } = new List<uint>();

		internal int SkippedEvents { get; private set; }

		internal RunReport? Report { get; private set; }

		internal string? ReportFailure { get; private set; }

		internal ClientInference? Inferred { get; private set; }

		internal List<PresenceLine> Presence { get; } = new List<PresenceLine>();

		internal List<uint> FoamLaunches { get; } = new List<uint>();

		internal bool TerminalOf(int slot, uint nowMs, out ulong terminal)
		{
			for (int num = TerminalUses.Count - 1; num >= 0; num--)
			{
				TerminalUse terminalUse = TerminalUses[num];
				if (terminalUse.TimeMs <= nowMs && terminalUse.Slot == slot)
				{
					terminal = terminalUse.Terminal;
					return true;
				}
			}
			terminal = 0uL;
			return false;
		}

		internal int TerminalScreenAt(ulong terminal, uint nowMs, int most, List<string>? into, out string typed)
		{
			typed = "";
			for (int num = TerminalTexts.Count - 1; num >= 0; num--)
			{
				TerminalText terminalText = TerminalTexts[num];
				if (terminalText.TimeMs <= nowMs && terminalText.Terminal == terminal)
				{
					if (terminalText.Typed)
					{
						typed = terminalText.Text;
					}
					break;
				}
			}
			int result = 0;
			int num2 = -1;
			for (int num3 = TerminalPrints.Count - 1; num3 >= 0; num3--)
			{
				var (num4, terminalPrint) = TerminalPrints[num3];
				if (num4 <= nowMs && terminalPrint.Key == terminal && result++ < most)
				{
					num2 = num3;
				}
			}
			if (into != null && num2 >= 0)
			{
				for (int i = num2; i < TerminalPrints.Count && TerminalPrints[i].TimeMs <= nowMs; i++)
				{
					if (TerminalPrints[i].Line.Key == terminal)
					{
						into.Add(ScreenLine(TerminalPrints[i].Line));
					}
				}
			}
			return result;
		}

		internal Analysis(bool exact)
		{
			Exact = exact;
		}

		private static void Tally(HostTotals[] into, int slot, StatKind kind, float amount)
		{
			ref HostTotals reference = ref into[slot & 3];
			long num = (long)MathF.Round(amount * 10f);
			switch (kind)
			{
			case StatKind.Bullet:
				reference.BulletTenths = (uint)Math.Max(0L, reference.BulletTenths + num);
				break;
			case StatKind.Melee:
				reference.MeleeTenths = (uint)Math.Max(0L, reference.MeleeTenths + num);
				break;
			case StatKind.Explosion:
				reference.ExplosionTenths = (uint)Math.Max(0L, reference.ExplosionTenths + num);
				break;
			case StatKind.Kill:
				reference.Kills = (uint)Math.Max(0L, reference.Kills + (long)amount);
				break;
			case StatKind.Landed:
				reference.Landed = (uint)Math.Max(0L, reference.Landed + (long)amount);
				break;
			case StatKind.Weak:
				reference.Weak = (uint)Math.Max(0L, reference.Weak + (long)amount);
				break;
			case StatKind.Backstab:
				reference.Backstabs = (uint)Math.Max(0L, reference.Backstabs + (long)amount);
				break;
			case StatKind.Woken:
				reference.Woken = (uint)Math.Max(0L, reference.Woken + (long)amount);
				break;
			case StatKind.Pack:
				reference.Packs = (uint)Math.Max(0L, reference.Packs + (long)amount);
				break;
			case StatKind.Supplied:
				reference.Supplied = (uint)Math.Max(0L, reference.Supplied + (long)amount);
				break;
			case StatKind.Taken:
			case StatKind.Down:
			case StatKind.Revive:
			case StatKind.TakenShare:
			case StatKind.Rescue:
			case StatKind.Mine:
			case StatKind.Dodge:
			case StatKind.BulletHit:
				break;
			}
		}

		internal void HostTotalsOf(Span<HostTotals> into)
		{
			for (int i = 0; i < 4; i++)
			{
				PlayerStats playerStats = Players[i];
				into[i] = new HostTotals
				{
					BulletTenths = (uint)MathF.Round(playerStats.BulletDamage * 10f),
					MeleeTenths = (uint)MathF.Round(playerStats.MeleeDamage * 10f),
					ExplosionTenths = (uint)MathF.Round(playerStats.ExplosionDamage * 10f),
					Kills = (uint)playerStats.Kills,
					Landed = (uint)playerStats.Landed,
					Weak = (uint)playerStats.Weak,
					Backstabs = (uint)playerStats.Backstabs,
					Woken = (uint)playerStats.Woken,
					Packs = (uint)playerStats.Packs,
					Supplied = (uint)playerStats.Supplied
				};
			}
		}

		private void TakeSnapshot(uint timeMs, int mask, HostTotals[] totals, bool extended)
		{
			_hostLive = true;
			HostSeen = true;
			int slot;
			for (slot = 0; slot < 4; slot++)
			{
				if (((mask >> slot) & 1) != 0)
				{
					HostTotals hostTotals = totals[slot];
					HostTotals hostTotals2 = _hosted[slot];
					HostTotals hostTotals3 = _guessed[slot];
					Add(StatKind.Bullet, hostTotals.BulletTenths, hostTotals2.BulletTenths, hostTotals3.BulletTenths, 10f);
					Add(StatKind.Melee, hostTotals.MeleeTenths, hostTotals2.MeleeTenths, hostTotals3.MeleeTenths, 10f);
					Add(StatKind.Explosion, hostTotals.ExplosionTenths, hostTotals2.ExplosionTenths, hostTotals3.ExplosionTenths, 10f);
					Add(StatKind.Kill, hostTotals.Kills, hostTotals2.Kills, hostTotals3.Kills, 1f);
					Add(StatKind.Landed, hostTotals.Landed, hostTotals2.Landed, hostTotals3.Landed, 1f);
					Add(StatKind.Weak, hostTotals.Weak, hostTotals2.Weak, hostTotals3.Weak, 1f);
					Add(StatKind.Backstab, hostTotals.Backstabs, hostTotals2.Backstabs, hostTotals3.Backstabs, 1f);
					Add(StatKind.Woken, hostTotals.Woken, hostTotals2.Woken, hostTotals3.Woken, 1f);
					if (extended)
					{
						Add(StatKind.Pack, hostTotals.Packs, hostTotals2.Packs, hostTotals3.Packs, 1f);
						Add(StatKind.Supplied, hostTotals.Supplied, hostTotals2.Supplied, hostTotals3.Supplied, 1f);
					}
					_hosted[slot] = hostTotals;
					_guessed[slot] = default(HostTotals);
				}
			}
			void Add(StatKind kind, long now, long was, long guess, float scale)
			{
				long num = now - was - guess;
				if (num != 0L)
				{
					Count(timeMs, slot, kind, (float)num / scale);
				}
			}
		}

		private void FlushKills(uint timeMs)
		{
			foreach (KeyValuePair<int, (uint, ulong, uint)> pendingKill in _pendingKills)
			{
				if (timeMs - pendingKill.Value.Item1 > 2000)
				{
					_expired.Add(pendingKill.Key);
				}
			}
			foreach (int item in _expired)
			{
				_pendingKills.Remove(item);
			}
			_expired.Clear();
		}

		private void CountKill(uint timeMs, int entity, int killer, bool exact, int kind, ulong data, uint spawnMs)
		{
			Count(timeMs, killer, StatKind.Kill, 1f, !exact);
			Func<ulong, bool>? notable = _notable;
			if (notable != null && notable(data))
			{
				Markers.Add(new Marker(timeMs, MarkerKind.Kill, killer));
			}
			if (!TotalsOnly)
			{
				Kills.Add(new KillLine(timeMs, killer, kind, data, _wielded[killer], exact, entity, spawnMs));
			}
		}

		private void Hurt(uint timeMs, int entity, int kind, int slot, bool weak, bool behind, bool settled, float taken, bool lethal)
		{
			_lastKind[entity] = kind;
			if (kind == 0 && _shot[slot] && timeMs - _lastShotMs[slot] <= 1000)
			{
				Count(timeMs, slot, StatKind.BulletHit, 1f);
			}
			if (kind <= 1)
			{
				Count(timeMs, slot, StatKind.Landed, 1f);
				if (weak)
				{
					Count(timeMs, slot, StatKind.Weak, 1f);
				}
				if (behind)
				{
					Count(timeMs, slot, StatKind.Backstab, 1f);
				}
			}
			if (!settled)
			{
				return;
			}
			Damaged(timeMs, slot, kind, WeaponOf(slot, kind), taken, estimated: false);
			if (!lethal)
			{
				return;
			}
			if (_fromHost && _pendingKills.Remove(entity, out (uint, ulong, uint) value))
			{
				CountKill(value.Item1, entity, slot, exact: true, kind, value.Item2, value.Item3);
				_lastKind.Remove(entity);
				return;
			}
			_killer[entity] = (slot, true);
			if (_fromHost)
			{
				_hostKilled.Add(entity);
			}
		}

		private void Busied(uint timeMs)
		{
			if (!TotalsOnly)
			{
				int num = (int)(timeMs / 1000);
				while (Busy.Count <= num)
				{
					Busy.Add(item: false);
				}
				Busy[num] = true;
			}
		}

		private void Moved(uint timeMs, int slot, float x, float y, float z)
		{
			ref(float, float, float, bool) reference = ref _anchor[slot];
			float num = x - reference.Item1;
			float num2 = y - reference.Item2;
			float num3 = z - reference.Item3;
			if (!reference.Item4 || !(num * num + num2 * num2 + num3 * num3 < 2.25f))
			{
				if (reference.Item4)
				{
					Busied(timeMs);
				}
				reference = (x, y, z, true);
			}
		}

		private void Count(uint timeMs, int slot, StatKind kind, float amount, bool estimated = false)
		{
			StatsClock.Add(Players[slot & 3], kind, amount, estimated);
			if (!TotalsOnly)
			{
				Deltas.Add(new StatDelta(timeMs, slot & 3, kind, amount, estimated));
			}
			if (_fromHost)
			{
				Tally(_hosted, slot, kind, amount);
			}
			else if (!_hostLive && !Exact && kind != StatKind.Supplied)
			{
				Tally(_guessed, slot, kind, amount);
			}
		}

		private static StatKind DamageKind(int kind)
		{
			if ((kind != 0 && kind != 3) || 1 == 0)
			{
				if (kind != 1)
				{
					return StatKind.Explosion;
				}
				return StatKind.Melee;
			}
			return StatKind.Bullet;
		}

		private int WeaponOf(int slot, int kind)
		{
			return kind switch
			{
				3 => -3, 
				2 => -2, 
				_ => _wielded[slot & 3], 
			};
		}

		private void Damaged(uint timeMs, int slot, int kind, int wielded, float amount, bool estimated, bool weaponKnown = false)
		{
			Count(timeMs, slot, DamageKind(kind), amount, estimated);
			if (!TotalsOnly)
			{
				Damages.Add(new DamageLine(timeMs, slot & 3, kind, wielded, amount, estimated, weaponKnown));
			}
		}

		internal static Analysis Run(Timeline timeline, bool exact, int recorderSlot = -1, Func<ulong, bool>? notable = null, Func<ulong, Hearing?>? hearing = null, DamageData? damage = null, IReadOnlyList<PlayerEntry>? players = null, CancellationToken cancel = default(CancellationToken))
		{
			Analysis analysis = new Analysis(exact)
			{
				_state = timeline.State,
				_timeline = timeline,
				_notable = notable,
				RecorderSlot = recorderSlot
			};
			if (!exact)
			{
				analysis._match = new HitMatch(recorderSlot);
			}
			if (damage != null)
			{
				analysis._estimate = new DamageEstimate(damage);
			}
			if (players != null)
			{
				foreach (PlayerEntry player in players)
				{
					int slot = player.Slot;
					if (slot >= 0 && slot <= 3)
					{
						analysis._loadouts[player.Slot] = player.Loadout;
					}
				}
			}
			ClientInference inference = new ClientInference(timeline.State, hearing);
			RunReport report = new RunReport(timeline.State);
			timeline.Seek(0u);
			timeline.Advance(timeline.DurationMs, delegate(Record r)
			{
				cancel.ThrowIfCancellationRequested();
				try
				{
					analysis.Take(r.TimeMs, r.EventType, new PayloadReader(r.Payload), r.Payload);
				}
				catch (FormatException)
				{
					analysis.SkippedEvents++;
				}
				try
				{
					inference.Take(r.TimeMs, r.EventType, r.Payload);
				}
				catch (FormatException)
				{
					analysis.SkippedEvents++;
				}
				report.Take(r.TimeMs, r.EventType, r.Payload);
			}, delegate(Record r)
			{
				inference.Sample(r.TimeMs, r.Entity, r.State);
				report.Sample(r.TimeMs, r.Entity, r.State);
				if (r.Entity < 4)
				{
					analysis.Moved(r.TimeMs, r.Entity, r.X, r.Y, r.Z);
				}
			});
			analysis.Settle(timeline.DurationMs);
			inference.Finish();
			analysis.Infer(inference);
			try
			{
				report.Finish(analysis, inference, timeline.DurationMs);
				analysis.Report = report;
			}
			catch (Exception ex) when (((ex is FormatException || ex is InvalidOperationException || ex is ArgumentException || ex is IndexOutOfRangeException || ex is KeyNotFoundException) ? 1 : 0) != 0)
			{
				analysis.ReportFailure = ex.Message;
			}
			return analysis;
		}

		internal bool PacksExact(int slot)
		{
			if (!_hasKit && (slot & 3) != RecorderSlot)
			{
				return _exactPacks[slot & 3];
			}
			return true;
		}

		internal bool HurtExact(int slot)
		{
			if ((slot & 3) != RecorderSlot && (!Exact || !_hurtSeen[slot & 3]))
			{
				return _healthSynced[slot & 3];
			}
			return true;
		}

		internal bool DamageKnown(int slot)
		{
			if (!Settled && !Synced && (slot & 3) != RecorderSlot)
			{
				return _estimate != null;
			}
			return true;
		}

		internal bool KillsKnown(int slot)
		{
			if (!Settled && !Synced && (slot & 3) != RecorderSlot)
			{
				return _match != null;
			}
			return true;
		}

		internal bool HitsKnown(int slot)
		{
			if (!Settled)
			{
				return (slot & 3) == RecorderSlot;
			}
			return true;
		}

		internal bool Estimable(StatKind kind, int slot)
		{
			ClientInference inferred = Inferred;
			if (inferred == null)
			{
				return false;
			}
			switch (kind)
			{
			case StatKind.TakenShare:
				return inferred.HealthSeen(slot);
			case StatKind.Rescue:
				if (!_hasReviveBy && inferred.Revives.Count != 0)
				{
					return inferred.Revives.Exists((InferredRevive r) => r.Reviver >= 0);
				}
				return true;
			case StatKind.Woken:
				if (_wakesPlaced.Count <= 0 && inferred.Wakes.Count != 0)
				{
					return inferred.Wakes.Exists((InferredWake w) => w.NoiseSlot >= 0);
				}
				return true;
			case StatKind.Mine:
				if (_minesCounted.Count <= 0 && inferred.Mines.Count != 0)
				{
					return inferred.Mines.Exists((InferredMine m) => m.Owner >= 0);
				}
				return true;
			default:
				return true;
			}
		}

		private void Infer(ClientInference inferred)
		{
			Inferred = inferred;
			List<StatDelta> list = new List<StatDelta>();
			foreach (InferredHurt hurt in inferred.Hurts)
			{
				list.Add(new StatDelta(hurt.TimeMs, hurt.Slot, StatKind.TakenShare, hurt.Fraction, Estimated: true));
			}
			if (!_hasReviveBy)
			{
				foreach (InferredRevive revife in inferred.Revives)
				{
					if (revife.Reviver >= 0)
					{
						list.Add(new StatDelta(revife.TimeMs, revife.Reviver, StatKind.Rescue, 1f, Estimated: true));
					}
				}
			}
			foreach (InferredPack pack in inferred.Packs)
			{
				if (!PacksExact(pack.User))
				{
					list.Add(new StatDelta(pack.TimeMs, pack.User, StatKind.Pack, 1f, Estimated: true));
				}
				if (pack.User != pack.Receiver && (!_hasKit || (pack.User != RecorderSlot && !_gave[pack.User])))
				{
					list.Add(new StatDelta(pack.TimeMs, pack.Receiver, StatKind.Supplied, 1f, Estimated: true));
				}
			}
			foreach (InferredWake wake in inferred.Wakes)
			{
				if (wake.NoiseSlot < 0)
				{
					continue;
				}
				for (int i = 0; i < Wakes.Count; i++)
				{
					if (Wakes[i].Entity == wake.Entity && Wakes[i].Waker < 0 && Wakes[i].Cause == WakeCause.Unknown && Math.Abs((long)Wakes[i].TimeMs - (long)wake.TimeMs) <= 3000)
					{
						Wakes[i] = Wakes[i]with
						{
							Waker = wake.NoiseSlot,
							Cause = WakeCause.Noise
						};
						break;
					}
				}
			}
			foreach (InferredWake w in inferred.Wakes)
			{
				if (w.NoiseSlot >= 0 && !_wakesPlaced.Exists(((int Entity, uint TimeMs) e) => e.Entity == w.Entity && Math.Abs((long)e.TimeMs - (long)w.TimeMs) <= 3000))
				{
					list.Add(new StatDelta(w.TimeMs, w.NoiseSlot, StatKind.Woken, 1f, Estimated: true));
				}
			}
			foreach (InferredMine mine in inferred.Mines)
			{
				if (mine.Owner >= 0 && !_minesCounted.Contains(mine.Key))
				{
					list.Add(new StatDelta(mine.TimeMs, mine.Owner, StatKind.Mine, 1f, Estimated: true));
				}
			}
			foreach (InferredDodge dodge in inferred.Dodges)
			{
				list.Add(new StatDelta(dodge.TimeMs, dodge.Slot, StatKind.Dodge, 1f, !dodge.TargetRecorded || (!Exact && dodge.Slot != RecorderSlot)));
			}
			foreach (EstimatedHit estimatedHit in EstimatedHits)
			{
				list.Add(new StatDelta(estimatedHit.TimeMs, estimatedHit.Slot, DamageKind(estimatedHit.Kind), estimatedHit.Damage, Estimated: true));
				Damages.Add(new DamageLine(estimatedHit.TimeMs, estimatedHit.Slot, estimatedHit.Kind, estimatedHit.Wielded, estimatedHit.Damage, Estimated: true, WeaponKnown: true));
			}
			foreach (StatDelta item in list)
			{
				StatsClock.Add(Players[item.Slot & 3], item.Kind, item.Amount, item.Estimated);
			}
			List<StatDelta> collection = (from d in Deltas.Concat(list)
				orderby d.TimeMs
				select d).ToList();
			Deltas.Clear();
			Deltas.AddRange(collection);
			List<DamageLine> collection2 = Damages.OrderBy((DamageLine d) => d.TimeMs).ToList();
			Damages.Clear();
			Damages.AddRange(collection2);
		}

		internal void Take(uint timeMs, ushort type, PayloadReader read, byte[]? payload = null)
		{
			if (_match != null && _state != null && payload != null)
			{
				_match.Watch(timeMs, _state, EstimateSwing);
				if (type == 11)
				{
					EstimateShot(timeMs, _match.Shot(timeMs, new PayloadReader(payload), _state), payload);
				}
				else if ((type == 12 || type == 63) ? true : false)
				{
					PayloadReader payloadReader = new PayloadReader(payload);
					int num = (int)payloadReader.U() & 3;
					if (type == 63)
					{
						_match.Charge(timeMs, num, payloadReader.U() == 1);
					}
					else
					{
						_match.Swung(timeMs, num, (int)payloadReader.U(), _estimate?.MeleeOf(_loadouts[num]));
					}
				}
				else if (type == 86)
				{
					_estimate?.Boosters(new PayloadReader(payload));
				}
				else if (type == 100)
				{
					EstimateStruck(timeMs, new PayloadReader(payload));
				}
				else if ((type == 32 || type == 34) ? true : false)
				{
					Placed(type, new PayloadReader(payload));
				}
				else
				{
					switch (type)
					{
					case 33:
						EstimateSentry(timeMs, new PayloadReader(payload));
						break;
					case 35:
						EstimateBlast(timeMs, new PayloadReader(payload));
						break;
					}
				}
			}
			if (_pendingKills.Count > 0)
			{
				FlushKills(timeMs);
			}
			bool[] wasDown = _wasDown;
			_ = _seen;
			switch (type)
			{
			case 11:
			{
				int num22 = (int)read.U() & 3;
				read.U();
				read.Pos();
				read.Pos();
				Count(timeMs, num22, StatKind.Ray, 1f);
				Busied(timeMs);
				_shot[num22] = true;
				_lastShotMs[num22] = timeMs;
				bool num23 = read.U() == 1;
				ulong num24 = read.U();
				if (num23 && num24 == 2)
				{
					Count(timeMs, num22, StatKind.RayHit, 1f);
				}
				break;
			}
			case 3:
			{
				EnemyHurtEvent enemyHurtEvent = EnemyHurtEvent.Read(read);
				int entity2 = enemyHurtEvent.Entity;
				int kind = enemyHurtEvent.Kind;
				float damage = enemyHurtEvent.Damage;
				ulong attacker = enemyHurtEvent.Attacker;
				bool settled = enemyHurtEvent.Settled;
				bool lethal = enemyHurtEvent.Lethal;
				bool behind = enemyHurtEvent.Behind;
				bool lethal2 = lethal;
				bool flag4 = settled;
				ulong num27 = attacker;
				float item9 = damage;
				int num28 = kind;
				int num29 = entity2;
				int limbType = enemyHurtEvent.LimbType;
				bool weak = enemyHurtEvent.Weak;
				float taken = enemyHurtEvent.Taken;
				Busied(timeMs);
				if (num27 > 3)
				{
					break;
				}
				int num30 = (int)num27;
				if (!flag4 && _hostLive)
				{
					break;
				}
				Hurt(timeMs, num29, num28, num30, weak, behind, flag4, taken, lethal2);
				if (flag4)
				{
					break;
				}
				_match?.Hit(timeMs, num29, num30, num28);
				_estimate?.Own(num28, limbType);
				if (!_syncedEnemies.Contains(num29))
				{
					if (!_readings.TryGetValue(num29, out List<(uint, int, int, int, float)> value3))
					{
						value3 = (_readings[num29] = new List<(uint, int, int, int, float)>());
					}
					value3.Add((timeMs, num30, num28, WeaponOf(num30, num28), item9));
				}
				break;
			}
			case 90:
			{
				int num50 = (int)read.U();
				float num51 = (float)read.U() / 10f;
				float num52 = (float)read.U() / 10f;
				HealthTrack.Add(num50, timeMs, num52);
				if (Exact || _hostLive)
				{
					break;
				}
				Synced = true;
				_syncedEnemies.Add(num50);
				_readings.Remove(num50);
				_estimate?.Forget(num50);
				float num53 = num51 - num52;
				if (num53 <= 0f || _match == null)
				{
					break;
				}
				int last2;
				int lastKind2;
				int num54 = _match.Match(timeMs, num50, _matchCounts, out last2, out lastKind2);
				if (num54 == 0)
				{
					break;
				}
				int num55 = 0;
				int[] matchCounts = _matchCounts;
				foreach (int num56 in matchCounts)
				{
					num55 += num56;
				}
				for (int l = 0; l < 4; l++)
				{
					if (_matchCounts[l] > 0)
					{
						Damaged(timeMs, l, _match.KindOf[l], WeaponOf(l, _match.KindOf[l]), num53 * (float)_matchCounts[l] / (float)num55, num54 > 1);
					}
				}
				_lastKind[num50] = lastKind2;
				if (num52 <= 0f && num51 > 0f)
				{
					_killer[num50] = (last2, num54 == 1);
				}
				break;
			}
			case 1:
			{
				int num39 = (int)read.U();
				_dataOf[num39] = read.U();
				read.U();
				read.Pos();
				_spawnMs[num39] = timeMs;
				HealthTrack.Spawned(num39, timeMs);
				_fullHealth[num39] = (float)read.U() / 10f;
				break;
			}
			case 2:
			{
				int num35 = (int)read.U();
				bool flag6 = read.U() == 1;
				ulong num36 = _timeline?.GoneData ?? 0;
				OwnReadings(timeMs, num35, flag6);
				(int, bool) value4;
				bool flag7 = _killer.Remove(num35, out value4);
				uint valueOrDefault = _spawnMs.GetValueOrDefault(num35);
				if (flag6 && !flag7 && _hostLive)
				{
					_pendingKills[num35] = (timeMs, num36, valueOrDefault);
					flag7 = false;
				}
				else if (flag7 && _hostKilled.Remove(num35))
				{
					_fromHost = true;
				}
				if (flag6 && !flag7 && !_hostLive && _match != null)
				{
					int last;
					int lastKind;
					int num37 = _match.Match(timeMs, num35, _matchCounts, out last, out lastKind);
					if (num37 > 0)
					{
						value4 = (last, num37 == 1 && lastKind <= 1);
						flag7 = true;
						_lastKind[num35] = lastKind;
					}
				}
				if (flag6 && flag7)
				{
					CountKill(timeMs, num35, value4.Item1, value4.Item2, _lastKind.GetValueOrDefault(num35), num36, valueOrDefault);
				}
				_fromHost = false;
				_match?.Forget(num35);
				_lastKind.Remove(num35);
				_wokenBy.Remove(num35);
				_syncedEnemies.Remove(num35);
				_fullHealth.Remove(num35);
				_dataOf.Remove(num35);
				_spawnMs.Remove(num35);
				_wokeAt.Remove(num35);
				_wakeLine.Remove(num35);
				_locomotion.Remove(num35);
				break;
			}
			case 13:
			{
				int num32 = (int)read.U() & 3;
				read.U();
				_hurtSeen[num32] = true;
				Busied(timeMs);
				if (Exact || num32 == RecorderSlot)
				{
					Count(timeMs, num32, StatKind.Taken, (float)read.U() / 10f);
				}
				break;
			}
			case 91:
			{
				int num19 = (int)read.U() & 3;
				float num20 = (float)read.U() / 10f;
				float num21 = (float)read.U() / 10f;
				if (num19 != RecorderSlot && (!Exact || !_hurtSeen[num19]))
				{
					_healthSynced[num19] = true;
					if (num20 > num21)
					{
						Count(timeMs, num19, StatKind.Taken, num20 - num21);
					}
				}
				break;
			}
			case 10:
			{
				int num31 = (int)read.U() & 3;
				read.U();
				_wielded[num31] = (int)read.U();
				read.U();
				for (int i = 0; i < 3; i++)
				{
					AmmoPeak[num31, i] = Math.Max(AmmoPeak[num31, i], read.U());
				}
				bool flag5 = read.U() == 1;
				if (flag5 && !_wasDown[num31])
				{
					Count(timeMs, num31, StatKind.Down, 1f);
					Markers.Add(new Marker(timeMs, MarkerKind.Down, num31));
				}
				wasDown[num31] = flag5;
				Wiped(timeMs);
				break;
			}
			case 14:
			{
				int num67 = (int)read.U() & 3;
				Count(timeMs, num67, StatKind.Revive, 1f);
				Markers.Add(new Marker(timeMs, MarkerKind.Revive, num67));
				Rescued(timeMs, num67);
				break;
			}
			case 56:
			{
				int num17 = (int)read.U();
				int num18 = (int)read.U();
				_hasReviveBy = true;
				if (num18 <= 3 && num18 != num17)
				{
					Count(timeMs, num18, StatKind.Rescue, 1f);
				}
				break;
			}
			case 15:
			{
				int num60 = (int)read.U() & 3;
				_exactPacks[num60] = true;
				_lastUseMs[num60] = timeMs;
				if (!_hasKit)
				{
					Count(timeMs, num60, StatKind.Pack, 1f);
				}
				break;
			}
			case 55:
			{
				int num62 = (int)read.U() & 3;
				PlayerKit playerKit = PlayerKit.Read(read);
				PlayerKit playerKit2 = _kits[num62];
				_hasKit = true;
				_kits[num62] = playerKit;
				if (!playerKit2.Known || playerKit2.PackItem == 0 || playerKit2.PackCount <= 0)
				{
					break;
				}
				bool num63;
				if (playerKit.PackItem != playerKit2.PackItem)
				{
					if (playerKit.PackItem != 0 || _lastUseMs[num62] == 0)
					{
						break;
					}
					num63 = timeMs - _lastUseMs[num62] <= 3000;
				}
				else
				{
					num63 = playerKit.PackCount < playerKit2.PackCount;
				}
				if (num63)
				{
					Count(timeMs, num62, StatKind.Pack, 1f);
				}
				break;
			}
			case 30:
			{
				int num42 = (int)read.U() & 3;
				Busied(timeMs);
				ulong num43 = read.U();
				if ((num43 - 5 <= 1) ? true : false)
				{
					_lastUseMs[num42] = timeMs;
				}
				break;
			}
			case 57:
			{
				int num40 = (int)read.U();
				int num41 = (int)read.U();
				if (num40 <= 3 && num41 <= 3)
				{
					_gave[num40] = true;
					_lastUseMs[num40] = timeMs;
					if (num40 != num41)
					{
						Count(timeMs, num41, StatKind.Supplied, 1f);
					}
				}
				break;
			}
			case 34:
			{
				ulong item10 = read.U();
				ulong num33 = read.U();
				ulong num34 = read.U();
				if (num33 == 0L && num34 >= 1 && num34 <= 4 && _minesCounted.Add(item10))
				{
					Count(timeMs, (int)num34 - 1, StatKind.Mine, 1f);
				}
				break;
			}
			case 53:
			{
				int entity3 = (int)read.U();
				bool propagated = read.U() == 1;
				read.U();
				read.U();
				int propagator = (int)read.U() - 1;
				int detection = (int)read.U();
				bool heard = read.U() == 1;
				int player = (int)read.U() - 1;
				int action = (int)read.U();
				Waked(timeMs, entity3, propagated, propagator, detection, heard, player, action, Exact);
				break;
			}
			case 105:
			{
				int entity5 = (int)read.U();
				bool propagated2 = read.U() == 1;
				int num48 = (int)read.U();
				bool heard2 = read.U() == 1;
				int player2 = (int)read.U() - 1;
				int action2 = (int)read.U();
				int propagator2 = (int)read.U() - 1;
				ulong num49 = Math.Min(read.U(), timeMs);
				if (_hostLive)
				{
					_fromHost = true;
					Waked(timeMs - (uint)(int)num49, entity5, propagated2, propagator2, (num48 == 7) ? 255 : num48, heard2, player2, action2, count: true);
					_fromHost = false;
				}
				break;
			}
			case 104:
			{
				int entity4 = (int)read.U();
				int num44 = (int)read.U();
				int slot = (int)read.U() & 3;
				float taken2 = (float)read.U() / 10f;
				int num45 = (int)read.U();
				ulong num46 = read.U();
				read.U();
				read.U();
				ulong num47 = Math.Min(read.U(), timeMs);
				if (_hostLive)
				{
					Busied(timeMs);
					_fromHost = true;
					Hurt(timeMs - (uint)(int)num47, entity4, num44 & 3, slot, num45 == 1, (num46 & 2) != 0, settled: true, taken2, (num46 & 1) != 0);
					_fromHost = false;
				}
				break;
			}
			case 106:
			{
				bool live;
				int mask;
				bool extended;
				HostTotals[] totals = HostLink.ReadLink(read, out live, out mask, out extended);
				if (live)
				{
					_hostGap |= HostSeen && !_hostLive;
					TakeSnapshot(timeMs, mask, totals, extended);
				}
				else if (_hostLive)
				{
					_hostLive = false;
					_hostGap = true;
					_pendingKills.Clear();
				}
				break;
			}
			case 109:
			{
				int num6 = (int)read.U();
				int num7 = (int)read.U();
				int num8 = (int)read.U();
				ulong num9 = Math.Min(read.U(), timeMs);
				if (_hostLive && num6 <= 3 && num7 <= 3 && num8 <= 2)
				{
					uint num10 = timeMs - (uint)(int)num9;
					_gave[num6] = true;
					_lastUseMs[num6] = num10;
					if (num6 != num7)
					{
						_fromHost = true;
						Count(num10, num7, StatKind.Supplied, 1f);
						_fromHost = false;
					}
				}
				break;
			}
			case 110:
			{
				int num64 = (int)read.U() & 3;
				ulong num65 = Math.Min(read.U(), timeMs);
				if (_hostLive)
				{
					uint num66 = timeMs - (uint)(int)num65;
					_exactPacks[num64] = true;
					_lastUseMs[num64] = num66;
					if (!_hasKit)
					{
						_fromHost = true;
						Count(num66, num64, StatKind.Pack, 1f);
						_fromHost = false;
					}
				}
				break;
			}
			case 112:
			{
				int num57 = (int)read.U() & 3;
				bool flag9 = read.U() == 1;
				ulong num58 = Math.Min(read.U(), timeMs);
				if (_hostLive)
				{
					uint num59 = timeMs - (uint)(int)num58;
					_shot[num57] = true;
					_lastShotMs[num57] = num59;
					_fromHost = true;
					Count(num59, num57, StatKind.Ray, 1f);
					if (flag9)
					{
						Count(num59, num57, StatKind.RayHit, 1f);
					}
					_fromHost = false;
				}
				break;
			}
			case 92:
			{
				int entity = (int)read.U();
				read.U();
				read.U();
				read.U();
				bool flag3 = read.U() == 1;
				if (!Exact && !_hostLive && !WokeLately(entity, timeMs))
				{
					Woke(timeMs, entity, -1, flag3 ? WakeCause.Passed : WakeCause.Unknown, 0, -1);
				}
				break;
			}
			case 51:
			{
				int num12 = (int)read.U();
				int num13 = (int)read.U();
				int value;
				int num14 = (_locomotion.TryGetValue(num12, out value) ? value : 0);
				_locomotion[num12] = num13;
				if (!Exact && !_hostLive && num13 == 15 && num14 != 15 && !WokeLately(num12, timeMs))
				{
					Woke(timeMs, num12, -1, WakeCause.Unknown, 0, -1);
				}
				break;
			}
			case 33:
			case 35:
				_otherKiller = true;
				_otherKillerMs = timeMs;
				if (type == 33)
				{
					read.U();
					var (x2, y2, z2) = read.Pos();
					WakeSource(timeMs, WakeCause.Sentry, x2, y2, z2);
				}
				else
				{
					read.U();
					var (x3, y3, z3) = read.Pos();
					WakeSource(timeMs, WakeCause.Explosion, x3, y3, z3);
				}
				break;
			case 37:
				if (read.U() == 1)
				{
					FoamLaunches.Add(timeMs);
				}
				break;
			case 45:
			{
				int num38 = (int)read.U();
				if (num38 <= 3)
				{
					bool flag8 = read.U() == 1;
					string text5 = read.Text();
					string text6 = read.Text();
					Presence.Add(new PresenceLine(timeMs, num38, flag8, string.IsNullOrEmpty(text5) ? null : text5, string.IsNullOrWhiteSpace(text6) ? null : text6));
					if (flag8 && !string.IsNullOrEmpty(text6))
					{
						_loadouts[num38] = text6;
					}
				}
				break;
			}
			case 20:
				if (payload != null)
				{
					PayloadReader payloadReader2 = new PayloadReader(payload);
					ulong key2 = payloadReader2.U();
					ulong num15 = payloadReader2.U();
					payloadReader2.U();
					(float X, float Y, float Z) tuple3 = payloadReader2.Pos();
					float item3 = tuple3.X;
					float item4 = tuple3.Y;
					float item5 = tuple3.Z;
					ulong value2;
					bool num16 = !_doorStatus.TryGetValue(key2, out value2) || value2 != num15;
					_doorStatus[key2] = num15;
					bool flag = num16;
					if (flag)
					{
						bool flag2 = ((num15 - 10 <= 1) ? true : false);
						flag = flag2;
					}
					if (flag)
					{
						WakeSource(timeMs, WakeCause.Door, item3, item4, item5);
					}
				}
				Changed(timeMs, type, read, MarkerKind.Door, _seen);
				break;
			case 22:
				Changed(timeMs, type, read, MarkerKind.Alarm, _seen);
				break;
			case 21:
				Changed(timeMs, type, read, MarkerKind.Scan, _seen);
				break;
			case 43:
				Changed(timeMs, type, read, MarkerKind.Reactor, _seen);
				break;
			case 23:
				if (read.U() == 1)
				{
					Markers.Add(new Marker(timeMs, MarkerKind.Wave, -1));
				}
				break;
			case 24:
			{
				ulong key = read.U();
				var (num3, num4, num5) = read.Pos();
				Markers.Add(new Marker(timeMs, MarkerKind.Terminal, -1, NearestPlayer(num3, num4, num5)));
				TerminalPlaces[key] = (num3, num4, num5);
				break;
			}
			case 28:
				Markers.Add(new Marker(timeMs, MarkerKind.Checkpoint, -1));
				break;
			case 46:
				read.U();
				if (!TotalsOnly)
				{
					Exact = read.U() == 1;
					if (!Exact && _match == null)
					{
						_match = new HitMatch(RecorderSlot);
					}
				}
				break;
			case 58:
			{
				ulong num61 = read.U();
				Objectives.Add(new ObjectiveLine(timeMs, (num61 > 2) ? (-1) : ((int)num61), read.U()));
				break;
			}
			case 67:
			{
				string item11 = ReplayExtras.Intel(payload).Text;
				item11 = Untagged(item11);
				if (item11.Length > 0)
				{
					AddGameLine(new GameLine(timeMs, item11));
				}
				break;
			}
			case 65:
			{
				if (TotalsOnly)
				{
					break;
				}
				WorldEventLine worldEventLine = ReplayExtras.WorldEvent(payload);
				worldEventLine = worldEventLine with
				{
					Intel = Untagged(worldEventLine.Intel),
					SubHeader = Untagged(worldEventLine.SubHeader),
					SubText = Untagged(worldEventLine.SubText),
					Subtitle = Untagged(worldEventLine.Subtitle)
				};
				if (worldEventLine.Accepted && worldEventLine.Intel.Length + worldEventLine.SubHeader.Length + worldEventLine.SubText.Length + worldEventLine.Subtitle.Length != 0)
				{
					WorldEvents.Add((timeMs, worldEventLine));
					Markers.Add(new Marker(timeMs, MarkerKind.WorldEvent, -1));
					if (worldEventLine.Subtitle.Length > 0)
					{
						AddGameLine(new GameLine(timeMs + (uint)MathF.Round(worldEventLine.DelayS * 1000f), worldEventLine.Subtitle));
					}
				}
				break;
			}
			case 73:
			{
				TerminalPrint terminalPrint = ReplayExtras.Printed(payload);
				TerminalPrints.Add((timeMs, terminalPrint));
				if (Prefixed(terminalPrint, out string column, out string text3))
				{
					string[] array = text3.Split('\n');
					for (int j = 0; j < array.Length; j++)
					{
						TerminalTexts.Add(new TerminalText(timeMs, terminalPrint.Key, array[j].TrimEnd(), Typed: false, (j == 0) ? column : ""));
					}
					break;
				}
				string[] array2 = TerminalColumns(terminalPrint.Text).Split('\n');
				foreach (string text4 in array2)
				{
					TerminalTexts.Add(new TerminalText(timeMs, terminalPrint.Key, text4.TrimEnd(), Typed: false));
				}
				break;
			}
			case 75:
				var (terminal2, text2) = ReplayExtras.Typed(payload);
				TerminalTexts.Add(new TerminalText(timeMs, terminal2, Untagged(text2), Typed: true));
				break;
			case 74:
			{
				ulong num25 = read.U();
				read.U();
				int num26 = (int)read.U() - 1;
				var (item6, item7, item8) = read.Pos();
				TerminalPlaces[num25] = (item6, item7, item8);
				bool flag = ((num26 < 0 || num26 > 3) ? true : false);
				if (!flag && !TotalsOnly && (!TerminalOf(num26, timeMs, out var terminal) || terminal != num25))
				{
					TerminalUses.Add(new TerminalUse(timeMs, num26, num25));
				}
				break;
			}
			case 47:
				if (read.U() != 1)
				{
					string text = Untagged(read.Text());
					if (text.Length > 0)
					{
						AddGameLine(new GameLine(timeMs, text));
					}
				}
				break;
			case 41:
			{
				ulong num11 = read.U();
				var (x, y, z) = read.Pos();
				Pings.Add(new PingMark(timeMs, (num11 > 3) ? (-1) : ((int)num11), x, y, z));
				Markers.Add(new Marker(timeMs, MarkerKind.Ping, (num11 > 3) ? (-1) : ((int)num11)));
				break;
			}
			case 101:
			{
				NoteLine item2 = new NoteLine(timeMs, read.Text(), read.Text(), read.Text(), read.U() != 0);
				Notes.Add(item2);
				if (item2.Mark)
				{
					Markers.Add(new Marker(timeMs, MarkerKind.Note, -1));
				}
				break;
			}
			case 29:
			{
				ulong num2 = read.U();
				ChatLine item = new ChatLine(timeMs, (num2 > 3) ? (-1) : ((int)num2), read.Text());
				Chat.Add(item);
				Markers.Add(new Marker(timeMs, MarkerKind.Chat, item.Slot));
				break;
			}
			}
		}

		private void OwnReadings(uint timeMs, int entity, bool killed = false)
		{
			float num = 0f;
			if (_readings.Remove(entity, out List<(uint, int, int, int, float)> value))
			{
				(ulong, ulong, float) value2;
				float num2 = ((_state != null && _state.Enemies.TryGetValue(entity, out value2)) ? value2.Item3 : _fullHealth.GetValueOrDefault(entity));
				float num3 = ((num2 > 0f) ? num2 : float.MaxValue);
				foreach (var item in value)
				{
					float num4 = Math.Min(item.Item5, num3);
					num3 -= num4;
					num += num4;
					Damaged(item.Item1, item.Item2, item.Item3, item.Item4, num4, item.Item2 != RecorderSlot);
				}
			}
			_estimate?.Gone(entity, num, killed && (!_otherKiller || timeMs - _otherKillerMs > 1500));
		}

		private void Settle(uint durationMs)
		{
			if (_state != null)
			{
				_match?.Watch(durationMs, _state, EstimateSwing);
			}
			foreach (int item in _readings.Keys.ToList())
			{
				OwnReadings(durationMs, item);
			}
			_estimate?.Finish();
		}

		private bool Estimating(int entity, out (ulong DataId, ulong Dimension, float FullHealth) enemy)
		{
			enemy = default((ulong, ulong, float));
			if (_estimate != null && !Exact && !_hostLive && entity >= 0 && !_syncedEnemies.Contains(entity))
			{
				return _state.Enemies.TryGetValue(entity, out enemy);
			}
			return false;
		}

		private void EstimateShot(uint timeMs, int entity, byte[] payload)
		{
			if (Estimating(entity, out (ulong, ulong, float) enemy))
			{
				PayloadReader payloadReader = new PayloadReader(payload);
				int num = (int)payloadReader.U() & 3;
				ulong gun = payloadReader.U();
				(float X, float Y, float Z) tuple = payloadReader.Pos();
				float item = tuple.X;
				float item2 = tuple.Y;
				float item3 = tuple.Z;
				(float X, float Y, float Z) tuple2 = payloadReader.Pos();
				float item4 = tuple2.X;
				float item5 = tuple2.Y;
				float item6 = tuple2.Z;
				float metres = MathF.Sqrt((item4 - item) * (item4 - item) + (item5 - item2) * (item5 - item2) + (item6 - item3) * (item6 - item3));
				_estimate.Shot(timeMs, entity, enemy.Item1, enemy.Item3, num, _wielded[num], gun, metres, DamageEstimate.BackDot(_state, entity, timeMs, item4 - item, item5 - item2, item6 - item3));
			}
		}

		private void Placed(ushort type, PayloadReader read)
		{
			ulong key = read.U();
			ulong num = read.U();
			int num2 = (int)read.U() - 1;
			bool flag = num != 0;
			if (!flag)
			{
				bool flag2 = ((num2 < 0 || num2 > 3) ? true : false);
				flag = flag2;
			}
			if (!flag)
			{
				if (type == 32)
				{
					_sentryOwners[key] = num2;
					return;
				}
				var (item, item2, item3) = read.Pos();
				_mineOwners[key] = (num2, item, item2, item3);
			}
		}

		private void EstimateSentry(uint timeMs, PayloadReader read)
		{
			read.U();
			(float X, float Y, float Z) tuple = read.Pos();
			float item = tuple.X;
			float item2 = tuple.Y;
			float item3 = tuple.Z;
			ulong key = read.U();
			var (num, num2, num3) = read.Pos();
			read.U();
			ulong mode = read.U();
			if (_sentryOwners.TryGetValue(key, out var value))
			{
				float metres;
				int entity = _match.Sentry(timeMs, value, item, item2, item3, num, num2, num3, _state, out metres);
				if (Estimating(entity, out (ulong, ulong, float) enemy))
				{
					_estimate.Sentry(timeMs, entity, enemy.Item1, enemy.Item3, value, mode, metres, DamageEstimate.BackDot(_state, entity, timeMs, num, num2, num3));
				}
			}
		}

		private void EstimateBlast(uint timeMs, PayloadReader read)
		{
			ulong num = read.U();
			var (num2, num3, num4) = read.Pos();
			if (num != 0L)
			{
				return;
			}
			int num5 = -1;
			float num6 = 1f;
			foreach (var value in _mineOwners.Values)
			{
				float num7 = (value.X - num2) * (value.X - num2) + (value.Y - num3) * (value.Y - num3) + (value.Z - num4) * (value.Z - num4);
				if (num7 <= num6)
				{
					num6 = num7;
					(num5, _, _, _) = value;
				}
			}
			if (num5 < 0)
			{
				return;
			}
			float most = (float)read.U() / 10f;
			float least = (float)read.U() / 10f;
			float near = (float)read.U() / 10f;
			float num8 = (float)read.U() / 10f;
			foreach (int key in _state.Enemies.Keys)
			{
				if (!_state.Place(key, timeMs, out var x, out var y, out var z, out var _, out var _, out var _, out var _))
				{
					continue;
				}
				float num9 = MathF.Sqrt((x - num2) * (x - num2) + (y - num3) * (y - num3) + (z - num4) * (z - num4));
				if (!(num9 > num8))
				{
					_match.Hit(timeMs, key, num5, 2);
					if (Estimating(key, out (ulong, ulong, float) enemy))
					{
						_estimate.Blast(timeMs, key, enemy.Item1, enemy.Item3, num5, num9, near, num8, most, least);
					}
				}
			}
		}

		private void EstimateStruck(uint timeMs, PayloadReader read)
		{
			int num = (int)read.U() - 1;
			var (num2, num3, num4) = read.Pos();
			if ((num >= 0 && num <= 3) || 1 == 0)
			{
				int kind;
				float held;
				int num5 = _match.Struck(timeMs, num, num2, num3, num4, _state, out kind, out held);
				if (Estimating(num5, out (ulong, ulong, float) enemy))
				{
					float x;
					float y;
					float z;
					float qx;
					float qy;
					float qz;
					float qw;
					float backDot = (_state.Place(num, timeMs, out x, out y, out z, out qx, out qy, out qz, out qw) ? DamageEstimate.BackDot(_state, num5, timeMs, num2 - x, num3 - y, num4 - z) : (-1f));
					_estimate.Swing(timeMs, num5, enemy.Item1, enemy.Item3, num, _wielded[num], kind, held, _estimate.MeleeOf(_loadouts[num]), backDot, _locomotion.GetValueOrDefault(num5) == 14, struck: true);
				}
			}
		}

		private void EstimateSwing(uint swungMs, uint timeMs, int slot, int kind, float held, int entity)
		{
			if (Estimating(entity, out (ulong, ulong, float) enemy) && _state.Place(slot, timeMs, out var x, out var y, out var z, out var qx, out var qy, out var qz, out var qw) && _state.Place(entity, timeMs, out var x2, out var y2, out var z2, out qw, out qz, out qy, out qx))
			{
				_estimate.Swing(timeMs, entity, enemy.Item1, enemy.Item3, slot, _wielded[slot], kind, held, _estimate.MeleeOf(_loadouts[slot]), DamageEstimate.BackDot(_state, entity, timeMs, x2 - x, y2 - y, z2 - z), _locomotion.GetValueOrDefault(entity) == 14);
			}
		}

		private void AddGameLine(GameLine line)
		{
			int num = GameLines.Count;
			while (num > 0 && GameLines[num - 1].TimeMs > line.TimeMs)
			{
				num--;
			}
			GameLines.Insert(num, line);
		}

		private void Wiped(uint timeMs)
		{
			if (_state == null || TotalsOnly)
			{
				return;
			}
			int num = 0;
			int num2 = 0;
			for (int i = 0; i < 4; i++)
			{
				if (_state.Poses[i].Present)
				{
					num++;
					if (_wasDown[i])
					{
						num2++;
					}
				}
			}
			bool flag = num > 0 && num2 == num;
			if (flag && !_wiped)
			{
				Wipes.Add(timeMs);
			}
			_wiped = flag;
		}

		private void Rescued(uint timeMs, int revived)
		{
			if (_state == null || TotalsOnly)
			{
				return;
			}
			ref Pose reference = ref _state.Poses[revived];
			int num = -1;
			float num2 = 9f;
			for (int i = 0; i < 4; i++)
			{
				ref Pose reference2 = ref _state.Poses[i];
				if (i != revived && reference2.Present && !_wasDown[i])
				{
					float num3 = reference2.X - reference.X;
					float num4 = reference2.Y - reference.Y;
					float num5 = reference2.Z - reference.Z;
					float num6 = num3 * num3 + num4 * num4 + num5 * num5;
					if (num6 <= num2)
					{
						num2 = num6;
						num = i;
					}
				}
			}
			Rescues.Add(new RescueLine(timeMs, revived, num, (num < 0) ? 1f : ((float)(int)_state.Poses[num].State / 127f)));
		}

		private void WakeSource(uint timeMs, WakeCause cause, float x, float y, float z)
		{
			if (!TotalsOnly)
			{
				_wakeSources.Add((timeMs, cause, x, y, z));
				if (_wakeSources.Count > 256)
				{
					_wakeSources.RemoveRange(0, 128);
				}
			}
		}

		private WakeCause SourceOf(uint timeMs, int entity)
		{
			if (_state == null || !_state.Place(entity, timeMs, out var x, out var y, out var z, out var _, out var _, out var _, out var _))
			{
				return WakeCause.Unknown;
			}
			WakeCause result = WakeCause.Unknown;
			float num = float.MaxValue;
			for (int num2 = _wakeSources.Count - 1; num2 >= 0; num2--)
			{
				(uint, WakeCause, float, float, float) tuple = _wakeSources[num2];
				if (tuple.Item1 <= timeMs)
				{
					if (timeMs - tuple.Item1 > 3000)
					{
						break;
					}
					float num3 = ((tuple.Item2 == WakeCause.Door) ? 25f : ((tuple.Item2 == WakeCause.Explosion) ? 20f : 35f));
					float num4 = MathF.Sqrt((tuple.Item3 - x) * (tuple.Item3 - x) + (tuple.Item4 - y) * (tuple.Item4 - y) + (tuple.Item5 - z) * (tuple.Item5 - z));
					if (num4 <= num3 && num4 < num)
					{
						num = num4;
						result = tuple.Item2;
					}
				}
			}
			return result;
		}

		private bool WokeLately(int entity, uint timeMs)
		{
			if (_wokeAt.TryGetValue(entity, out var value) && timeMs >= value)
			{
				return timeMs - value <= 3000;
			}
			return false;
		}

		private void Waked(uint timeMs, int entity, bool propagated, int propagator, int detection, bool heard, int player, int action, bool count)
		{
			if (player > 3)
			{
				player = -1;
			}
			WakeCause wakeCause = (heard ? WakeCause.Noise : ((propagated || detection == 5) ? WakeCause.Passed : (detection switch
			{
				2 => WakeCause.Sensed, 
				4 => WakeCause.Damage, 
				_ => WakeCause.Unknown, 
			})));
			Woke(timeMs, entity, player, wakeCause, (wakeCause == WakeCause.Sensed) ? action : 0, propagated ? propagator : (-1));
			if (!count)
			{
				return;
			}
			int value;
			int num = ((propagated && propagator >= 0 && _wokenBy.TryGetValue(propagator, out value)) ? value : player);
			if (num >= 0)
			{
				_wokenBy[entity] = num;
				if (!TotalsOnly)
				{
					_wakesPlaced.Add((entity, timeMs));
				}
				Count(timeMs, num, StatKind.Woken, 1f);
			}
		}

		private void Woke(uint timeMs, int entity, int waker, WakeCause cause, int action, int root)
		{
			_wokeAt[entity] = timeMs;
			if (!TotalsOnly)
			{
				if (cause == WakeCause.Unknown)
				{
					cause = SourceOf(timeMs, entity);
				}
				if (root >= 0 && _wakeLine.TryGetValue(root, out var value))
				{
					Wakes[value] = Wakes[value]with
					{
						Chain = Wakes[value].Chain + 1
					};
					_wakeLine[entity] = value;
				}
				else
				{
					_wakeLine[entity] = Wakes.Count;
					Wakes.Add(new WakeLine(timeMs, entity, (_state != null && _state.Enemies.TryGetValue(entity, out (ulong, ulong, float) value2)) ? value2.Item1 : _dataOf.GetValueOrDefault(entity), waker, cause, action, 0));
				}
			}
		}

		internal static string Untagged(string text)
		{
			return Regex.Replace(text, "<[^>]*>", "").Trim();
		}

		internal static bool Prefixed(TerminalPrint line, out string column, out string text)
		{
			int type = line.Type;
			bool flag = (uint)(type - 253) <= 1u;
			int num = (flag ? line.Text.IndexOf('\t') : (-1));
			column = ((num < 0) ? "" : Untagged(line.Text.Substring(0, num)));
			text = ((num < 0) ? "" : TerminalColumns(line.Text.Substring(num + 1).Replace("\\n", "\n")));
			return num >= 0;
		}

		internal static string ScreenLine(TerminalPrint line)
		{
			if (!Prefixed(line, out string column, out string text))
			{
				return line.Text;
			}
			int num = Math.Max(16, column.Length + 2);
			return column.PadRight(num) + text.Replace("\n", "\n" + new string(' ', num));
		}

		internal static string TerminalColumns(string text)
		{
			string[] array = text.Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i];
				StringBuilder stringBuilder = new StringBuilder();
				int num = 0;
				foreach (Match item in Spacing.Matches(text2))
				{
					stringBuilder.Append(Regex.Replace(text2.Substring(num, item.Index - num), "<[^>]*>", ""));
					num = item.Index + item.Length;
					int num2 = stringBuilder.Length + 2;
					if (item.Groups[2].Success && float.TryParse(item.Groups[2].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
					{
						string value = item.Groups[3].Value;
						int num3 = ((value == "%") ? ((int)MathF.Round(result * 60f / 100f)) : ((value == "px") ? ((int)MathF.Round(result / 10f)) : ((int)MathF.Round(result * 1.5f))));
						num2 = (item.Groups[1].Value.Equals("pos", StringComparison.OrdinalIgnoreCase) ? Math.Max(num2, num3) : Math.Max(num2, stringBuilder.Length + num3));
					}
					else if (item.Value == "\t")
					{
						num2 = (((stringBuilder.Length / 8 + 1) * 8 < stringBuilder.Length + 2) ? (stringBuilder.Length + 2) : ((stringBuilder.Length / 8 + 1) * 8));
					}
					stringBuilder.Append(' ', num2 - stringBuilder.Length);
				}
				stringBuilder.Append(Regex.Replace(text2.Substring(num), "<[^>]*>", ""));
				array[i] = stringBuilder.ToString();
			}
			return string.Join("\n", array).Trim();
		}

		private void Changed(uint timeMs, ushort type, PayloadReader read, MarkerKind kind, Dictionary<(ushort, ulong), ulong> seen)
		{
			ulong item = read.U();
			ulong num = read.U();
			if (!seen.TryGetValue((type, item), out var value) || value != num)
			{
				seen[(type, item)] = num;
				read.U();
				var (x, y, z) = read.Pos();
				Markers.Add(new Marker(timeMs, kind, -1, NearestPlayer(x, y, z)));
			}
		}

		private int NearestPlayer(float x, float y, float z)
		{
			if (_state == null)
			{
				return -1;
			}
			int result = -1;
			float num = 900f;
			for (int i = 0; i < 4; i++)
			{
				ref Pose reference = ref _state.Poses[i];
				if (reference.Present)
				{
					float num2 = reference.X - x;
					float num3 = reference.Y - y;
					float num4 = reference.Z - z;
					float num5 = num2 * num2 + num3 * num3 + num4 * num4;
					if (num5 <= num)
					{
						num = num5;
						result = i;
					}
				}
			}
			return result;
		}
	}
	internal static class Director
	{
		internal const uint WindowBeforeMs = 4000u;

		internal const uint WindowAfterMs = 1000u;

		internal const uint MinStayMs = 12000u;

		internal const float NearEnemy = 15f;

		internal const float SwitchMargin = 1.3f;

		internal const float BigEnemy = 7f;

		internal static float Weight(MarkerKind kind)
		{
			return kind switch
			{
				MarkerKind.Down => 8f, 
				MarkerKind.Revive => 6f, 
				MarkerKind.Alarm => 5f, 
				MarkerKind.Scan => 4f, 
				MarkerKind.Reactor => 4f, 
				MarkerKind.Kill => 3f, 
				MarkerKind.Terminal => 2f, 
				MarkerKind.Door => 1f, 
				MarkerKind.Chat => 1f, 
				_ => 0f, 
			};
		}

		internal static int Choose(WorldState state, Analysis analysis, uint timeMs, int current, uint lastSwitchMs, Func<ulong, bool>? big = null)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Invalid comparison between Unknown and I4
			Span<float> span = stackalloc float[4];
			for (int i = 0; i < 4; i++)
			{
				if (!state.Poses[i].Present)
				{
					span[i] = -1f;
					continue;
				}
				span[i] = 1f;
				ref Pose reference = ref state.Poses[i];
				for (int j = 4; j < 4096; j++)
				{
					ref Pose reference2 = ref state.Poses[j];
					if (reference2.Present && (int)EnemyAlerts.Settle((EnemyAlert)(byte)(reference2.State & 3), (int)state.EnemyLocomotion[j]) == 3)
					{
						float num = reference2.X - reference.X;
						float num2 = reference2.Y - reference.Y;
						float num3 = reference2.Z - reference.Z;
						if (num * num + num2 * num2 + num3 * num3 <= 225f)
						{
							span[i] += 0.5f;
						}
					}
				}
			}
			foreach (Marker marker in analysis.Markers)
			{
				int num4 = ((marker.Slot >= 0) ? marker.Slot : marker.Near);
				if (num4 >= 0 && marker.TimeMs + 4000 >= timeMs && marker.TimeMs <= timeMs + 1000 && !(span[num4] < 0f))
				{
					span[num4] += Weight(marker.Kind);
				}
			}
			int num5 = -1;
			float num6 = -1f;
			for (int k = 0; k < 4; k++)
			{
				if (span[k] >= 0f && (num5 < 0 || span[k] > num6))
				{
					num5 = k;
					num6 = span[k];
				}
			}
			if (big != null)
			{
				foreach (KeyValuePair<int, (ulong, ulong, float)> enemy in state.Enemies)
				{
					enemy.Deconstruct(out var key, out var _);
					int num7 = key;
					float num8 = EnemyScore(state, num7, big);
					if (num8 > num6)
					{
						num5 = num7;
						num6 = num8;
					}
				}
			}
			float num9 = ((current >= 0 && current < 4) ? span[current] : ((current >= 4) ? EnemyScore(state, current, big) : (-1f)));
			if (current < 0 || num9 < 0f)
			{
				return num5;
			}
			if (num5 == current || timeMs - lastSwitchMs < 12000)
			{
				return current;
			}
			if (!(num6 > num9 * 1.3f))
			{
				return current;
			}
			return num5;
		}

		private static float EnemyScore(WorldState state, int entity, Func<ulong, bool>? big)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Invalid comparison between Unknown and I4
			bool flag = big == null;
			if (!flag)
			{
				bool flag2 = ((entity < 4 || entity >= 4096) ? true : false);
				flag = flag2;
			}
			if (flag || !state.Enemies.TryGetValue(entity, out (ulong, ulong, float) value) || !big(value.Item1))
			{
				return -1f;
			}
			ref Pose reference = ref state.Poses[entity];
			if (!reference.Present || (int)EnemyAlerts.Settle((EnemyAlert)(byte)(reference.State & 3), (int)state.EnemyLocomotion[entity]) != 3)
			{
				return -1f;
			}
			for (int i = 0; i < 4; i++)
			{
				ref Pose reference2 = ref state.Poses[i];
				if (reference2.Present)
				{
					float num = reference2.X - reference.X;
					float num2 = reference2.Y - reference.Y;
					float num3 = reference2.Z - reference.Z;
					if (num * num + num2 * num2 + num3 * num3 <= 225f)
					{
						return 7f;
					}
				}
			}
			return -1f;
		}
	}
	internal static class DataChunks
	{
		internal const ushort Delta = 1;

		internal const ushort Keyframe = 2;

		internal const ushort Footer = 3;
	}
	internal sealed class BlockPipeline
	{
		private sealed class Job
		{
			internal byte[] Buffer = Array.Empty<byte>();

			internal int Length;

			internal uint StartMs;

			internal uint EndMs;

			internal ushort Type;
		}

		private readonly ChunkWriter _writer;

		private readonly Action<string> _error;

		private readonly uint _blockMs;

		private readonly uint _keyframeMs;

		private readonly Action<BlockPipeline, uint> _fullState;

		private readonly SampleEncoder _encoder = new SampleEncoder();

		private readonly Stack<byte[]> _free = new Stack<byte[]>();

		private readonly Queue<Job> _queue = new Queue<Job>();

		private readonly Thread _thread;

		private readonly object _gate = new object();

		private byte[] _current;

		private uint _blockStart;

		private uint _lastKeyframe;

		private bool _currentIsKeyframe;

		private bool _keyframeNext;

		private bool _finishing;

		private bool _failed;

		private int _lostSamples;

		private int _lostEvents;

		private int _buffers;

		private int _maxQueue;

		internal bool Failed
		{
			get
			{
				lock (_gate)
				{
					return _failed;
				}
			}
		}

		internal int LostSamples => _lostSamples;

		internal int LostEvents => _lostEvents;

		internal int MaxQueue
		{
			get
			{
				lock (_gate)
				{
					return _maxQueue;
				}
			}
		}

		internal BlockPipeline(ChunkWriter writer, Action<string> error, Action<BlockPipeline, uint> fullState, uint startMs, int buffers = 4, int bufferBytes = 524288, uint blockMs = 2000u, uint keyframeMs = 30000u)
		{
			_writer = writer;
			_error = error;
			_fullState = fullState;
			_blockMs = blockMs;
			_keyframeMs = keyframeMs;
			_buffers = buffers;
			for (int i = 1; i < buffers; i++)
			{
				_free.Push(new byte[bufferBytes]);
			}
			_current = new byte[bufferBytes];
			_thread = new Thread(Run)
			{
				IsBackground = true,
				Name = "ForgeReplay writer"
			};
			_thread.Start();
			BeginBlock(startMs, keyframe: true);
		}

		internal bool Sample(uint timeMs, int entity, float x, float y, float z, float qx, float qy, float qz, float qw, byte state)
		{
			if (Failed)
			{
				return false;
			}
			if (_encoder.Sample(timeMs, entity, x, y, z, qx, qy, qz, qw, state))
			{
				return true;
			}
			if (_lostSamples++ == 0)
			{
				_error("The block buffer is full; samples are being dropped until the writer catches up.");
			}
			return false;
		}

		internal bool Event(uint timeMs, ushort type, ReadOnlySpan<byte> payload)
		{
			if (Failed)
			{
				return false;
			}
			if (_encoder.Event(timeMs, type, payload))
			{
				return true;
			}
			if (_lostEvents++ == 0)
			{
				_error("The block buffer is full; an event was lost.");
			}
			return false;
		}

		internal void Forget(int entity)
		{
			_encoder.Forget(entity);
		}

		internal void WaitForWriter()
		{
			lock (_gate)
			{
				while (!_failed && (_queue.Count > 0 || _free.Count < _buffers - 1))
				{
					Monitor.Wait(_gate, 50);
				}
			}
		}

		internal void KeyframeNext()
		{
			_keyframeNext = true;
		}

		internal void Tick(uint nowMs)
		{
			if (Failed || (!_keyframeNext && nowMs - _blockStart < _blockMs))
			{
				return;
			}
			byte[] array = null;
			lock (_gate)
			{
				if (_free.Count > 0)
				{
					array = _free.Pop();
				}
			}
			if (array != null)
			{
				byte[] current = _current;
				_current = array;
				Close(current, nowMs);
				BeginBlock(nowMs, _keyframeNext || nowMs - _lastKeyframe >= _keyframeMs);
				_keyframeNext = false;
			}
		}

		internal void Finish(uint nowMs, byte[]? footer = null)
		{
			if (!Failed)
			{
				Close(_current, nowMs);
			}
			lock (_gate)
			{
				_finishing = true;
				Monitor.PulseAll(_gate);
			}
			_thread.Join();
			if (Failed)
			{
				return;
			}
			try
			{
				if (footer != null)
				{
					_writer.Append((ushort)3, nowMs, nowMs, (ReadOnlySpan<byte>)footer);
				}
				_writer.Finish();
			}
			catch (Exception ex)
			{
				Fail("Finishing the recording failed: " + ex.Message);
			}
		}

		private void BeginBlock(uint startMs, bool keyframe)
		{
			_blockStart = startMs;
			_currentIsKeyframe = keyframe;
			if (keyframe)
			{
				_lastKeyframe = startMs;
			}
			_encoder.Begin(_current, startMs, keyframe);
			if (keyframe)
			{
				_fullState(this, startMs);
			}
		}

		private void Close(byte[] buffer, uint endMs)
		{
			Job item = new Job
			{
				Buffer = buffer,
				Length = _encoder.Length,
				StartMs = _blockStart,
				EndMs = endMs,
				Type = (ushort)((!_currentIsKeyframe) ? 1 : 2)
			};
			lock (_gate)
			{
				_queue.Enqueue(item);
				if (_queue.Count > _maxQueue)
				{
					_maxQueue = _queue.Count;
				}
				Monitor.PulseAll(_gate);
			}
		}

		private void Run()
		{
			while (true)
			{
				Job job;
				lock (_gate)
				{
					while (_queue.Count == 0)
					{
						if (_finishing)
						{
							return;
						}
						Monitor.Wait(_gate);
					}
					job = _queue.Dequeue();
				}
				if (!Failed)
				{
					try
					{
						_writer.Append(job.Type, job.StartMs, job.EndMs, new ReadOnlySpan<byte>(job.Buffer, 0, job.Length));
					}
					catch (Exception ex)
					{
						Fail("Writing a block failed, the recording stops: " + ex.Message);
					}
				}
				lock (_gate)
				{
					if (job.Buffer != _current)
					{
						_free.Push(job.Buffer);
					}
					Monitor.PulseAll(_gate);
				}
			}
		}

		private void Fail(string message)
		{
			lock (_gate)
			{
				if (_failed)
				{
					return;
				}
				_failed = true;
			}
			_error(message);
		}
	}
	internal static class BodyStates
	{
		internal const int FullBody = 1;

		internal const int AimOffset = 4;

		internal const int UpperBody = 5;

		internal const int Additive = 6;

		internal const int LeftHand = 7;

		internal const int RightHand = 8;

		internal const int Layers = 9;

		internal const int FullWeight = 10;

		internal static readonly int[] Recorded;

		internal const int FadeMs = 100;

		internal const int DeadMs = 2500;

		internal const int ReviveMs = 2300;

		internal const int EquipGunMs = 950;

		internal const int EquipMeleeMs = 720;

		internal const int ThrowMs = 520;

		internal const int SwingMs = 650;

		internal const int ReleaseMs = 600;

		internal const int ShoveMs = 600;

		internal const int RecoilMs = 320;

		private static readonly (int Hash, string Name)[] Seen;

		private static readonly (int Hash, string Name)[] NotSeen;

		private static readonly Dictionary<int, string> Names;

		private static readonly Dictionary<string, int> Hashes;

		private static readonly string[] Families;

		internal const int RifleFamily = 0;

		internal static int Dead => Of("Dead");

		internal static int DeadIdle => Of("Dead_idle");

		internal static int Revive => Of("Revive");

		internal static int UpperRest => Of("Spear_Idle");

		internal static int Empty => Of("empty");

		internal static int Recoil => Of("Rifle_Recoil");

		internal static IEnumerable<(int Hash, string Name)> Rows
		{
			get
			{
				(int Hash, string Name)[] seen = Seen;
				for (int i = 0; i < seen.Length; i++)
				{
					yield return seen[i];
				}
				seen = NotSeen;
				for (int i = 0; i < seen.Length; i++)
				{
					yield return seen[i];
				}
			}
		}

		internal static ulong Key(int slot, int layer)
		{
			return (ulong)(slot * 16 + layer);
		}

		internal static int InteractMs(int type)
		{
			switch (type)
			{
			case 1:
				return 1200;
			case 2:
			case 3:
				return 750;
			case 4:
				return 1650;
			default:
				return 1500;
			}
		}

		static BodyStates()
		{
			Recorded = new int[6] { 1, 4, 5, 6, 7, 8 };
			Seen = new(int, string)[130]
			{
				(-1822188247, "AmmoPack_idle"),
				(-920457963, "ClimbLadder"),
				(-1503198266, "ClimbLadderEnterBottom"),
				(-789000283, "ClimbLadderExitBottom"),
				(-352530914, "ClimbLadderExitTop"),
				(-1674048173, "ConsumablePack_Give"),
				(803981446, "ConsumablePack_Take"),
				(1035492301, "Consumable_Throw"),
				(1115759447, "Consumable_Throw_Charge"),
				(993993995, "Consumable_Throw_Charge_Idle"),
				(1293411866, "Dead"),
				(83611764, "Dead_idle"),
				(1901610868, "DefaultGrip"),
				(483441810, "Default_Movement"),
				(-1013317996, "DefoggerBig"),
				(-654811613, "Delivery_Bio_Tracker_1"),
				(700449694, "Delivery_Mine_Deployer_Direct_1"),
				(1594429564, "DisinfectionPack_idle"),
				(1032512850, "ElevatorHangIdle"),
				(1691821118, "EquipGeneric"),
				(819898422, "EquipKnife"),
				(-438472853, "EquipPrimary"),
				(1834056835, "EquipSecondary"),
				(-145735571, "EquipSledgehammer"),
				(352370365, "EquipSpear"),
				(-620049206, "EquipTool"),
				(1330988760, "FogRepeller"),
				(1741028529, "Fogrepeller_Throw"),
				(-928877594, "Fogrepeller_Throw_Charge"),
				(653427573, "Fogrepeller_Throw_Charge_Idle"),
				(-218021073, "Front_AutoShotgun_3_idle"),
				(-741382112, "Front_AutoShotgun_3_reload"),
				(1848035194, "Front_Machinegun_2_Animation_idle"),
				(-19522769, "Front_Machinegun_2_Animation_reload"),
				(534356912, "Front_Precision_2"),
				(1760124887, "Front_Precision_2_reload"),
				(397869626, "Front_Precision_3_Player_Idle"),
				(-442426492, "Front_Precision_3_Player_Reload"),
				(-1916873227, "Front_Revolver_2_Idle"),
				(-1317794437, "Front_Revolver_2_Reload"),
				(703862305, "Front_Rifle_1"),
				(-1325578341, "Front_Rifle_2"),
				(164621234, "Front_Rifle_2_reload"),
				(-1282331115, "Front_Rifle_3_idle"),
				(736282458, "Front_Rifle_3_reload_animation"),
				(-939384965, "Front_Shotgun_3"),
				(-1906472768, "Front_Shotgun_3_reload"),
				(1558948067, "Generator_Cell"),
				(1159820392, "GlueGrenade"),
				(-1213043458, "Knife_Charge_Left_Idle"),
				(1919317008, "Knife_Charge_Left_Release"),
				(-1463093082, "Knife_Charge_Left_Start"),
				(-2010534627, "Knife_Charge_Left_Start_Crouch"),
				(-1986326628, "Knife_Idle"),
				(-1761847882, "Knife_Idle_crouch"),
				(-564965284, "Knife_JumpLand"),
				(-1667255307, "Knife_JumpMidAir"),
				(1977237811, "Knife_JumpStart"),
				(-736558964, "Knife_Movement"),
				(-1322186900, "Knife_Stand_Shove"),
				(-1298775011, "Knife_SwingLeft"),
				(1436456992, "LockMelter"),
				(2038832366, "MediPack_idle"),
				(-1072057000, "Melee_JumpLand"),
				(680754764, "Melee_JumpMidAir"),
				(1923731407, "Melee_JumpStart"),
				(-900471416, "Melee_Movement"),
				(-1444512546, "Pickup_High"),
				(425517724, "Pickup_Low"),
				(-897945869, "Pickup_Mid"),
				(1342985417, "PistolAimOffset"),
				(-1670623806, "Pistol_JumpLand"),
				(1647296621, "Pistol_JumpStart"),
				(-1775887086, "Pistol_Movement"),
				(638613553, "Pistol_TurnL"),
				(-601930414, "Pistol_TurnR"),
				(726268102, "Player_Reviving_End_Crouch_A"),
				(1252081396, "Player_Reviving_Loop_Crouch_A"),
				(1717050679, "Player_Reviving_Start_Crouch_A"),
				(747021347, "Point_Forward"),
				(-323374038, "Revive"),
				(1044074034, "Rifle1_Reload"),
				(933186518, "RifleAimOffset"),
				(-67153187, "Rifle_JumpLand"),
				(1342791295, "Rifle_JumpMidAir"),
				(-280994169, "Rifle_JumpStart"),
				(-239795699, "Rifle_Movement"),
				(562291691, "Rifle_Recoil"),
				(-1461739520, "Rifle_TurnL"),
				(1389403491, "Rifle_TurnR"),
				(1685361460, "SMG_Front_3_Idle"),
				(-64297445, "SMG_Front_3_Reload"),
				(2037490572, "SMG_Front_4_Idle"),
				(-152047870, "SMG_Front_4_Reload"),
				(-881856248, "Short_Shotgun_2_Player_Idle"),
				(744829067, "Short_Shotgun_2_Player_Reload"),
				(-1346223135, "Shotgun_front_2_idle"),
				(-1479046558, "Shotgun_front_2_reloadPump"),
				(902343739, "SledgeHammer_fp_arms"),
				(-716001131, "Sledgehammer_Charge_Left_Idle"),
				(-1151125288, "Sledgehammer_Charge_Left_Release"),
				(1925750954, "Sledgehammer_Charge_Left_Start"),
				(1494636819, "Sledgehammer_Crouch_Shove"),
				(591244724, "Sledgehammer_Idle"),
				(-473234945, "Sledgehammer_Idle_crouch"),
				(-1006218459, "Sledgehammer_Stand_Shove"),
				(760775911, "Sledgehammer_SwingLeft"),
				(1772682815, "Spear_Charge_Left_Idle"),
				(1545509211, "Spear_Charge_Left_Release"),
				(995717778, "Spear_Charge_Left_Release_Crouch"),
				(1148653586, "Spear_Charge_Left_Start"),
				(-755339932, "Spear_Charge_Left_Start_Crouch"),
				(1429950081, "Spear_Idle"),
				(1213524166, "Spear_Idle_crouch"),
				(739908351, "Spear_JumpLand"),
				(989329963, "Spear_JumpStart"),
				(642796079, "Spear_Movement"),
				(-38011131, "Spear_SwingLeft"),
				(-593336433, "Spear_SwingLeft_crouch"),
				(1662624979, "Stock_Pistol_1"),
				(122605288, "Stock_Pistol_1_reload"),
				(-1959085039, "Stock_Precision_2"),
				(-634392596, "TerminalConsole_Idle"),
				(611019729, "Tool_Grip_2"),
				(85000065, "Tools_Grip_1"),
				(2022056779, "Turret_Base_1"),
				(1757887940, "empty"),
				(1592261978, "fps_hands_idle"),
				(-2073717886, "fps_shoulder_pose"),
				(564600263, "hackingtool_idle")
			};
			NotSeen = new(int, string)[6]
			{
				(937380992, "Consumable_Mine_Use"),
				(379251778, "Default_JumpLand"),
				(-1979073724, "Default_JumpMidAir"),
				(-1893878292, "Default_JumpStart"),
				(274414215, "Pistol_JumpMidAir"),
				(-1883503080, "Spear_JumpMidAir")
			};
			Names = new Dictionary<int, string>();
			Hashes = new Dictionary<string, int>();
			Families = new string[6] { "Rifle", "Pistol", "Melee", "Default", "Knife", "Spear" };
			(int, string)[][] array = new(int, string)[2][] { Seen, NotSeen };
			foreach ((int, string)[] array2 in array)
			{
				for (int j = 0; j < array2.Length; j++)
				{
					var (num, text) = array2[j];
					Names[num] = text;
					Hashes[text] = num;
				}
			}
		}

		internal static string? Name(int hash)
		{
			if (!Names.TryGetValue(hash, out string value))
			{
				return null;
			}
			return value;
		}

		private static int Of(string name)
		{
			return Hashes[name];
		}

		private static string Family(int family)
		{
			return Families[((uint)family < (uint)Families.Length) ? family : 0];
		}

		internal static int FullBodyState(int family, int locomotion, bool jumped = false)
		{
			return locomotion switch
			{
				3 => Of(Family(family) + "_JumpStart"), 
				4 => Of(Family(family) + (jumped ? "_JumpStart" : "_JumpMidAir")), 
				5 => Of(Family(family) + "_JumpLand"), 
				7 => Of("Dead"), 
				8 => Of("ClimbLadder"), 
				9 => Of("TerminalConsole_Idle"), 
				15 => Of("ElevatorHangIdle"), 
				_ => Of(Family(family) + "_Movement"), 
			};
		}

		internal static (int State, int Weight) Aim(int family)
		{
			return family switch
			{
				0 => (State: Of("RifleAimOffset"), Weight: 10), 
				1 => (State: Of("PistolAimOffset"), Weight: 10), 
				_ => (State: Of("RifleAimOffset"), Weight: 0), 
			};
		}

		internal static int EquipState(int slot)
		{
			return slot switch
			{
				1 => Of("EquipPrimary"), 
				2 => Of("EquipSecondary"), 
				3 => Of("EquipTool"), 
				10 => 0, 
				_ => Of("EquipGeneric"), 
			};
		}

		internal static string MeleePrefix(string idleName)
		{
			if (!idleName.EndsWith("_Idle", StringComparison.Ordinal))
			{
				return idleName;
			}
			return idleName.Substring(0, idleName.Length - 5);
		}

		internal static string MeleeEquip(string idleName)
		{
			return "Equip" + MeleePrefix(idleName);
		}

		internal static string MeleeShove(string idleName, bool crouched)
		{
			return MeleePrefix(idleName) + (crouched ? "_Crouch_Shove" : "_Stand_Shove");
		}

		internal static int InteractState(int type)
		{
			return type switch
			{
				0 => Of("Consumable_Mine_Use"), 
				1 => Of("Pickup_Low"), 
				2 => Of("Pickup_Mid"), 
				3 => Of("Pickup_High"), 
				4 => Of("Point_Forward"), 
				5 => Of("ConsumablePack_Give"), 
				6 => Of("ConsumablePack_Take"), 
				_ => 0, 
			};
		}

		internal static int ThrowState(int status)
		{
			return status switch
			{
				1 => Of("Consumable_Throw_Charge"), 
				2 => Of("Consumable_Throw"), 
				_ => 0, 
			};
		}
	}
	internal enum HurtSource : byte
	{
		Unknown,
		EnemyAttack,
		Tongue,
		Projectile,
		Explosion
	}
	internal readonly record struct InferredHurt(uint TimeMs, int Slot, float Fraction, HurtSource Source, int Entity);
	internal readonly record struct InferredWake(uint TimeMs, int Entity, int NoiseSlot, bool Ambiguous);
	internal readonly record struct InferredMine(uint TimeMs, ulong Key, int Owner);
	internal readonly record struct InferredPack(uint TimeMs, int User, int Receiver, float HealthFraction, int AmmoGained, int InfectionRemoved);
	internal readonly record struct InferredDodge(uint TimeMs, int Slot, int Entity, bool TargetRecorded = false);
	internal readonly record struct InferredRevive(uint TimeMs, int Slot, int Reviver);
	internal sealed class ClientInference
	{
		private readonly record struct Cause(uint TimeMs, HurtSource Source, int Entity, float X, float Y, float Z);

		private readonly record struct Noise(uint TimeMs, int Slot, float X, float Y, float Z, float Radius);

		private readonly record struct Use(uint TimeMs, int User, int Kind);

		private readonly record struct Place(uint TimeMs, int Slot);

		private readonly record struct Tongue(uint TimeMs, int Entity, float X, float Y, float Z, int Target, bool TargetRecorded);

		private readonly record struct Drop(uint TimeMs, int Slot, float Fraction, bool Placed, float X, float Y, float Z);

		private readonly record struct Wakeup(uint TimeMs, int Entity, bool Placed, float X, float Y, float Z, Hearing? Hearing, int Runners);

		internal const uint HurtBeforeMs = 1500u;

		internal const uint HurtAfterMs = 100u;

		internal const uint WakeBeforeMs = 3000u;

		internal const uint WakeAfterMs = 200u;

		internal const uint WakeTieMs = 250u;

		internal const uint UseWindowMs = 3000u;

		internal const uint MineWindowMs = 6000u;

		internal const float AttackReach = 3f;

		internal const float ExplosionReach = 8f;

		internal const float ProjectileReach = 15f;

		internal const float MineReach = 6f;

		internal const float ReviveReach = 3f;

		internal const float TongueReach = 3f;

		internal const int PackHealthBytes = 3;

		private readonly Func<ulong, Hearing?>? _hearingOf;

		private const int Downed = 7;

		private const int GrabbedByTrap = 12;

		private const int GrabbedByTank = 13;

		private const int GrabbedByPouncer = 16;

		private const int GiveResource = 5;

		private const int ConsumeResource = 6;

		private const int PlaceTripmine = 0;

		private const int Sleeping = 1;

		private const int Awake = 2;

		private readonly WorldState _state;

		private readonly NoiseRebuild _rebuild;

		private readonly int[] _health = new int[4] { -1, -1, -1, -1 };

		private readonly uint[] _lastDropMs = new uint[4];

		private readonly uint[] _grabbedMs = new uint[4];

		private readonly uint[] _downedMs = new uint[4];

		private const uint ReviveHealthMs = 4000u;

		private readonly int[] _infection = new int[4] { -1, -1, -1, -1 };

		private readonly int[,] _ammo = new int[4, 3]
		{
			{ -1, -1, -1 },
			{ -1, -1, -1 },
			{ -1, -1, -1 },
			{ -1, -1, -1 }
		};

		private readonly bool[] _healthSeen = new bool[4];

		private readonly Dictionary<int, int> _alert = new Dictionary<int, int>();

		private readonly HashSet<ulong> _mines = new HashSet<ulong>();

		private readonly List<Cause> _causes = new List<Cause>();

		private readonly List<Noise> _noises = new List<Noise>();

		private readonly List<Use> _uses = new List<Use>();

		private readonly List<Place> _places = new List<Place>();

		private readonly Dictionary<int, Tongue> _tongues = new Dictionary<int, Tongue>();

		private readonly List<Drop> _drops = new List<Drop>();

		private readonly List<Wakeup> _wakeups = new List<Wakeup>();

		private readonly List<(uint TimeMs, int Slot)> _candidates = new List<(uint, int)>();

		private uint _maxMs;

		private uint _slackMs;

		private int _causeFrom;

		private int _noiseFrom;

		private int _actionFrom;

		internal List<InferredHurt> Hurts { get; } = new List<InferredHurt>();

		internal List<InferredWake> Wakes { get; } = new List<InferredWake>();

		internal List<InferredMine> Mines { get; } = new List<InferredMine>();

		internal List<InferredPack> Packs { get; } = new List<InferredPack>();

		internal List<InferredDodge> Dodges { get; } = new List<InferredDodge>();

		internal List<InferredRevive> Revives { get; } = new List<InferredRevive>();

		internal IReadOnlyList<PlayerAction> Actions => _rebuild.Actions;

		internal long Checked { get; private set; }

		internal static bool Grabbed(int locomotion)
		{
			if ((uint)(locomotion - 12) <= 1u || locomotion == 16)
			{
				return true;
			}
			return false;
		}

		internal ClientInference(WorldState state, Func<ulong, Hearing?>? hearingOf = null)
		{
			_state = state;
			_rebuild = new NoiseRebuild(state);
			_hearingOf = hearingOf;
		}

		private void At(uint timeMs)
		{
			if (timeMs < _maxMs)
			{
				_slackMs = Math.Max(_slackMs, _maxMs - timeMs);
			}
			else
			{
				_maxMs = timeMs;
			}
		}

		internal bool HealthSeen(int slot)
		{
			return _healthSeen[slot & 3];
		}

		internal float TakenFraction(int slot)
		{
			float num = 0f;
			foreach (InferredHurt hurt in Hurts)
			{
				if (hurt.Slot == (slot & 3))
				{
					num += hurt.Fraction;
				}
			}
			return num;
		}

		internal void Sample(uint timeMs, int entity, byte state)
		{
			At(timeMs);
			if (entity < 4)
			{
				int num = _health[entity];
				_health[entity] = state;
				_healthSeen[entity] = true;
				if (num >= 0)
				{
					if (state < num)
					{
						float x;
						float y;
						float z;
						bool placed = Where(entity, out x, out y, out z);
						_drops.Add(new Drop(timeMs, entity, (float)(num - state) / 127f, placed, x, y, z));
						_lastDropMs[entity] = timeMs;
					}
					else if (state - num >= 3 && (_downedMs[entity] == 0 || timeMs - _downedMs[entity] > 4000))
					{
						Gained(timeMs, entity, (float)(state - num) / 127f, 0, 0);
					}
				}
			}
			else
			{
				int num2 = state & 3;
				if (_alert.TryGetValue(entity, out var value) && value == 1 && num2 >= 2)
				{
					Woke(timeMs, entity);
				}
				_alert[entity] = num2;
			}
		}

		internal void Take(uint timeMs, ushort type, byte[] payload)
		{
			At(timeMs);
			_rebuild.Take(timeMs, type, new PayloadReader(payload));
			PayloadReader payloadReader = new PayloadReader(payload);
			switch (type)
			{
			case 2:
			{
				int key = (int)payloadReader.U();
				_alert.Remove(key);
				_tongues.Remove(key);
				break;
			}
			case 49:
			{
				int entity = (int)payloadReader.U();
				payloadReader.U();
				payloadReader.U();
				var (x4, y4, z4) = payloadReader.Pos();
				_causes.Add(new Cause(timeMs, HurtSource.EnemyAttack, entity, x4, y4, z4));
				break;
			}
			case 36:
			{
				int num7 = (int)payloadReader.U();
				ulong num8 = payloadReader.U();
				var (x, y, z) = payloadReader.Pos();
				switch (num8)
				{
				case 0uL:
					_causes.Add(new Cause(timeMs, HurtSource.Tongue, num7, x, y, z));
					_tongues[num7] = new Tongue(timeMs, num7, x, y, z, (int)payloadReader.U() - 1, TargetRecorded: true);
					break;
				case 1uL:
					Retracted(timeMs, num7);
					break;
				}
				break;
			}
			case 37:
				if (payloadReader.U() == 0L)
				{
					payloadReader.U();
					var (x6, y6, z6) = payloadReader.Pos();
					_causes.Add(new Cause(timeMs, HurtSource.Projectile, -1, x6, y6, z6));
				}
				break;
			case 35:
				payloadReader.U();
				var (x2, y2, z2) = payloadReader.Pos();
				_causes.Add(new Cause(timeMs, HurtSource.Explosion, -1, x2, y2, z2));
				break;
			case 40:
			{
				ulong num9 = payloadReader.U();
				payloadReader.U();
				var (x3, y3, z3) = payloadReader.Pos();
				_noises.Add(new Noise(timeMs, (num9 > 3) ? (-1) : ((int)num9), x3, y3, z3, (float)payloadReader.U() / 10f));
				break;
			}
			case 30:
			{
				int num11 = (int)payloadReader.U() & 3;
				int num12 = (int)payloadReader.U();
				bool flag;
				switch (num12)
				{
				case 0:
					_places.Add(new Place(timeMs, num11));
					return;
				case 5:
				case 6:
					flag = true;
					break;
				default:
					flag = false;
					break;
				}
				if (flag)
				{
					_uses.Add(new Use(timeMs, num11, num12));
				}
				break;
			}
			case 34:
			{
				ulong num13 = payloadReader.U();
				ulong num14 = payloadReader.U();
				payloadReader.U();
				var (x5, y5, z5) = payloadReader.Pos();
				if (num14 == 0L && _mines.Add(num13))
				{
					Mines.Add(new InferredMine(timeMs, num13, MineOwner(timeMs, x5, y5, z5)));
				}
				break;
			}
			case 14:
			{
				int num10 = (int)payloadReader.U() & 3;
				Revives.Add(new InferredRevive(timeMs, num10, Reviver(num10)));
				break;
			}
			case 10:
			{
				int num = (int)payloadReader.U() & 3;
				int num2 = (int)payloadReader.U();
				payloadReader.U();
				int num3 = (int)payloadReader.U();
				if (num2 == 7)
				{
					_downedMs[num] = timeMs | 1;
				}
				int num4 = 0;
				for (int i = 0; i < 3; i++)
				{
					int num5 = (int)payloadReader.U();
					if (_ammo[num, i] >= 0 && num5 > _ammo[num, i])
					{
						num4 += num5 - _ammo[num, i];
					}
					_ammo[num, i] = num5;
				}
				int num6 = ((_infection[num] >= 0 && num3 < _infection[num]) ? (_infection[num] - num3) : 0);
				_infection[num] = num3;
				if (Grabbed(num2))
				{
					_grabbedMs[num] = timeMs;
				}
				if (num4 > 0 || num6 > 0)
				{
					Gained(timeMs, num, 0f, num4, num6);
				}
				break;
			}
			}
		}

		internal void Finish()
		{
			foreach (Drop drop in _drops)
			{
				Hurts.Add(Settle(drop));
			}
			_drops.Clear();
			foreach (Wakeup wakeup in _wakeups)
			{
				Wakes.Add(Settle(wakeup));
			}
			_wakeups.Clear();
			_causes.Clear();
			_noises.Clear();
			_causeFrom = (_noiseFrom = (_actionFrom = 0));
		}

		private int From<T>(List<T> list, Func<T, uint> time, ref int from, uint timeMs, uint before)
		{
			while (from < list.Count && (long)time(list[from]) + (long)before + _slackMs < timeMs)
			{
				from++;
			}
			return from;
		}

		private bool Past(uint entryMs, uint timeMs, uint after)
		{
			return entryMs > (long)timeMs + (long)after + _slackMs;
		}

		private bool Where(int entity, out float x, out float y, out float z)
		{
			ref Pose reference = ref _state.Poses[entity];
			x = reference.X;
			y = reference.Y;
			z = reference.Z;
			return reference.Present;
		}

		private static float Squared(float ax, float ay, float az, float bx, float by, float bz)
		{
			return (ax - bx) * (ax - bx) + (ay - by) * (ay - by) + (az - bz) * (az - bz);
		}

		private InferredHurt Settle(Drop drop)
		{
			HurtSource source = HurtSource.Unknown;
			int entity = -1;
			if (drop.Placed)
			{
				float num = float.MaxValue;
				for (int num2 = From(_causes, (Cause c) => c.TimeMs, ref _causeFrom, drop.TimeMs, 1500u); num2 < _causes.Count; num2++)
				{
					Cause cause = _causes[num2];
					if (Past(cause.TimeMs, drop.TimeMs, 100u))
					{
						break;
					}
					Checked++;
					if (cause.TimeMs + 1500 < drop.TimeMs || cause.TimeMs > drop.TimeMs + 100)
					{
						continue;
					}
					float num3 = cause.Source switch
					{
						HurtSource.Explosion => 8f, 
						HurtSource.Projectile => 15f, 
						_ => 3f, 
					};
					float num4 = Squared(cause.X, cause.Y, cause.Z, drop.X, drop.Y, drop.Z);
					if (!(num4 > num3 * num3))
					{
						float num5 = (float)Math.Abs((long)drop.TimeMs - (long)cause.TimeMs) * 1000f + num4;
						if (num5 < num)
						{
							num = num5;
							source = cause.Source;
							entity = cause.Entity;
						}
					}
				}
			}
			return new InferredHurt(drop.TimeMs, drop.Slot, drop.Fraction, source, entity);
		}

		private void Woke(uint timeMs, int entity)
		{
			float x;
			float y;
			float z;
			bool flag = Where(entity, out x, out y, out z);
			(ulong, ulong, float) value;
			Hearing? hearing = ((!_state.Enemies.TryGetValue(entity, out value)) ? ((Hearing?)null) : _hearingOf?.Invoke(value.Item1));
			int num = 0;
			if (flag && hearing.HasValue)
			{
				Hearing valueOrDefault = hearing.GetValueOrDefault();
				if (valueOrDefault.Movement > 0f)
				{
					for (int i = 0; i < 4; i++)
					{
						if (_rebuild.Locomotion(i) == 2 && Where(i, out var x2, out var y2, out var z2) && Squared(x2, y2, z2, x, y, z) <= valueOrDefault.Movement * valueOrDefault.Movement)
						{
							num |= 1 << i;
						}
					}
				}
			}
			_wakeups.Add(new Wakeup(timeMs, entity, flag, x, y, z, hearing, num));
		}

		private InferredWake Settle(Wakeup wake)
		{
			if (!wake.Placed)
			{
				return new InferredWake(wake.TimeMs, wake.Entity, -1, Ambiguous: false);
			}
			_candidates.Clear();
			for (int i = 0; i < 4; i++)
			{
				if ((wake.Runners & (1 << i)) != 0)
				{
					_candidates.Add((wake.TimeMs, i));
				}
			}
			for (int num = From(_noises, (Noise n) => n.TimeMs, ref _noiseFrom, wake.TimeMs, 3000u); num < _noises.Count; num++)
			{
				Noise noise = _noises[num];
				if (Past(noise.TimeMs, wake.TimeMs, 200u))
				{
					break;
				}
				Checked++;
				if (noise.TimeMs + 3000 >= wake.TimeMs && noise.TimeMs <= wake.TimeMs + 200 && Squared(noise.X, noise.Y, noise.Z, wake.X, wake.Y, wake.Z) <= noise.Radius * noise.Radius)
				{
					_candidates.Add((noise.TimeMs, noise.Slot));
				}
			}
			Hearing? hearing = wake.Hearing;
			if (hearing.HasValue)
			{
				Hearing valueOrDefault = hearing.GetValueOrDefault();
				List<PlayerAction> actions = _rebuild.Actions;
				for (int num2 = From(actions, (PlayerAction a) => a.TimeMs, ref _actionFrom, wake.TimeMs, 3000u); num2 < actions.Count; num2++)
				{
					PlayerAction playerAction = actions[num2];
					if (Past(playerAction.TimeMs, wake.TimeMs, 200u))
					{
						break;
					}
					Checked++;
					if (playerAction.TimeMs + 3000 >= wake.TimeMs && playerAction.TimeMs <= wake.TimeMs + 200)
					{
						float num3 = NoiseRebuild.Reach(playerAction.Action, valueOrDefault);
						if (num3 > 0f && !(Squared(playerAction.X, playerAction.Y, playerAction.Z, wake.X, wake.Y, wake.Z) > num3 * num3))
						{
							_candidates.Add((playerAction.TimeMs, playerAction.Slot));
						}
					}
				}
			}
			if (_candidates.Count == 0)
			{
				return new InferredWake(wake.TimeMs, wake.Entity, -1, Ambiguous: false);
			}
			(uint, int) tuple = _candidates[0];
			foreach (var candidate in _candidates)
			{
				if (Math.Abs((long)wake.TimeMs - (long)candidate.TimeMs) < Math.Abs((long)wake.TimeMs - (long)tuple.Item1))
				{
					tuple = candidate;
				}
			}
			foreach (var candidate2 in _candidates)
			{
				if (candidate2.Slot != tuple.Item2 && Math.Abs((long)candidate2.TimeMs - (long)tuple.Item1) <= 250)
				{
					return new InferredWake(wake.TimeMs, wake.Entity, -1, Ambiguous: true);
				}
			}
			return new InferredWake(wake.TimeMs, wake.Entity, tuple.Item2, Ambiguous: false);
		}

		private int MineOwner(uint timeMs, float x, float y, float z)
		{
			int result = -1;
			long num = 0L;
			foreach (Place place in _places)
			{
				if (place.TimeMs <= timeMs && place.TimeMs + 6000 >= timeMs && Where(place.Slot, out var x2, out var y2, out var z2) && !(Squared(x2, y2, z2, x, y, z) > 36f) && place.TimeMs >= num)
				{
					num = place.TimeMs;
					result = place.Slot;
				}
			}
			return result;
		}

		private int Reviver(int downed)
		{
			if (!Where(downed, out var x, out var y, out var z))
			{
				return -1;
			}
			int result = -1;
			float num = 9f;
			for (int i = 0; i < 4; i++)
			{
				if (i != downed && _rebuild.Locomotion(i) != 7 && Where(i, out var x2, out var y2, out var z2))
				{
					float num2 = Squared(x2, y2, z2, x, y, z);
					if (num2 <= num)
					{
						num = num2;
						result = i;
					}
				}
			}
			return result;
		}

		private void Gained(uint timeMs, int receiver, float health, int ammo, int infection)
		{
			int num = _uses.Count - 1;
			while (num >= 0)
			{
				Use use = _uses[num];
				if (use.TimeMs + 3000 >= timeMs)
				{
					if (use.TimeMs <= timeMs && use.Kind == 6 == (use.User == receiver))
					{
						Packs.Add(new InferredPack(timeMs, use.User, receiver, health, ammo, infection));
						_uses.RemoveAt(num);
						break;
					}
					num--;
					continue;
				}
				break;
			}
		}

		private void Retracted(uint timeMs, int entity)
		{
			if (!_tongues.Remove(entity, out var value))
			{
				return;
			}
			int num = value.Target;
			float num2 = 9f;
			for (int i = 0; i < 4; i++)
			{
				if (value.TargetRecorded)
				{
					break;
				}
				if (Where(i, out var x, out var y, out var z))
				{
					float num3 = Squared(x, y, z, value.X, value.Y, value.Z);
					if (num3 <= num2)
					{
						num2 = num3;
						num = i;
					}
				}
			}
			if ((num >= 0 && num <= 3) || 1 == 0)
			{
				bool flag = Grabbed(_rebuild.Locomotion(num)) || (_grabbedMs[num] >= value.TimeMs && _grabbedMs[num] != 0);
				if (!((_lastDropMs[num] >= value.TimeMs && _lastDropMs[num] != 0) || flag))
				{
					Dodges.Add(new InferredDodge(timeMs, num, entity, value.TargetRecorded));
				}
			}
		}
	}
	internal sealed class CorpseBook<T> where T : class
	{
		internal const float KeepSeconds = 15f;

		private readonly List<(T Body, float Since)> _bodies = new List<(T, float)>();

		internal int Count => _bodies.Count;

		internal void Add(T body, float now)
		{
			_bodies.Add((body, now));
		}

		internal void Due(float now, Action<T> hide)
		{
			for (int num = _bodies.Count - 1; num >= 0; num--)
			{
				if (!(now - _bodies[num].Since < 15f))
				{
					hide(_bodies[num].Body);
					_bodies.RemoveAt(num);
				}
			}
		}

		internal void All(Action<T> hide)
		{
			foreach (var body in _bodies)
			{
				T item = body.Body;
				hide(item);
			}
			_bodies.Clear();
		}
	}
	internal readonly record struct GunDamage(float Damage, float FalloffStart, float FalloffEnd, float Precision, int Booster = 0, bool Piercing = false, float SentryLong = 0f, float SentryShort = 0f)
	{
		private const float FalloffFloor = 0.1f;

		internal float At(float metres)
		{
			if (metres <= FalloffStart)
			{
				return Damage;
			}
			if (FalloffEnd <= FalloffStart)
			{
				return Damage * 0.1f;
			}
			return Damage * Math.Max(0.1f, 1f - (metres - FalloffStart) / (FalloffEnd - FalloffStart));
		}
	}
	internal readonly record struct SwingDamage(float Light, float Charged, float LightPrecision, float ChargedPrecision, float LightBack, float ChargedBack, float LightSleeper, float ChargedSleeper, float FullCharge, float Reach, bool Multiple, float LightFrom, float LightTo, float ChargedFrom, float ChargedTo)
	{
		internal float Share(float heldSeconds)
		{
			float num = ((FullCharge > 0f) ? Math.Clamp(heldSeconds / FullCharge, 0f, 1f) : 1f);
			return num * num * num;
		}
	}
	internal readonly record struct EnemyLimbs(float Weak, float Armour, bool FromBehind);
	internal sealed record DamageData(Func<ulong, GunDamage?> Gun, Func<ulong, EnemyLimbs?> Enemy, Func<uint, SwingDamage?> Swing, Func<uint, int?>? Booster = null, Func<ulong, ulong?>? SentryGun = null);
	internal readonly record struct EstimatedHit(uint TimeMs, int Slot, int Kind, int Wielded, float Damage);
	internal sealed class DamageEstimate
	{
		private readonly record struct Hit(uint TimeMs, int Slot, int Kind, int Wielded, float Base, float Precision, bool Struck = false);

		private sealed class Enemy
		{
			internal ulong Data;

			internal float Full;

			internal float Taken;

			internal bool Died;

			internal readonly List<Hit> Hits = new List<Hit>();
		}

		private readonly DamageData _data;

		private readonly Dictionary<int, Enemy> _open = new Dictionary<int, Enemy>();

		private readonly List<Enemy> _closed = new List<Enemy>();

		private bool _struck;

		private const float BehindFrom = 0.25f;

		private const float Backstab