Decompiled source of PoVBalanceLog v1.1.0

PoVBalanceLog.dll

Decompiled 6 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using PassiveTree;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("PoVBalanceLog")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("PoVBalanceLog")]
[assembly: AssemblyTitle("PoVBalanceLog")]
[assembly: AssemblyVersion("1.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoVBalanceLog
{
	[BepInPlugin("groshyr.povbalancelog", "PoVBalanceLog", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private struct Actor
		{
			public string Prefab;

			public string Biome;

			public bool? Boss;

			public bool? IsPlayer;

			public int? Stars;

			public int? Level;

			public string[] Mods;
		}

		private struct RecentHit
		{
			public double Time;

			public Actor Attacker;

			public Outcome Outcome;

			public string HitType;

			public bool Dot;

			public float Total;

			public float HpLoss;

			public float? Absorbed;

			public float Taken => HpLoss + Absorbed.GetValueOrDefault();
		}

		private struct FightEnemy
		{
			public Actor Actor;

			public bool Killed;
		}

		private sealed class Fight
		{
			public double Start;

			public double StartStamp;

			public double Last;

			public double LastStamp;

			public float Taken;

			public float Absorbed;

			public float Dealt;

			public float HpMin;

			public float HpMax;

			public int Potions;

			public int HitsIn;

			public readonly int[] Counts = new int[Outcomes.Length];

			public readonly Dictionary<ZDOID, FightEnemy> Enemies = new Dictionary<ZDOID, FightEnemy>();

			public string Biome;
		}

		private sealed class Target
		{
			public Character Character;

			public Actor Actor;

			public double Start;

			public float MaxHealth;

			public float Dealt;

			public bool Others;
		}

		[HarmonyPatch(typeof(Character), "Damage")]
		private static class OutgoingHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(0)]
			private static void BeforeOutgoing(Character __instance, HitData hit)
			{
				try
				{
					Plugin instance = Plugin.instance;
					Player localPlayer = Player.m_localPlayer;
					if (!((Object)(object)instance == (Object)null) && instance.recording && Object.op_Implicit((Object)(object)localPlayer) && !((Object)(object)__instance == (Object)(object)localPlayer) && hit != null && hit.HaveAttacker() && !((Object)(object)hit.GetAttacker() != (Object)(object)localPlayer))
					{
						instance.NoteOutgoing(localPlayer, __instance, hit);
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "BeforeOutgoing");
				}
			}
		}

		[HarmonyPatch(typeof(Player), "OnDeath")]
		private static class DeathHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void BeforeDeath(Player __instance)
			{
				try
				{
					Plugin instance = Plugin.instance;
					if ((Object)(object)instance != (Object)null && instance.recording && (Object)(object)__instance == (Object)(object)Player.m_localPlayer)
					{
						instance.NoteDeath(__instance);
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "BeforeDeath");
				}
			}
		}

		[HarmonyPatch(typeof(Player), "ConsumeItem")]
		private static class PotionHook
		{
			[HarmonyPostfix]
			private static void AfterPotion(Player __instance, ItemData item, bool __result)
			{
				try
				{
					Plugin instance = Plugin.instance;
					if (!((Object)(object)instance == (Object)null) && instance.recording && __result && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && instance.fight != null && !(Time.realtimeSinceStartupAsDouble - instance.fight.Last >= 10.0))
					{
						StatusEffect obj = item?.m_shared.m_consumeStatusEffect;
						SE_Stats val = (SE_Stats)(object)((obj is SE_Stats) ? obj : null);
						if (val != null && (val.m_healthUpFront > 0f || val.m_healthPerTick > 0f || val.m_healthOverTime > 0f || val.m_staminaUpFront > 0f || val.m_staminaOverTime > 0f || val.m_eitrUpFront > 0f || val.m_eitrOverTime > 0f || val.m_healthRegenMultiplier > 1f || val.m_staminaRegenMultiplier > 1f || val.m_eitrRegenMultiplier > 1f))
						{
							instance.fight.Potions++;
						}
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "AfterPotion");
				}
			}
		}

		private enum Outcome
		{
			Evaded,
			Blocked,
			Parried,
			Glancing,
			Hit
		}

		private sealed class HitCapture
		{
			public HitCapture Parent;

			public HitData Data;

			public Actor Attacker;

			public ZDOID AttackerId;

			public string Kind;

			public string HitType;

			public Vector3 Pos;

			public double Time;

			public double Stamp;

			public float Total;

			public float Phys;

			public float Elem;

			public float Spirit;

			public float Poison;

			public float HpLoss;

			public float? BaseTotal;

			public float? HpBefore;

			public float? HpAfter;

			public float? HpMax;

			public float? ShieldBefore;

			public float? ShieldMax;

			public float? ShieldAbsorbed;

			public float? AfterBlock;

			public float? AfterArmor;

			public float? AfterArmorPhys;

			public float? Armor;

			public float? Pen;

			public float? MeasuredArmor;

			public float? MeasuredPen;

			public bool Dodge;

			public bool Glancing;

			public bool Blocking;

			public bool Blocked;

			public bool Parried;

			public bool Applied;

			public bool Dot;
		}

		private struct ApplyState
		{
			public HitCapture Capture;

			public bool Standalone;

			public float Health;
		}

		private sealed class RpcFrame
		{
			public HitCapture Capture;

			public RpcFrame Outer;
		}

		[HarmonyPatch(typeof(Character), "RPC_Damage")]
		private static class IncomingHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(1800)]
			[HarmonyBefore(new string[] { "treextr.pathofvalheiman" })]
			private static void BeforeIncoming(Character __instance, HitData hit, out RpcFrame __state)
			{
				__state = null;
				try
				{
					Plugin instance = Plugin.instance;
					Player localPlayer = Player.m_localPlayer;
					if (!((Object)(object)instance == (Object)null) && instance.recording && Object.op_Implicit((Object)(object)localPlayer) && !((Object)(object)__instance != (Object)(object)localPlayer) && ((Character)localPlayer).IsOwner())
					{
						__state = new RpcFrame
						{
							Capture = instance.StartHit(localPlayer, hit, rpc: true),
							Outer = rpcFrame
						};
						rpcFrame = __state;
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "BeforeIncoming");
				}
			}

			[HarmonyFinalizer]
			[HarmonyPriority(0)]
			private static void FinishIncoming(RpcFrame __state)
			{
				try
				{
					if (__state != null)
					{
						rpcFrame = __state.Outer;
						HitCapture capture = __state.Capture;
						if (capture != null)
						{
							incoming = capture.Parent;
							instance?.CompleteHit(capture);
						}
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "FinishIncoming");
				}
			}
		}

		[HarmonyPatch(typeof(Character), "RPC_Damage")]
		private static class ScaledHitHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(799)]
			private static void FollowScaledHit(Character __instance, HitData hit)
			{
				try
				{
					HitCapture hitCapture = FrameCapture(__instance, hit);
					if (hitCapture != null)
					{
						hitCapture.Data = hit;
						if (!hitCapture.Dodge && hit.GetTotalDamage() > 0f)
						{
							hitCapture.BaseTotal = hitCapture.Total;
							ReadAmounts(hitCapture, hit);
						}
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "FollowScaledHit");
				}
			}
		}

		[HarmonyPatch(typeof(Character), "RPC_Damage")]
		private static class FinalHitHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(0)]
			private static void FollowFinalHit(Character __instance, HitData hit)
			{
				try
				{
					HitCapture hitCapture = FrameCapture(__instance, hit);
					if (hitCapture != null)
					{
						hitCapture.Data = hit;
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "FollowFinalHit");
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "BlockAttack")]
		private static class BlockHook
		{
			private static readonly FieldInfo BlockTimer = AccessTools.Field(typeof(Humanoid), "m_blockTimer");

			[HarmonyPrefix]
			[HarmonyPriority(0)]
			private static void BeforeBlock(Humanoid __instance, HitData hit, Character attacker, out bool __state)
			{
				__state = false;
				try
				{
					HitCapture hitCapture = Match(hit);
					if (hitCapture == null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
					{
						return;
					}
					hitCapture.Blocking = true;
					if (!Object.op_Implicit((Object)(object)attacker))
					{
						return;
					}
					ItemData val = __instance.LeftItem ?? __instance.GetCurrentWeapon();
					if (val != null && !(val.m_shared.m_timedBlockBonus <= 1f))
					{
						if (BlockTimer == null)
						{
							throw new MissingFieldException(typeof(Humanoid).Name, "m_blockTimer");
						}
						float num = (float)BlockTimer.GetValue(__instance);
						__state = num != -1f && num < ParryWindow.Seconds(__instance);
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "BeforeBlock");
				}
			}

			[HarmonyPostfix]
			[HarmonyPriority(0)]
			[HarmonyAfter(new string[] { "treextr.pathofvalheiman" })]
			private static void AfterBlock(Humanoid __instance, HitData hit, bool __result, bool __state)
			{
				try
				{
					HitCapture hitCapture = Match(hit);
					if (hitCapture != null && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
					{
						hitCapture.AfterBlock = hit.GetTotalDamage();
						hitCapture.Parried = __result && hitCapture.Blocked && __state;
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "AfterBlock");
				}
			}

			[HarmonyFinalizer]
			private static void FinishBlock(Humanoid __instance, HitData hit)
			{
				try
				{
					HitCapture hitCapture = Match(hit);
					if (hitCapture != null && (Object)(object)__instance == (Object)(object)Player.m_localPlayer)
					{
						hitCapture.Blocking = false;
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "FinishBlock");
				}
			}
		}

		[HarmonyPatch(typeof(HitData), "BlockDamage")]
		private static class BlockDamageHook
		{
			[HarmonyPostfix]
			private static void MarkSuccessfulBlock(HitData __instance)
			{
				try
				{
					HitCapture hitCapture = Match(__instance);
					if (hitCapture != null && hitCapture.Blocking)
					{
						hitCapture.Blocked = true;
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "MarkSuccessfulBlock");
				}
			}
		}

		[HarmonyPatch(typeof(Glancing), "Roll")]
		private static class GlancingHook
		{
			[HarmonyPostfix]
			private static void AfterGlancing(Character c, HitData hit, float __result)
			{
				try
				{
					HitCapture hitCapture = Match(hit);
					if (hitCapture != null && (Object)(object)c == (Object)(object)Player.m_localPlayer && __result > 0f)
					{
						hitCapture.Glancing = true;
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "AfterGlancing");
				}
			}
		}

		[HarmonyPatch(typeof(Player), "GetBodyArmor")]
		private static class BodyArmorHook
		{
			[HarmonyPostfix]
			[HarmonyPriority(100)]
			private static void BeforePenetration(Player __instance, float __result)
			{
				try
				{
					if (incoming != null && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
					{
						incoming.MeasuredArmor = __result;
						incoming.MeasuredPen = ArmorPen.Pending;
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "BeforePenetration");
				}
			}
		}

		[HarmonyPatch(typeof(HitData), "ApplyArmor", new Type[] { typeof(float) })]
		private static class ArmorHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void AtArmor(HitData __instance)
			{
				try
				{
					HitCapture hitCapture = Match(__instance);
					if (hitCapture != null)
					{
						hitCapture.Armor = hitCapture.MeasuredArmor;
						hitCapture.Pen = hitCapture.MeasuredPen;
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "AtArmor");
				}
			}

			[HarmonyPostfix]
			[HarmonyPriority(0)]
			private static void AfterArmor(HitData __instance)
			{
				try
				{
					HitCapture hitCapture = Match(__instance);
					if (hitCapture != null)
					{
						hitCapture.AfterArmor = __instance.GetTotalDamage();
						hitCapture.AfterArmorPhys = Physical(__instance);
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "AfterArmor");
				}
			}
		}

		[HarmonyPatch(typeof(EnergyShield), "Absorb")]
		private static class ShieldHook
		{
			[HarmonyPrefix]
			private static void BeforeShield(HitData hit, out float? __state)
			{
				__state = null;
				try
				{
					if (Match(hit) != null)
					{
						__state = hit.GetTotalDamage();
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "BeforeShield");
				}
			}

			[HarmonyPostfix]
			private static void AfterShield(HitData hit, float? __state)
			{
				try
				{
					HitCapture hitCapture = Match(hit);
					if (hitCapture != null && __state.HasValue)
					{
						hitCapture.ShieldAbsorbed += Mathf.Max(0f, __state.Value - hit.GetTotalDamage());
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "AfterShield");
				}
			}
		}

		[HarmonyPatch(typeof(Character), "ApplyDamage")]
		private static class HealthHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(800)]
			[HarmonyBefore(new string[] { "treextr.pathofvalheiman" })]
			private static void BeforeHealth(Character __instance, HitData hit, out ApplyState __state)
			{
				__state = default(ApplyState);
				try
				{
					Plugin instance = Plugin.instance;
					Player localPlayer = Player.m_localPlayer;
					if (!((Object)(object)instance == (Object)null) && instance.recording && Object.op_Implicit((Object)(object)localPlayer) && !((Object)(object)__instance != (Object)(object)localPlayer) && ((Character)localPlayer).IsOwner())
					{
						__state.Health = ((Character)localPlayer).GetHealth();
						HitCapture hitCapture = Match(hit);
						__state.Capture = hitCapture ?? instance.StartHit(localPlayer, hit, rpc: false);
						__state.Standalone = hitCapture == null;
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "BeforeHealth");
				}
			}

			[HarmonyPostfix]
			[HarmonyPriority(0)]
			private static void AfterHealth(Character __instance, ApplyState __state)
			{
				try
				{
					HitCapture capture = __state.Capture;
					if (capture != null)
					{
						if (!capture.Applied)
						{
							capture.HpBefore = __state.Health;
						}
						capture.Applied = true;
						float health = __instance.GetHealth();
						capture.HpAfter = health;
						capture.HpLoss += Mathf.Max(0f, __state.Health - health);
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "AfterHealth");
				}
			}

			[HarmonyFinalizer]
			private static void FinishDirectDamage(ApplyState __state)
			{
				try
				{
					HitCapture capture = __state.Capture;
					if (capture != null && __state.Standalone)
					{
						incoming = capture.Parent;
						instance?.CompleteHit(capture);
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "FinishDirectDamage");
				}
			}
		}

		private sealed class JsonLines
		{
			private readonly StringBuilder text = new StringBuilder(4096);

			private int complete;

			public int Length => complete;

			public void Begin()
			{
				text.Length = complete;
				text.Append('{');
			}

			public void Finish()
			{
				text.Append("}\n");
				complete = text.Length;
			}

			public string Drain()
			{
				string result = text.ToString(0, complete);
				Clear();
				return result;
			}

			public void Clear()
			{
				text.Clear();
				complete = 0;
			}

			public void Object(string key)
			{
				Name(key);
				text.Append('{');
			}

			public void Object()
			{
				Delimit();
				text.Append('{');
			}

			public void EndObject()
			{
				text.Append('}');
			}

			public void Array(string key)
			{
				Name(key);
				text.Append('[');
			}

			public void EndArray()
			{
				text.Append(']');
			}

			public void S(string key, string value)
			{
				Name(key);
				Quote(value);
			}

			public void S(string value)
			{
				Delimit();
				Quote(value);
			}

			public void N(string key, double? value)
			{
				Name(key);
				Number(value);
			}

			public void N(double value)
			{
				Delimit();
				Number(value);
			}

			public void I(string key, int? value)
			{
				Name(key);
				text.Append(value?.ToString(Invariant) ?? "null");
			}

			public void B(string key, bool? value)
			{
				Name(key);
				text.Append((!value.HasValue) ? "null" : (value.Value ? "true" : "false"));
			}

			public void Null(string key)
			{
				Name(key);
				text.Append("null");
			}

			public void Strings(string key, string[] values)
			{
				if (values == null)
				{
					Null(key);
					return;
				}
				Array(key);
				foreach (string value in values)
				{
					S(value);
				}
				EndArray();
			}

			private void Delimit()
			{
				char c = text[text.Length - 1];
				if (c != '{' && c != '[')
				{
					text.Append(',');
				}
			}

			private void Name(string name)
			{
				Delimit();
				text.Append('"').Append(name).Append("\":");
			}

			private void Number(double? value)
			{
				text.Append((value.HasValue && !double.IsNaN(value.Value) && !double.IsInfinity(value.Value)) ? value.Value.ToString("0.0", Invariant) : "null");
			}

			private void Quote(string value)
			{
				if (value == null)
				{
					text.Append("null");
					return;
				}
				text.Append('"');
				foreach (char c in value)
				{
					if (c != '"')
					{
						if (c == '\\')
						{
							text.Append("\\\\");
						}
						else if (c < ' ' || char.IsSurrogate(c))
						{
							text.Append("\\u").Append("0123456789abcdef"[(int)c >> 12]).Append("0123456789abcdef"[((int)c >> 8) & 0xF])
								.Append("0123456789abcdef"[((int)c >> 4) & 0xF])
								.Append("0123456789abcdef"[c & 0xF]);
						}
						else
						{
							text.Append(c);
						}
					}
					else
					{
						text.Append("\\\"");
					}
				}
				text.Append('"');
			}
		}

		[HarmonyPatch(typeof(Player), "OnSpawned")]
		private static class SpawnHook
		{
			[HarmonyPostfix]
			[HarmonyPriority(0)]
			private static void AfterSpawn(Player __instance)
			{
				try
				{
					Plugin instance = Plugin.instance;
					if (!((Object)(object)instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
					{
						if (instance.recording)
						{
							instance.snapshotPending = true;
						}
						else
						{
							instance.PreparePlayer(__instance, Time.realtimeSinceStartupAsDouble);
						}
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "AfterSpawn");
				}
			}
		}

		[HarmonyPatch(typeof(Game), "Shutdown")]
		private static class GameShutdownHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void BeforeGameShutdown()
			{
				try
				{
					instance?.StopSession();
				}
				catch (Exception error)
				{
					PatchWarning(error, "BeforeGameShutdown");
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "StopAll")]
		private static class NetStopHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void BeforeNetworkStop()
			{
				try
				{
					instance?.StopSession();
				}
				catch (Exception error)
				{
					PatchWarning(error, "BeforeNetworkStop");
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "EquipItem")]
		private static class EquipHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void BeforeEquip(Humanoid __instance, out Plugin __state)
			{
				__state = null;
				try
				{
					__state = EnterEquipment(__instance);
				}
				catch (Exception error)
				{
					PatchWarning(error, "BeforeEquip");
				}
			}

			[HarmonyPostfix]
			[HarmonyPriority(0)]
			private static void AfterEquip(Humanoid __instance, ItemData item, bool __result, Plugin __state)
			{
				try
				{
					if ((Object)(object)__state != (Object)null && __result && item != null && __instance.IsItemEquiped(item))
					{
						__state.equipmentChanged = true;
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "AfterEquip");
				}
			}

			[HarmonyFinalizer]
			[HarmonyPriority(0)]
			[HarmonyAfter(new string[] { "treextr.pathofvalheiman" })]
			private static void FinishEquip(Humanoid __instance, Plugin __state)
			{
				try
				{
					__state?.LeaveEquipment(__instance);
				}
				catch (Exception error)
				{
					PatchWarning(error, "FinishEquip");
				}
			}
		}

		private struct UnequipState
		{
			public Plugin Log;

			public bool Equipped;
		}

		[HarmonyPatch(typeof(Humanoid), "UnequipItem")]
		private static class UnequipHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void BeforeUnequip(Humanoid __instance, ItemData item, out UnequipState __state)
			{
				__state = default(UnequipState);
				try
				{
					if (item != null)
					{
						__state.Log = EnterEquipment(__instance);
						if ((Object)(object)__state.Log != (Object)null)
						{
							__state.Equipped = __instance.IsItemEquiped(item);
						}
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "BeforeUnequip");
				}
			}

			[HarmonyFinalizer]
			[HarmonyPriority(0)]
			[HarmonyAfter(new string[] { "treextr.pathofvalheiman" })]
			private static void FinishUnequip(Humanoid __instance, ItemData item, UnequipState __state)
			{
				Plugin log = __state.Log;
				if ((Object)(object)log == (Object)null)
				{
					return;
				}
				try
				{
					try
					{
						if (__state.Equipped && !__instance.IsItemEquiped(item))
						{
							log.equipmentChanged = true;
						}
					}
					finally
					{
						log.LeaveEquipment(__instance);
					}
				}
				catch (Exception error)
				{
					PatchWarning(error, "FinishUnequip");
				}
			}
		}

		private enum Remote
		{
			Pending,
			Missing,
			Disabled,
			Enabled
		}

		private sealed class PeerLabel
		{
			public long Id;

			public string Label;
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static class DisconnectHook
		{
			[HarmonyPostfix]
			private static void AfterPeerDisconnect(ZNetPeer peer)
			{
				try
				{
					instance?.receivers.Remove(peer);
				}
				catch (Exception error)
				{
					PatchWarning(error, "AfterPeerDisconnect");
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		private static class NetStartHook
		{
			[HarmonyPostfix]
			private static void AfterNetworkStart(ZNet __instance)
			{
				try
				{
					instance?.Connect(__instance);
				}
				catch (Exception error)
				{
					PatchWarning(error, "AfterNetworkStart");
				}
			}
		}

		private const double FightGap = 10.0;

		private const double TargetInterval = 0.5;

		private readonly Dictionary<ZDOID, Target> targets = new Dictionary<ZDOID, Target>();

		private readonly List<ZDOID> endedTargets = new List<ZDOID>();

		private readonly List<ZDOID> lostTargets = new List<ZDOID>();

		private readonly Queue<RecentHit> recent = new Queue<RecentHit>();

		private Fight fight;

		private double nextTargetPoll;

		private static readonly string[] Outcomes = new string[5] { "evaded", "blocked", "parried", "glancing", "hit" };

		[ThreadStatic]
		private static HitCapture incoming;

		private const double AilmentMemory = 30.0;

		private static readonly int BurningHash = SEMan.s_statusEffectBurning;

		private static readonly int PoisonHash = SEMan.s_statusEffectPoison;

		private readonly Dictionary<int, (Actor Actor, double Time)> ailmentSources = new Dictionary<int, (Actor, double)>();

		[ThreadStatic]
		private static RpcFrame rpcFrame;

		public const string Guid = "groshyr.povbalancelog";

		public const string Name = "PoVBalanceLog";

		public const string Version = "1.1.0";

		private const string PovGuid = "treextr.pathofvalheiman";

		private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;

		private static readonly UTF8Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);

		private static Plugin instance;

		private readonly HashSet<string> warnings = new HashSet<string>();

		private readonly JsonLines json = new JsonLines();

		private ConfigEntry<bool> collect;

		private ConfigEntry<int> retentionDays;

		private ConfigEntry<int> maxFileMb;

		private Harmony harmony;

		private string povVersion;

		private string label;

		private string worldHash;

		private bool recording;

		private bool snapshotPending;

		private bool unavailableLogged;

		private bool shuttingDown;

		private double nextSnapshot;

		private double nextFlush;

		private const double SnapshotInterval = 600.0;

		private int equipmentDepth;

		private bool equipmentChanged;

		private const string HelloRpc = "PoVBalanceLog_Hello";

		private const string ReadyRpc = "PoVBalanceLog_Ready";

		private const string BatchRpc = "PoVBalanceLog_Batch";

		private const double FlushInterval = 5.0;

		private const int FlushChars = 32768;

		private const int MaxWireBytes = 1048576;

		private const string DateFormat = "yyyy-MM-dd";

		private readonly Dictionary<ZNetPeer, PeerLabel> receivers = new Dictionary<ZNetPeer, PeerLabel>();

		private readonly HashSet<string> capped = new HashSet<string>();

		private ZRoutedRpc routed;

		private Remote remote;

		private bool remoteDedicated;

		private bool publishedCollect;

		private bool reportedWrite;

		private double helloDeadline;

		private DateTime previousFileDate;

		private static string LogRoot => Path.Combine(Paths.BepInExRootPath, "PoVBalanceLog");

		private Actor Describe(Character character, bool hasAttacker = true)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)character))
			{
				return new Actor
				{
					IsPlayer = (hasAttacker ? ((bool?)null) : new bool?(false))
				};
			}
			Actor result = new Actor
			{
				Prefab = Utils.GetPrefabName(((Component)character).gameObject),
				Boss = character.IsBoss(),
				Stars = character.GetLevel() - 1,
				Biome = GetBiome(((Component)character).transform.position),
				IsPlayer = character.IsPlayer()
			};
			result.Level = ReadPoV<Character, int>("creature combat level", character, CombatLevel);
			if (result.Level <= 0)
			{
				result.Level = null;
			}
			try
			{
				result.Mods = ModifierNames(character);
			}
			catch (Exception error)
			{
				Warn("creature modifiers", error);
			}
			return result;
		}

		private static int CombatLevel(Character character)
		{
			return CreatureLevels.Combat(character);
		}

		private static string[] ModifierNames(Character character)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			Mod val = RarityMods.On(character);
			if ((int)val == 0)
			{
				return Array.Empty<string>();
			}
			List<string> list = new List<string>();
			foreach (Mod item in RarityMods.Each(val))
			{
				list.Add(((object)item/*cast due to .constrained prefix*/).ToString());
			}
			return list.ToArray();
		}

		private unsafe static string GetBiome(Vector3 pos)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			WorldGenerator obj = WorldGenerator.instance;
			Biome val = (Biome)((obj != null) ? ((int)obj.GetBiome(pos)) : 0);
			if ((int)val != 0)
			{
				return ((object)(*(Biome*)(&val))/*cast due to .constrained prefix*/).ToString();
			}
			return null;
		}

		private unsafe static string GetBiome(Player player)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			Biome currentBiome = player.GetCurrentBiome();
			if ((int)currentBiome != 0)
			{
				return ((object)(*(Biome*)(&currentBiome))/*cast due to .constrained prefix*/).ToString();
			}
			return GetBiome(((Component)player).transform.position);
		}

		private void WriteActor(Actor actor)
		{
			json.S("prefab", actor.Prefab);
			json.B("boss", actor.Boss);
			json.I("stars", actor.Stars);
			json.I("plev", actor.Level);
			json.S("biome", actor.Biome);
			json.Strings("mods", actor.Mods);
		}

		private void TouchFight(Player player, double now, double stamp, float hp, float max)
		{
			if (fight != null && now - fight.Last >= 10.0)
			{
				PollTargets(now, force: true);
				CloseFight(fight.Last, fight.LastStamp, died: false);
			}
			if (fight == null)
			{
				fight = new Fight
				{
					Start = now,
					StartStamp = stamp,
					Biome = GetBiome(player),
					HpMin = hp,
					HpMax = max
				};
			}
			if (now >= fight.Last)
			{
				fight.Last = now;
				fight.LastStamp = stamp;
			}
			fight.HpMin = Math.Min(fight.HpMin, hp);
			fight.HpMax = Math.Max(fight.HpMax, max);
		}

		private void AddFightEnemy(ZDOID id, Actor actor)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (!((ZDOID)(ref id)).IsNone() && actor.IsPlayer == false && !fight.Enemies.ContainsKey(id))
			{
				fight.Enemies.Add(id, new FightEnemy
				{
					Actor = actor
				});
			}
		}

		private void TrimRecent(double now)
		{
			while (recent.Count > 0 && now - recent.Peek().Time > 10.0)
			{
				recent.Dequeue();
			}
		}

		private void NoteIncoming(HitCapture hit, Outcome outcome)
		{
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (Object.op_Implicit((Object)(object)localPlayer))
			{
				double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
				TrimRecent(realtimeSinceStartupAsDouble);
				recent.Enqueue(new RecentHit
				{
					Time = realtimeSinceStartupAsDouble,
					Attacker = hit.Attacker,
					Outcome = outcome,
					HitType = hit.HitType,
					Dot = hit.Dot,
					Total = hit.Total,
					HpLoss = hit.HpLoss,
					Absorbed = hit.ShieldAbsorbed
				});
				TouchFight(localPlayer, hit.Time, hit.Stamp, hit.HpAfter ?? ((Character)localPlayer).GetHealth(), hit.HpMax ?? ((Character)localPlayer).GetMaxHealth());
				if (hit.HpBefore.HasValue)
				{
					fight.HpMin = Math.Min(fight.HpMin, hit.HpBefore.Value);
				}
				fight.Taken += hit.HpLoss;
				fight.Absorbed += hit.ShieldAbsorbed.GetValueOrDefault();
				fight.Counts[(int)outcome]++;
				fight.HitsIn++;
				AddFightEnemy(hit.AttackerId, hit.Attacker);
			}
		}

		private void NoteOutgoing(Player player, Character character, HitData hit)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			float totalDamage = hit.GetTotalDamage();
			if (!(totalDamage > 0f) || character.IsDead())
			{
				return;
			}
			ZDOID zDOID = character.GetZDOID();
			if (((ZDOID)(ref zDOID)).IsNone())
			{
				return;
			}
			double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
			TouchFight(player, realtimeSinceStartupAsDouble, Stamp(), ((Character)player).GetHealth(), ((Character)player).GetMaxHealth());
			fight.Dealt += totalDamage;
			if (!character.IsPlayer() && !character.IsTamed())
			{
				if (!targets.TryGetValue(zDOID, out var value))
				{
					value = new Target
					{
						Character = character,
						Actor = Describe(character),
						Start = realtimeSinceStartupAsDouble,
						MaxHealth = character.GetMaxHealth()
					};
					targets.Add(zDOID, value);
				}
				value.Dealt += totalDamage;
				AddFightEnemy(zDOID, value.Actor);
			}
		}

		private void PollTargets(double now, bool force = false)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			if (targets.Count == 0 || (!force && now < nextTargetPoll))
			{
				return;
			}
			nextTargetPoll = now + 0.5;
			try
			{
				foreach (KeyValuePair<ZDOID, Target> target2 in targets)
				{
					Target value = target2.Value;
					ZDOMan obj = ZDOMan.instance;
					ZDO val = ((obj != null) ? obj.GetZDO(target2.Key) : null);
					if (!value.Others)
					{
						value.Others = ((val != null) ? val.GetInt(ZDOVars.s_attackers, 0) : 0) > 1;
					}
					if (Object.op_Implicit((Object)(object)value.Character) && value.Character.IsDead())
					{
						endedTargets.Add(target2.Key);
					}
					else if (!Object.op_Implicit((Object)(object)value.Character))
					{
						((val == null) ? endedTargets : lostTargets).Add(target2.Key);
					}
				}
				foreach (ZDOID lostTarget in lostTargets)
				{
					targets.Remove(lostTarget);
				}
				foreach (ZDOID endedTarget in endedTargets)
				{
					Target target = targets[endedTarget];
					targets.Remove(endedTarget);
					if (fight != null && fight.Enemies.TryGetValue(endedTarget, out var value2))
					{
						value2.Killed = true;
						fight.Enemies[endedTarget] = value2;
					}
					Begin("kill", Stamp());
					WriteActor(target.Actor);
					json.N("hp_max", target.MaxHealth);
					json.N("ttk", now - target.Start);
					json.N("dealt", target.Dealt);
					json.N("share", (target.MaxHealth > 0f) ? new double?((double)target.Dealt / (double)target.MaxHealth) : ((double?)null));
					json.B("others", target.Others);
					Finish();
				}
			}
			finally
			{
				endedTargets.Clear();
				lostTargets.Clear();
			}
		}

		private void CloseFight(double end, double stamp, bool died)
		{
			Fight fight = this.fight;
			if (fight == null)
			{
				return;
			}
			this.fight = null;
			Begin("fight", stamp);
			json.N("start", fight.StartStamp);
			json.N("end", stamp);
			json.N("dur", end - fight.Start);
			json.N("taken", fight.Taken);
			json.N("absorbed", fight.Absorbed);
			json.N("dealt", fight.Dealt);
			json.Object("hits_in");
			json.I("total", fight.HitsIn);
			for (int i = 0; i < Outcomes.Length; i++)
			{
				json.I(Outcomes[i], fight.Counts[i]);
			}
			json.EndObject();
			json.Array("enemies");
			foreach (FightEnemy value in fight.Enemies.Values)
			{
				json.Object();
				json.S("prefab", value.Actor.Prefab);
				json.I("stars", value.Actor.Stars);
				json.B("boss", value.Actor.Boss);
				json.S("biome", value.Actor.Biome);
				json.B("killed", value.Killed);
				json.EndObject();
			}
			json.EndArray();
			json.N("hp_min", fight.HpMin);
			json.N("hp_max", fight.HpMax);
			json.I("potions", fight.Potions);
			json.B("died", died);
			json.S("biome", fight.Biome);
			Finish();
			Flush();
		}

		private void NoteDeath(Player player)
		{
			double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
			double num = Stamp();
			TrimRecent(realtimeSinceStartupAsDouble);
			float maxHealth = ((Character)player).GetMaxHealth();
			float? num2 = ReadPoV("shield max", ShieldMax);
			float? num3 = ReadPoV<Player, float>("body armor", player, EffectiveArmor);
			string biome = GetBiome(player);
			RecentHit? recentHit = null;
			RecentHit? recentHit2 = null;
			foreach (RecentHit item in recent)
			{
				recentHit2 = item;
				if (item.Attacker.Prefab != null && (!recentHit.HasValue || item.Taken >= recentHit.Value.Taken))
				{
					recentHit = item;
				}
			}
			Actor actor = recentHit?.Attacker ?? default(Actor);
			Begin("death", num);
			json.Object("cause");
			json.S("prefab", actor.Prefab);
			json.I("stars", actor.Stars);
			json.B("boss", actor.Boss);
			json.Strings("mods", actor.Mods);
			json.N("taken", recentHit?.Taken);
			json.S("ht", recentHit?.HitType);
			json.EndObject();
			json.Object("blow");
			json.S("prefab", recentHit2?.Attacker.Prefab);
			json.S("ht", recentHit2?.HitType);
			json.N("taken", recentHit2?.Taken);
			json.EndObject();
			json.Array("last");
			foreach (RecentHit item2 in recent)
			{
				json.Object();
				json.N("dt", Math.Max(0.0, realtimeSinceStartupAsDouble - item2.Time));
				json.S("prefab", item2.Attacker.Prefab);
				json.I("stars", item2.Attacker.Stars);
				json.S("ht", item2.HitType);
				json.B("dot", item2.Dot);
				json.S("out", Outcomes[(int)item2.Outcome]);
				json.N("raw_total", item2.Total);
				json.N("hp_loss", item2.HpLoss);
				json.N("shield_absorbed", item2.Absorbed);
				json.EndObject();
			}
			json.EndArray();
			json.N("hp_max", maxHealth);
			json.N("shield_max", num2);
			json.N("armor", num3);
			json.S("biome", biome);
			Finish();
			recent.Clear();
			PollTargets(realtimeSinceStartupAsDouble, force: true);
			if (fight != null)
			{
				if (realtimeSinceStartupAsDouble - fight.Last < 10.0)
				{
					fight.HpMin = Math.Min(fight.HpMin, ((Character)player).GetHealth());
					CloseFight(realtimeSinceStartupAsDouble, num, died: true);
				}
				else
				{
					CloseFight(fight.Last, fight.LastStamp, died: false);
				}
			}
			Flush();
		}

		private static float Physical(HitData hit)
		{
			return hit.m_damage.m_blunt + hit.m_damage.m_slash + hit.m_damage.m_pierce;
		}

		private static string HitKind(HitData hit)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected I4, but got Unknown
			HitType hitType = hit.m_hitType;
			if (hitType - 1 > 1)
			{
				switch (hitType - 16)
				{
				case 4:
				case 5:
				case 6:
					return "aoe";
				case 0:
				case 2:
				case 3:
					return "projectile";
				default:
					if (!hit.m_ranged)
					{
						return "other";
					}
					return "projectile";
				}
			}
			if (!hit.m_ranged)
			{
				return "melee";
			}
			return "projectile";
		}

		private Actor ResolveAttacker(HitData hit, bool hasAttacker, Character attacker, out bool dot)
		{
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Invalid comparison between Unknown and I4
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Invalid comparison between Unknown and I4
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			dot = false;
			if (Object.op_Implicit((Object)(object)attacker))
			{
				return Describe(attacker);
			}
			if (hasAttacker)
			{
				Actor result = new Actor
				{
					IsPlayer = null
				};
				try
				{
					ZDOMan obj = ZDOMan.instance;
					ZDO val = ((obj != null) ? obj.GetZDO(hit.m_attacker) : null);
					object obj2;
					if (val == null)
					{
						obj2 = null;
					}
					else
					{
						ZNetScene obj3 = ZNetScene.instance;
						obj2 = ((obj3 != null) ? obj3.GetPrefab(val.GetPrefab()) : null);
					}
					GameObject val2 = (GameObject)obj2;
					if (Object.op_Implicit((Object)(object)val2))
					{
						result.Prefab = ((Object)val2).name;
						result.IsPlayer = ((Object)val2).name == "Player";
					}
				}
				catch (Exception error)
				{
					Warn("attacker prefab", error);
				}
				return result;
			}
			int num = (((int)hit.m_hitType == 5) ? BurningHash : (((int)hit.m_hitType == 7) ? PoisonHash : 0));
			if (num != 0 && ailmentSources.TryGetValue(num, out (Actor, double) value) && Time.realtimeSinceStartupAsDouble - value.Item2 <= 30.0)
			{
				dot = true;
				return value.Item1;
			}
			return new Actor
			{
				IsPlayer = false
			};
		}

		private HitCapture StartHit(Player player, HitData hit, bool rpc)
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			if (hit == null)
			{
				return null;
			}
			float totalDamage = hit.GetTotalDamage();
			bool flag = hit.HaveAttacker();
			if (!flag && totalDamage == 0f)
			{
				return null;
			}
			Character val = (flag ? hit.GetAttacker() : null);
			float health = ((Character)player).GetHealth();
			bool dot;
			HitCapture hitCapture = new HitCapture
			{
				Parent = incoming,
				Data = hit,
				Time = Time.realtimeSinceStartupAsDouble,
				Stamp = Stamp(),
				Attacker = ResolveAttacker(hit, flag, val, out dot),
				Dot = dot,
				AttackerId = (Object.op_Implicit((Object)(object)val) ? val.GetZDOID() : ZDOID.None),
				Kind = HitKind(hit),
				HitType = ((object)Unsafe.As<HitType, HitType>(ref hit.m_hitType)/*cast due to .constrained prefix*/).ToString(),
				Pos = ((Component)player).transform.position,
				HpBefore = health,
				HpAfter = health,
				HpMax = ((Character)player).GetMaxHealth(),
				ShieldBefore = ReadPoV("shield current", ShieldCurrent),
				ShieldMax = ReadPoV("shield max", ShieldMax),
				ShieldAbsorbed = 0f,
				Dodge = (rpc && hit.m_dodgeable && !((Character)player).IsDead() && health > 0f && ((Character)player).IsDodgeInvincible())
			};
			ReadAmounts(hitCapture, hit);
			if (rpc && Object.op_Implicit((Object)(object)val) && (hit.m_statusEffectHash == BurningHash || hit.m_statusEffectHash == PoisonHash))
			{
				ailmentSources[hit.m_statusEffectHash] = (hitCapture.Attacker, hitCapture.Time);
			}
			incoming = hitCapture;
			return hitCapture;
		}

		private static void ReadAmounts(HitCapture sample, HitData hit)
		{
			sample.Total = hit.GetTotalDamage();
			sample.Phys = Physical(hit);
			sample.Elem = hit.m_damage.m_fire + hit.m_damage.m_frost + hit.m_damage.m_lightning;
			sample.Spirit = hit.m_damage.m_spirit;
			sample.Poison = hit.m_damage.m_poison;
		}

		private static HitCapture Match(HitData hit)
		{
			if (incoming?.Data != hit)
			{
				return null;
			}
			return incoming;
		}

		private void CompleteHit(HitCapture hit)
		{
			if (recording)
			{
				Outcome outcome = ((!hit.Dodge && ReadPoV<HitData, bool>("evasion marker", hit.Data, WasEvaded) != true) ? (hit.Parried ? Outcome.Parried : (hit.Blocked ? Outcome.Blocked : (hit.Glancing ? Outcome.Glancing : Outcome.Hit))) : Outcome.Evaded);
				Begin("hit", hit.Stamp);
				json.Object("atk");
				WriteActor(hit.Attacker);
				json.B("player", hit.Attacker.IsPlayer);
				json.EndObject();
				json.S("kind", hit.Kind);
				json.S("ht", hit.HitType);
				json.B("dot", hit.Dot);
				json.S("out", Outcomes[(int)outcome]);
				json.Object("raw");
				json.N("total", hit.Total);
				json.N("phys", hit.Phys);
				json.N("elem", hit.Elem);
				json.N("spirit", hit.Spirit);
				json.N("poison", hit.Poison);
				json.EndObject();
				json.N("raw_base", hit.BaseTotal);
				json.N("after_block", hit.AfterBlock);
				if (hit.AfterArmor.HasValue)
				{
					json.Object("after_armor");
					json.N("total", hit.AfterArmor);
					json.N("phys", hit.AfterArmorPhys);
					json.EndObject();
				}
				else
				{
					json.Null("after_armor");
				}
				json.N("pen", hit.Pen);
				json.N("armor", hit.Armor);
				json.N("shield_absorbed", hit.ShieldAbsorbed);
				json.N("hp_loss", hit.HpLoss);
				json.N("hp_before", hit.HpBefore);
				json.N("hp_after", hit.HpAfter);
				json.N("hp_max", hit.HpMax);
				json.N("shield_before", hit.ShieldBefore);
				json.N("shield_max", hit.ShieldMax);
				json.Array("pos");
				json.N(hit.Pos.x);
				json.N(hit.Pos.y);
				json.N(hit.Pos.z);
				json.EndArray();
				Finish();
				NoteIncoming(hit, outcome);
			}
		}

		private static HitCapture FrameCapture(Character target, HitData hit)
		{
			if (hit != null && (Object)(object)target == (Object)(object)Player.m_localPlayer)
			{
				HitCapture hitCapture = rpcFrame?.Capture;
				if (hitCapture != null && hitCapture.Data != hit)
				{
					return hitCapture;
				}
			}
			return null;
		}

		private void Awake()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Expected O, but got Unknown
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Expected O, but got Unknown
			instance = this;
			collect = ((BaseUnityPlugin)this).Config.Bind<bool>("Telemetry", "Collect", true, new ConfigDescription("Collect combat telemetry. In multiplayer the server controls this setting.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			retentionDays = ((BaseUnityPlugin)this).Config.Bind<int>("Telemetry", "Retention days", 30, new ConfigDescription("Server only. Keep this many calendar days of telemetry, including today.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 36500), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			maxFileMb = ((BaseUnityPlugin)this).Config.Bind<int>("Telemetry", "Max file MB", 20, new ConfigDescription("Server only. Maximum size in MiB per player label per day.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1024), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			if (Chainloader.PluginInfos.TryGetValue("treextr.pathofvalheiman", out var value))
			{
				povVersion = value.Metadata.Version.ToString();
			}
			harmony = new Harmony("groshyr.povbalancelog");
			Type[] nestedTypes = ((object)this).GetType().GetNestedTypes(BindingFlags.NonPublic);
			foreach (Type type in nestedTypes)
			{
				if (Attribute.IsDefined(type, typeof(HarmonyPatch)))
				{
					try
					{
						harmony.CreateClassProcessor(type).Patch();
					}
					catch (Exception error)
					{
						Warn("install " + type.Name, error);
					}
				}
			}
		}

		private void OnDestroy()
		{
			try
			{
				StopSession();
			}
			catch (Exception error)
			{
				Warn("plugin shutdown", error);
			}
			harmony.UnpatchSelf();
			instance = null;
		}

		private void Update()
		{
			try
			{
				if (shuttingDown || routed == null)
				{
					return;
				}
				ZNet val = ZNet.instance;
				if (!Object.op_Implicit((Object)(object)val))
				{
					return;
				}
				double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
				if (val.IsServer())
				{
					PublishCollect(val);
				}
				else
				{
					CheckRemote(val, realtimeSinceStartupAsDouble);
				}
				Player localPlayer = Player.m_localPlayer;
				if (!recording && Object.op_Implicit((Object)(object)localPlayer) && !((Character)localPlayer).IsDead())
				{
					PreparePlayer(localPlayer, realtimeSinceStartupAsDouble);
				}
				if (!recording)
				{
					return;
				}
				if (!Allowed(val))
				{
					DiscardRecording();
					return;
				}
				PollTargets(realtimeSinceStartupAsDouble);
				if (fight != null && realtimeSinceStartupAsDouble - fight.Last >= 10.0)
				{
					CloseFight(fight.Last, fight.LastStamp, died: false);
				}
				if (Object.op_Implicit((Object)(object)localPlayer) && !((Character)localPlayer).IsDead() && (snapshotPending || realtimeSinceStartupAsDouble >= nextSnapshot))
				{
					snapshotPending = false;
					if (realtimeSinceStartupAsDouble >= nextSnapshot)
					{
						nextSnapshot = realtimeSinceStartupAsDouble + 600.0;
					}
					Snapshot(localPlayer);
				}
				if (realtimeSinceStartupAsDouble >= nextFlush)
				{
					Flush();
				}
			}
			catch (Exception error)
			{
				Warn("update", error);
			}
		}

		private void PreparePlayer(Player player, double now)
		{
			if (shuttingDown || routed == null || !Object.op_Implicit((Object)(object)ZNet.instance) || ((Character)player).IsDead())
			{
				return;
			}
			if (label == null)
			{
				long playerID = player.GetPlayerID();
				if (playerID == 0L)
				{
					return;
				}
				label = PlayerLabel(playerID);
				string worldName = ZNet.instance.GetWorldName();
				worldHash = (string.IsNullOrEmpty(worldName) ? null : HashTag("PoVBalanceLog:world:" + worldName));
				((BaseUnityPlugin)this).Logger.LogInfo((object)("PoVBalanceLog: your label is " + label));
			}
			if (!recording && Allowed(ZNet.instance))
			{
				recording = true;
				nextFlush = now + 5.0;
				WriteSession("start");
				nextSnapshot = now + 600.0;
				Snapshot(player);
			}
		}

		private bool Allowed(ZNet net)
		{
			if (!net.IsServer() && remote == Remote.Pending)
			{
				return false;
			}
			if (collect.Value && (net.IsServer() || remote == Remote.Enabled))
			{
				return true;
			}
			if (!unavailableLogged)
			{
				unavailableLogged = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)((remote == Remote.Missing) ? "PoVBalanceLog: server has no telemetry receiver; collection disabled." : "PoVBalanceLog: collection disabled (Collect=false)."));
			}
			return false;
		}

		private void StopSession()
		{
			if (shuttingDown)
			{
				return;
			}
			shuttingDown = true;
			try
			{
				if (recording && Object.op_Implicit((Object)(object)ZNet.instance) && Allowed(ZNet.instance))
				{
					double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
					PollTargets(realtimeSinceStartupAsDouble, force: true);
					if (fight != null)
					{
						CloseFight(realtimeSinceStartupAsDouble, Stamp(), died: false);
					}
					WriteSession("stop");
					Flush();
				}
			}
			finally
			{
				DiscardRecording();
			}
		}

		private void DiscardRecording()
		{
			recording = (snapshotPending = false);
			json.Clear();
			fight = null;
			recent.Clear();
			targets.Clear();
			endedTargets.Clear();
			lostTargets.Clear();
			nextTargetPoll = 0.0;
		}

		private void WriteSession(string action)
		{
			Begin("session", Stamp());
			json.S("event", action);
			json.S("world", worldHash);
			json.B("server", remoteDedicated);
			Finish();
		}

		private void Begin(string type, double ts)
		{
			json.Begin();
			json.I("v", 1);
			json.S("t", type);
			json.N("ts", ts);
			json.S("p", label);
			json.S("mod", "1.1.0");
			json.S("pov", povVersion);
		}

		private void Finish()
		{
			json.Finish();
			if (json.Length >= 32768)
			{
				Flush();
			}
		}

		private static double Stamp()
		{
			return (double)(DateTime.UtcNow.Ticks - 621355968000000000L) / 10000000.0;
		}

		private static string PlayerLabel(long id)
		{
			return "p-" + HashTag("PoVBalanceLog:" + id.ToString(Invariant));
		}

		private static string HashTag(string text)
		{
			using SHA256 sHA = SHA256.Create();
			byte[] array = sHA.ComputeHash(Utf8.GetBytes(text));
			char[] array2 = new char[8];
			for (int i = 0; i < 4; i++)
			{
				array2[i * 2] = "0123456789abcdef"[array[i] >> 4];
				array2[i * 2 + 1] = "0123456789abcdef"[array[i] & 0xF];
			}
			return new string(array2);
		}

		private void Warn(string site, Exception error)
		{
			if (warnings.Add(site))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("PoVBalanceLog: " + site + ": " + error.GetType().Name + ": " + error.Message));
			}
		}

		private static void PatchWarning(Exception error, [CallerMemberName] string site = null)
		{
			instance?.Warn(site, error);
		}

		private T? ReadPoV<T>(string site, Func<T> read) where T : struct
		{
			try
			{
				return read();
			}
			catch (Exception error)
			{
				Warn(site, error);
				return null;
			}
		}

		private T? ReadPoV<TArg, T>(string site, TArg arg, Func<TArg, T> read) where T : struct
		{
			try
			{
				return read(arg);
			}
			catch (Exception error)
			{
				Warn(site, error);
				return null;
			}
		}

		private static float ShieldCurrent()
		{
			return EnergyShield.Current;
		}

		private static float ShieldMax()
		{
			return EnergyShield.Max;
		}

		private static bool WasEvaded(HitData hit)
		{
			return Evasion.WasEvaded(hit);
		}

		private static float EvasionRating(Player player)
		{
			return Evasion.Rating(player, Progress.Current?.Stats);
		}

		private static int Level()
		{
			return Progress.Current?.Level ?? 0;
		}

		private static float EffectiveArmor(Player player)
		{
			return ((Character)player).GetBodyArmor() * ArmorEffect.Factor(Progress.Current?.Stats);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static float WithoutFood(Player player)
		{
			float baseFoodHP = player.GetBaseFoodHP();
			StatSet val = Progress.Current?.Stats;
			if (val == null)
			{
				return baseFoodHP;
			}
			if (val.Has((Stat)577))
			{
				return 1f;
			}
			return (baseFoodHP + val.Get((Stat)0)) * (1f + val.Get((Stat)1)) * val.MulOf((Stat)1) * (1f - Mathf.Clamp(val.Get((Stat)575), 0f, 0.9f));
		}

		private static string ItemPrefab(ItemData item)
		{
			if (!Object.op_Implicit((Object)(object)item?.m_dropPrefab))
			{
				return null;
			}
			return Utils.GetPrefabName(item.m_dropPrefab);
		}

		private void Snapshot(Player player)
		{
			int? num = ReadPoV("player level", Level);
			float maxHealth = ((Character)player).GetMaxHealth();
			List<Food> foods = player.GetFoods();
			float? num2 = ((foods.Count == 0) ? new float?(maxHealth) : ReadPoV<Player, float>("health without food", player, WithoutFood));
			float? num3 = ReadPoV<Player, float>("body armor", player, EffectiveArmor);
			float? num4 = ReadPoV<Player, float>("evasion rating", player, EvasionRating);
			float? num5 = ReadPoV("shield max", ShieldMax);
			float maxStamina = ((Character)player).GetMaxStamina();
			float maxEitr = ((Character)player).GetMaxEitr();
			List<ItemData> equippedItems = ((Humanoid)player).GetInventory().GetEquippedItems();
			string biome = GetBiome(player);
			Begin("snap", Stamp());
			json.I("lvl", (num > 0) ? num : ((int?)null));
			json.N("hp_max", maxHealth);
			json.N("hp_base", num2);
			json.N("armor", num3);
			json.N("evasion", num4);
			json.N("shield_max", num5);
			json.N("stamina_max", maxStamina);
			json.N("eitr_max", maxEitr);
			json.Array("gear");
			foreach (ItemData item in equippedItems)
			{
				string text = ItemPrefab(item);
				json.S((text == null) ? null : (text + ":" + item.m_quality.ToString(Invariant)));
			}
			json.EndArray();
			json.Array("food");
			foreach (Food item2 in foods)
			{
				json.S(ItemPrefab(item2.m_item));
			}
			json.EndArray();
			json.S("biome", biome);
			Finish();
		}

		private static Plugin EnterEquipment(Humanoid character)
		{
			Plugin plugin = instance;
			if ((Object)(object)plugin == (Object)null || !plugin.recording || (Object)(object)character != (Object)(object)Player.m_localPlayer || ((Character)character).IsDead())
			{
				return null;
			}
			plugin.equipmentDepth++;
			return plugin;
		}

		private void LeaveEquipment(Humanoid character)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			if (--equipmentDepth == 0 && equipmentChanged)
			{
				equipmentChanged = false;
				if (recording && (Object)(object)character == (Object)(object)Player.m_localPlayer && !((Character)character).IsDead())
				{
					Snapshot((Player)character);
				}
			}
		}

		private void Connect(ZNet net)
		{
			if (routed == ZRoutedRpc.instance)
			{
				return;
			}
			StopSession();
			routed = ZRoutedRpc.instance;
			if (routed != null)
			{
				label = (worldHash = null);
				unavailableLogged = (remoteDedicated = (shuttingDown = (reportedWrite = false)));
				helloDeadline = 0.0;
				remote = Remote.Pending;
				receivers.Clear();
				publishedCollect = collect.Value;
				routed.Register("PoVBalanceLog_Hello", (Action<long>)OnHello);
				routed.Register<bool, bool>("PoVBalanceLog_Ready", (Action<long, bool, bool>)OnReady);
				routed.Register<ZPackage>("PoVBalanceLog_Batch", (Action<long, ZPackage>)OnBatch);
				if (net.IsServer())
				{
					Prune();
					((BaseUnityPlugin)this).Logger.LogInfo((object)("PoVBalanceLog: server receiver ready; Collect=" + collect.Value + "."));
				}
			}
		}

		private void CheckRemote(ZNet net, double now)
		{
			if (remote != Remote.Pending)
			{
				return;
			}
			if (helloDeadline == 0.0)
			{
				ZNetPeer serverPeer = net.GetServerPeer();
				if (serverPeer != null && serverPeer.IsReady())
				{
					helloDeadline = now + 5.0;
					routed.InvokeRoutedRPC(serverPeer.m_uid, "PoVBalanceLog_Hello", Array.Empty<object>());
				}
			}
			else if (now >= helloDeadline)
			{
				remote = Remote.Missing;
			}
		}

		private void OnHello(long sender)
		{
			try
			{
				ZNet val = ZNet.instance;
				if (!Object.op_Implicit((Object)(object)val) || !val.IsServer())
				{
					return;
				}
				ZNetPeer peer = val.GetPeer(sender);
				if (peer != null && peer.IsReady())
				{
					if (!receivers.ContainsKey(peer))
					{
						receivers.Add(peer, new PeerLabel());
					}
					Reply(val, peer);
				}
			}
			catch (Exception error)
			{
				Warn("RPC hello", error);
			}
		}

		private void Reply(ZNet net, ZNetPeer peer)
		{
			routed.InvokeRoutedRPC(peer.m_uid, "PoVBalanceLog_Ready", new object[2]
			{
				collect.Value,
				net.IsDedicated()
			});
		}

		private void PublishCollect(ZNet net)
		{
			if (publishedCollect == collect.Value)
			{
				return;
			}
			publishedCollect = collect.Value;
			foreach (ZNetPeer key in receivers.Keys)
			{
				if (key.IsReady())
				{
					Reply(net, key);
				}
			}
		}

		private void OnReady(long sender, bool enabled, bool dedicated)
		{
			try
			{
				ZNet val = ZNet.instance;
				if (!Object.op_Implicit((Object)(object)val) || val.IsServer())
				{
					return;
				}
				ZNetPeer serverPeer = val.GetServerPeer();
				if (serverPeer != null && serverPeer.m_uid == sender)
				{
					bool num = remote == Remote.Pending || remote == Remote.Missing;
					remote = (enabled ? Remote.Enabled : Remote.Disabled);
					remoteDedicated = dedicated;
					if (num && enabled)
					{
						((BaseUnityPlugin)this).Logger.LogInfo((object)"PoVBalanceLog: server telemetry receiver confirmed.");
					}
				}
			}
			catch (Exception error)
			{
				Warn("RPC ready", error);
			}
		}

		private void Flush()
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			nextFlush = Time.realtimeSinceStartupAsDouble + 5.0;
			if (json.Length == 0)
			{
				return;
			}
			ZNet val = ZNet.instance;
			if (!Object.op_Implicit((Object)(object)val) || !Allowed(val))
			{
				json.Clear();
				return;
			}
			string text = json.Drain();
			if (val.IsServer())
			{
				Append(label, text);
				return;
			}
			ZNetPeer serverPeer = val.GetServerPeer();
			if (serverPeer != null && serverPeer.IsReady())
			{
				ZPackage val2 = new ZPackage();
				val2.Write(label);
				val2.Write(text);
				if (val2.Size() <= 1048576)
				{
					routed.InvokeRoutedRPC(serverPeer.m_uid, "PoVBalanceLog_Batch", new object[1] { val2 });
				}
				else
				{
					Warn("batch size", new InvalidDataException("A record exceeds the telemetry packet limit."));
				}
			}
		}

		private void OnBatch(long sender, ZPackage batch)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ZNet val = ZNet.instance;
				if (!Object.op_Implicit((Object)(object)val) || !val.IsServer() || !collect.Value || batch == null || batch.Size() > 1048576)
				{
					return;
				}
				ZNetPeer peer = val.GetPeer(sender);
				if (peer == null || !receivers.TryGetValue(peer, out var value))
				{
					return;
				}
				long num = peer.m_playerID;
				if (num == 0L)
				{
					ZDOMan obj = ZDOMan.instance;
					long? obj2;
					if (obj == null)
					{
						obj2 = null;
					}
					else
					{
						ZDO zDO = obj.GetZDO(peer.m_characterID);
						obj2 = ((zDO != null) ? new long?(zDO.GetLong(ZDOVars.s_playerID, 0L)) : ((long?)null));
					}
					long? num2 = obj2;
					num = num2.GetValueOrDefault();
				}
				if (num == 0L)
				{
					return;
				}
				if (value.Id != num)
				{
					value.Label = PlayerLabel(num);
					value.Id = num;
				}
				if (!(batch.ReadString() != value.Label))
				{
					string lines = batch.ReadString();
					if (batch.GetPos() == batch.Size() && HasRecordEnvelope(lines, value.Label))
					{
						Append(value.Label, lines);
					}
				}
			}
			catch (Exception error)
			{
				Warn("RPC batch", error);
			}
		}

		private static bool HasRecordEnvelope(string lines, string playerLabel)
		{
			if (lines.Length == 0 || lines[lines.Length - 1] != '\n' || lines.IndexOf('\r') >= 0)
			{
				return false;
			}
			int num = 0;
			while (num < lines.Length)
			{
				int num2 = lines.IndexOf('\n', num);
				if (num2 - num <= "{\"v\":1,\"t\":\"".Length || lines[num2 - 1] != '}' || string.CompareOrdinal(lines, num, "{\"v\":1,\"t\":\"", 0, "{\"v\":1,\"t\":\"".Length) != 0)
				{
					return false;
				}
				int num3 = lines.IndexOf(",\"p\":\"", num + "{\"v\":1,\"t\":\"".Length, num2 - num - "{\"v\":1,\"t\":\"".Length, StringComparison.Ordinal);
				if (num3 < 0)
				{
					return false;
				}
				num3 += ",\"p\":\"".Length;
				if (num3 + playerLabel.Length >= num2 || lines[num3 + playerLabel.Length] != '"' || string.CompareOrdinal(lines, num3, playerLabel, 0, playerLabel.Length) != 0)
				{
					return false;
				}
				num = num2 + 1;
			}
			return true;
		}

		private void Append(string playerLabel, string lines)
		{
			try
			{
				DateTime today = DateTime.Today;
				if (previousFileDate != today)
				{
					previousFileDate = today;
					capped.Clear();
				}
				if (capped.Contains(playerLabel))
				{
					return;
				}
				string text = Path.Combine(LogRoot, today.ToString("yyyy-MM-dd", Invariant));
				Directory.CreateDirectory(text);
				bool flag = false;
				using (FileStream fileStream = new FileStream(Path.Combine(text, playerLabel + ".jsonl"), FileMode.Append, FileAccess.Write, FileShare.Read))
				{
					long num = (long)maxFileMb.Value * 1024L * 1024 - fileStream.Length;
					byte[] bytes = Utf8.GetBytes(lines);
					int num2 = bytes.Length;
					if (num2 > num)
					{
						num2 = ((num > 0) ? Array.LastIndexOf(bytes, (byte)10, (int)num - 1) : (-1)) + 1;
						if (capped.Add(playerLabel))
						{
							((BaseUnityPlugin)this).Logger.LogWarning((object)("PoVBalanceLog: daily file cap reached for " + playerLabel + " on " + today.ToString("yyyy-MM-dd", Invariant) + "; dropping further records."));
						}
					}
					if (num2 > 0)
					{
						fileStream.Write(bytes, 0, num2);
						flag = true;
					}
				}
				if (flag && !reportedWrite)
				{
					reportedWrite = true;
					((BaseUnityPlugin)this).Logger.LogInfo((object)("PoVBalanceLog: telemetry written under " + text + "."));
				}
			}
			catch (Exception error)
			{
				Warn("file append", error);
			}
		}

		private void Prune()
		{
			try
			{
				DateTime dateTime = DateTime.Today.AddDays(1 - retentionDays.Value);
				if (!Directory.Exists(LogRoot))
				{
					return;
				}
				foreach (string item in Directory.EnumerateDirectories(LogRoot))
				{
					if (DateTime.TryParseExact(Path.GetFileName(item), "yyyy-MM-dd", Invariant, DateTimeStyles.None, out var result) && result < dateTime && (File.GetAttributes(item) & FileAttributes.ReparsePoint) == 0)
					{
						Directory.Delete(item, recursive: true);
					}
				}
			}
			catch (Exception error)
			{
				Warn("retention", error);
			}
		}
	}
}