Decompiled source of DeepNorthCompat v1.6.15

BepInEx/plugins/DeepNorthCompat/DeepNorthCompat.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ConditionalConfigSync;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[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("DeepNorthCompat")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.6.15.0")]
[assembly: AssemblyInformationalVersion("1.6.15")]
[assembly: AssemblyProduct("DeepNorthCompat")]
[assembly: AssemblyTitle("DeepNorthCompat")]
[assembly: InternalsVisibleTo("DeepNorthCompat.Tests")]
[assembly: AssemblyVersion("1.6.15.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 DeepNorthCompat
{
	public static class BowCalculation
	{
		public const float VanillaReduction = 0.33f;

		public static float Reduction(float configured, bool enabled)
		{
			if (enabled && !(configured <= 0f) && !(configured > 1f) && !float.IsNaN(configured))
			{
				return configured;
			}
			return 0.33f;
		}
	}
	public sealed class ResourceStack<TItem, TSource> where TItem : notnull where TSource : notnull
	{
		public readonly TItem Id;

		public readonly TSource Source;

		public readonly string Name;

		public readonly int Quality;

		public readonly int WorldLevel;

		public readonly int Count;

		public readonly bool Container;

		public readonly int Index;

		public ResourceStack(TItem id, TSource source, string name, int quality, int worldLevel, int count, bool container, int index = 0)
		{
			Id = id;
			Source = source;
			Name = name;
			Quality = quality;
			WorldLevel = worldLevel;
			Count = count;
			Container = container;
			Index = index;
		}
	}
	public sealed class ResourceNeed<TSource>
	{
		public readonly string Name;

		public readonly int MaximumQuality;

		public readonly int Count;

		public readonly Func<TSource, bool> AllowsSource;

		public ResourceNeed(string name, int maximumQuality, int count, Func<TSource, bool> allowsSource)
		{
			Name = name;
			MaximumQuality = maximumQuality;
			Count = count;
			AllowsSource = allowsSource;
		}
	}
	public sealed class Allocation<TItem, TSource> where TItem : notnull where TSource : notnull
	{
		public readonly ResourceStack<TItem, TSource> Stack;

		public readonly int Count;

		public Allocation(ResourceStack<TItem, TSource> stack, int count)
		{
			Stack = stack;
			Count = count;
		}
	}
	public sealed class SelectedIngredient<TItem, TSource> where TItem : notnull where TSource : notnull
	{
		public readonly ResourceNeed<TSource> Need;

		public readonly int Tier;

		public readonly IReadOnlyList<Allocation<TItem, TSource>> Allocations;

		public SelectedIngredient(ResourceNeed<TSource> need, int tier, List<Allocation<TItem, TSource>> allocations)
		{
			Need = need;
			Tier = tier;
			Allocations = allocations.AsReadOnly();
		}
	}
	public sealed class IngredientPlan<TItem, TSource> where TItem : notnull where TSource : notnull
	{
		public readonly IReadOnlyList<SelectedIngredient<TItem, TSource>> Ingredients;

		public IEnumerable<Allocation<TItem, TSource>> Allocations => Ingredients.SelectMany((SelectedIngredient<TItem, TSource> i) => i.Allocations);

		public IngredientPlan(List<SelectedIngredient<TItem, TSource>> ingredients)
		{
			Ingredients = ingredients.AsReadOnly();
		}
	}
	public static class IngredientSelector
	{
		public static IngredientPlan<TItem, TSource>? Select<TItem, TSource>(IReadOnlyList<ResourceStack<TItem, TSource>> stacks, IReadOnlyList<ResourceNeed<TSource>> needs, int worldLevel, bool leaveOne) where TItem : notnull where TSource : notnull
		{
			Dictionary<TItem, int> remaining = stacks.ToDictionary((ResourceStack<TItem, TSource> s) => s.Id, (ResourceStack<TItem, TSource> s) => s.Count);
			List<SelectedIngredient<TItem, TSource>> list = new List<SelectedIngredient<TItem, TSource>>();
			foreach (ResourceNeed<TSource> need in needs)
			{
				if (need.Count <= 0)
				{
					continue;
				}
				List<ResourceStack<TItem, TSource>> candidates = stacks.Where((ResourceStack<TItem, TSource> s) => s.Name == need.Name && s.WorldLevel >= worldLevel && need.AllowsSource(s.Source)).ToList();
				if (Capacity(candidates) < need.Count)
				{
					return null;
				}
				int num = 0;
				int quality;
				for (quality = 1; quality <= need.MaximumQuality; quality++)
				{
					if (need.MaximumQuality <= 1)
					{
						break;
					}
					if (Capacity(candidates.Where((ResourceStack<TItem, TSource> s) => s.Quality == quality)) >= need.Count)
					{
						num = quality;
						break;
					}
				}
				int num2 = need.Count;
				List<Allocation<TItem, TSource>> list2 = new List<Allocation<TItem, TSource>>();
				foreach (ResourceStack<TItem, TSource> stack in candidates)
				{
					if (num > 0 && stack.Quality != num)
					{
						continue;
					}
					int val = remaining[stack.Id];
					if (leaveOne && stack.Container)
					{
						int num3 = candidates.Where((ResourceStack<TItem, TSource> s) => object.Equals(s.Source, stack.Source)).Sum((ResourceStack<TItem, TSource> s) => remaining[s.Id]);
						val = Math.Min(val, Math.Max(0, num3 - 1));
					}
					int num4 = Math.Min(val, num2);
					if (num4 > 0)
					{
						list2.Add(new Allocation<TItem, TSource>(stack, num4));
						remaining[stack.Id] -= num4;
						num2 -= num4;
						if (num2 == 0)
						{
							break;
						}
					}
				}
				if (num2 != 0)
				{
					throw new InvalidOperationException("Selection capacity and allocation disagreed.");
				}
				list.Add(new SelectedIngredient<TItem, TSource>(need, num, list2));
				int Capacity(IEnumerable<ResourceStack<TItem, TSource>> subset)
				{
					return (from s in subset
						group s by s.Source).Sum(delegate(IGrouping<TSource, ResourceStack<TItem, TSource>> group)
					{
						int num5 = group.Sum((ResourceStack<TItem, TSource> s) => remaining[s.Id]);
						if (!leaveOne || !group.First().Container)
						{
							return num5;
						}
						int num6 = candidates.Where((ResourceStack<TItem, TSource> s) => object.Equals(s.Source, group.Key)).Sum((ResourceStack<TItem, TSource> s) => remaining[s.Id]);
						return Math.Min(num5, Math.Max(0, num6 - 1));
					});
				}
			}
			return new IngredientPlan<TItem, TSource>(list);
		}
	}
	public enum ReservationState
	{
		Planned,
		Reserved,
		Committed,
		RolledBack
	}
	public sealed class IngredientReservation<TItem, TSource> where TItem : notnull where TSource : notnull
	{
		private readonly IngredientPlan<TItem, TSource> plan;

		private readonly List<Tuple<ResourceStack<TItem, TSource>, int>> before = new List<Tuple<ResourceStack<TItem, TSource>, int>>();

		public ReservationState State { get; private set; }

		public IngredientReservation(IngredientPlan<TItem, TSource> plan)
		{
			this.plan = plan;
		}

		public bool Reserve(Func<ResourceStack<TItem, TSource>, int> currentCount, Func<Allocation<TItem, TSource>, bool> remove, Action<ResourceStack<TItem, TSource>, int> restore)
		{
			if (State != ReservationState.Planned)
			{
				return false;
			}
			foreach (IGrouping<TItem, Allocation<TItem, TSource>> item in from a in plan.Allocations
				group a by a.Stack.Id)
			{
				ResourceStack<TItem, TSource> stack = item.First().Stack;
				int num = currentCount(stack);
				if (num < item.Sum((Allocation<TItem, TSource> a) => a.Count))
				{
					return false;
				}
				before.Add(Tuple.Create(stack, num));
			}
			try
			{
				foreach (Allocation<TItem, TSource> allocation in plan.Allocations)
				{
					if (!remove(allocation))
					{
						Rollback(restore);
						return false;
					}
				}
				State = ReservationState.Reserved;
				return true;
			}
			catch
			{
				Rollback(restore);
				throw;
			}
		}

		public void Complete(bool outputCreated, Action<ResourceStack<TItem, TSource>, int> restore)
		{
			if (State == ReservationState.Reserved)
			{
				if (outputCreated)
				{
					State = ReservationState.Committed;
				}
				else
				{
					Rollback(restore);
				}
			}
		}

		public void Rollback(Action<ResourceStack<TItem, TSource>, int> restore)
		{
			if (State == ReservationState.Committed || State == ReservationState.RolledBack)
			{
				return;
			}
			foreach (IGrouping<TSource, Tuple<ResourceStack<TItem, TSource>, int>> item in from entry in before
				group entry by entry.Item1.Source)
			{
				foreach (Tuple<ResourceStack<TItem, TSource>, int> item2 in item.OrderBy((Tuple<ResourceStack<TItem, TSource>, int> entry) => entry.Item1.Index))
				{
					restore(item2.Item1, item2.Item2);
				}
			}
			before.Clear();
			State = ReservationState.RolledBack;
		}
	}
	internal enum Severity
	{
		Info,
		Warning,
		Problem
	}
	internal static class ChestDiagnostics
	{
		internal sealed class Finding
		{
			internal DateTime Utc;

			internal Severity Severity;

			internal string Kind = "";

			internal string Line = "";

			internal string Extra = "";

			internal string[] Context = Array.Empty<string>();
		}

		internal sealed class Marker
		{
			internal DateTime Utc;

			internal string Who = "";

			internal string Note = "";

			internal string[] Context = Array.Empty<string>();

			internal string[] Activity = Array.Empty<string>();
		}

		private const string Header = "utc\tsession\trole\tseverity\tevent\toperation\tchest\tpeer\towner\tdata_revision\tloaded_revision\tlocal_use\treplicated_use\tstacks\tfree_slots\titems\tpayload\tdetails";

		private static readonly HashSet<string> ActivityKinds = new HashSet<string>(StringComparer.Ordinal) { "operation-end", "operation-settled", "player-items", "craft-result", "craft-handoff-cancelled", "craft-output-without-consumption", "craft-consumed-without-output" };

		private const int ActivityLimit = 200;

		private const int ActivityMinutes = 20;

		private const int MarkerActivity = 40;

		private const int RecentLimit = 600;

		private const int ChestHistory = 12;

		private const int FindingLimit = 80;

		private const int KeptEarlyFindings = 10;

		private const int MarkerLimit = 30;

		private const int SessionsRetained = 20;

		private const int PartsPerSession = 16;

		internal static readonly string Session = Guid.NewGuid().ToString("N").Substring(0, 12);

		internal static readonly DateTime Started = DateTime.UtcNow;

		private static readonly object gate = new object();

		private static readonly Queue<(DateTime Utc, string Line)> recent = new Queue<(DateTime, string)>();

		private static readonly Queue<(DateTime Utc, string Line)> activity = new Queue<(DateTime, string)>();

		private static readonly Dictionary<ZDOID, Queue<string>> histories = new Dictionary<ZDOID, Queue<string>>();

		private static readonly List<Finding> findings = new List<Finding>();

		private static readonly List<Marker> markers = new List<Marker>();

		private static readonly Dictionary<string, int> counts = new Dictionary<string, int>(StringComparer.Ordinal);

		private static readonly HashSet<string> reportedFailures = new HashSet<string>(StringComparer.Ordinal);

		private static string? directory;

		private static string? writeError;

		private static string role = "client";

		private static StreamWriter? writer;

		private static long bytes;

		private static long limit;

		private static int part;

		private static int droppedFindings;

		private static int problems;

		private static int warnings;

		private static bool enabled;

		private static bool writeFailed;

		[ThreadStatic]
		private static bool recording;

		internal static string Operation = "";

		internal static bool Enabled => enabled;

		internal static bool Recording => recording;

		internal static string? Directory => directory;

		internal static string Role => role;

		internal static int Problems
		{
			get
			{
				lock (gate)
				{
					return problems;
				}
			}
		}

		internal static int Warnings
		{
			get
			{
				lock (gate)
				{
					return warnings;
				}
			}
		}

		internal static int Version { get; private set; }

		internal static void Configure(string path, bool server, long maxBytes)
		{
			Disable();
			role = (server ? "server" : "client");
			try
			{
				if (!Path.IsPathRooted(path))
				{
					throw new ArgumentException("Use an absolute diagnostics directory.", "path");
				}
				directory = Path.GetFullPath(path);
			}
			catch (Exception ex) when (ex is ArgumentException || ex is NotSupportedException || ex is SecurityException)
			{
				CompatibilityInstaller.Error("Diagnostics disabled because the configured directory is invalid: " + ex);
				return;
			}
			limit = maxBytes;
			part = 0;
			writeFailed = false;
			enabled = true;
			Record("session-start", null, "version=" + typeof(Plugin).Assembly.GetName().Version?.ToString() + ";role=" + role);
			CompatibilityInstaller.Info("Diagnostics: logs and reports in " + directory + ". Type /dnc_report in chat to collect a report.");
		}

		internal static void Record(string kind, Container? chest, string details = "", Severity severity = Severity.Info, string extra = "")
		{
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_0303: Unknown result type (might be due to invalid IL or missing references)
			if (!enabled || recording)
			{
				return;
			}
			string text = null;
			string text2 = null;
			recording = true;
			try
			{
				ZDO val = ChestRegistry.LiveZdo(chest);
				ZDOID? id = ((chest != null) ? ChestRegistry.IdOf(chest) : ((ZDOID?)null));
				Inventory val2 = ((chest != null) ? chest.GetInventory() : null);
				long num = ((ZDOMan.instance == null) ? 0 : ZDOMan.GetSessionID());
				long num2 = ((val != null) ? val.GetOwner() : 0);
				string text3 = ((val2 == null) ? "" : Items(val2));
				string text4 = ((val == null) ? "" : Short(ChestRegistry.PayloadHash(val)));
				object obj;
				if (chest != null)
				{
					uint num3 = ChestRegistry.LoadedRevision(chest);
					obj = ((num3 != uint.MaxValue) ? num3.ToString(CultureInfo.InvariantCulture) : "none");
				}
				else
				{
					obj = "";
				}
				string text5 = (string)obj;
				string text6 = ((chest == null) ? "" : (chest.IsInUse() ? "1" : "0"));
				string text7 = ((val == null) ? "" : val.GetInt(ZDOVars.s_inUse, 0).ToString(CultureInfo.InvariantCulture));
				DateTime utcNow = DateTime.UtcNow;
				string[] fields = new string[18]
				{
					utcNow.ToString("O", CultureInfo.InvariantCulture),
					Session,
					role,
					severity.ToString(),
					kind,
					Operation,
					(id.HasValue ? ((object)id.GetValueOrDefault()/*cast due to .constrained prefix*/).ToString() : null) ?? "",
					num.ToString(CultureInfo.InvariantCulture),
					(val == null) ? "" : num2.ToString(CultureInfo.InvariantCulture),
					((val != null) ? val.DataRevision.ToString(CultureInfo.InvariantCulture) : null) ?? "",
					text5,
					text6,
					text7,
					((val2 != null) ? val2.NrOfItems().ToString(CultureInfo.InvariantCulture) : null) ?? "",
					(val2 == null) ? "" : Math.Max(0, val2.GetWidth() * val2.GetHeight() - val2.NrOfItems()).ToString(CultureInfo.InvariantCulture),
					text3,
					text4,
					details + ((extra.Length == 0) ? "" : (" | " + extra))
				};
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append(utcNow.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)).Append(' ');
				if (severity != Severity.Info)
				{
					stringBuilder.Append((severity == Severity.Problem) ? "PROBLEM " : "WARNING ");
				}
				stringBuilder.Append(kind);
				if (Operation.Length > 0)
				{
					stringBuilder.Append(" [").Append(Operation).Append(']');
				}
				if (id.HasValue)
				{
					stringBuilder.Append(" chest=").Append(id.Value);
				}
				if (val != null)
				{
					stringBuilder.Append(" owner=").Append((num2 == 0L) ? "none" : ((num2 == num) ? "self" : num2.ToString(CultureInfo.InvariantCulture))).Append(" rev=")
						.Append(val.DataRevision)
						.Append('/')
						.Append(text5)
						.Append(" use=")
						.Append(text6)
						.Append('/')
						.Append(text7)
						.Append(" payload=")
						.Append(text4);
				}
				else if (id.HasValue)
				{
					stringBuilder.Append(" (unloaded)");
				}
				if (val2 != null)
				{
					stringBuilder.Append(" items=").Append(Clip((text3.Length == 0) ? "empty" : text3, 200));
				}
				if (details.Length > 0)
				{
					stringBuilder.Append(" | ").Append(Clip(details, 400));
				}
				lock (gate)
				{
					Store(kind, severity, id, stringBuilder.ToString(), extra, fields);
					text2 = writeError;
					writeError = null;
				}
			}
			catch (Exception ex)
			{
				text = kind + ": " + ex;
			}
			finally
			{
				recording = false;
			}
			if (text2 != null)
			{
				CompatibilityInstaller.Error(text2);
			}
			if (text != null)
			{
				ReportFailure(kind, text);
			}
		}

		internal static void RecordText(string kind, string details, Severity severity)
		{
			if (!enabled || recording)
			{
				return;
			}
			string text = null;
			string text2 = null;
			recording = true;
			try
			{
				DateTime utcNow = DateTime.UtcNow;
				string[] fields = new string[18]
				{
					utcNow.ToString("O", CultureInfo.InvariantCulture),
					Session,
					role,
					severity.ToString(),
					kind,
					"",
					"",
					"",
					"",
					"",
					"",
					"",
					"",
					"",
					"",
					"",
					"",
					details
				};
				string line = utcNow.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture) + " " + kind + " | " + Clip(details, 400);
				lock (gate)
				{
					Store(kind, severity, null, line, "", fields);
					text2 = writeError;
					writeError = null;
				}
			}
			catch (Exception ex)
			{
				text = kind + ": " + ex;
			}
			finally
			{
				recording = false;
			}
			if (text2 != null)
			{
				CompatibilityInstaller.Error(text2);
			}
			if (text != null)
			{
				ReportFailure(kind, text);
			}
		}

		internal static void Mark(string who, string note)
		{
			if (!enabled)
			{
				return;
			}
			Record("player-marker", null, "player=" + who + ";note=" + note);
			lock (gate)
			{
				DateTime now = DateTime.UtcNow;
				markers.Add(new Marker
				{
					Utc = now,
					Who = who,
					Note = note,
					Context = (from entry in recent
						where (now - entry.Utc).TotalSeconds <= 90.0
						select entry.Line).Reverse().Take(30).Reverse()
						.ToArray(),
					Activity = (from entry in activity
						where (now - entry.Utc).TotalMinutes <= 20.0
						select entry.Line).Reverse().Take(40).Reverse()
						.ToArray()
				});
				if (markers.Count > 30)
				{
					markers.RemoveAt(0);
				}
				Version++;
			}
		}

		private static void Store(string kind, Severity severity, ZDOID? id, string line, string extra, string[] fields)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			counts[kind] = ((!counts.TryGetValue(kind, out var value)) ? 1 : (value + 1));
			string[] context = Array.Empty<string>();
			if (id.HasValue)
			{
				if (!histories.TryGetValue(id.Value, out Queue<string> value2))
				{
					if (histories.Count > 2048)
					{
						histories.Clear();
					}
					value2 = (histories[id.Value] = new Queue<string>());
				}
				if (severity != Severity.Info)
				{
					context = value2.ToArray();
				}
				value2.Enqueue(line);
				if (value2.Count > 12)
				{
					value2.Dequeue();
				}
			}
			else if (severity != Severity.Info)
			{
				context = (from entry in recent.Skip(Math.Max(0, recent.Count - 8))
					select entry.Line).ToArray();
			}
			recent.Enqueue((DateTime.UtcNow, line));
			if (recent.Count > 600)
			{
				recent.Dequeue();
			}
			if (ActivityKinds.Contains(kind))
			{
				activity.Enqueue((DateTime.UtcNow, line));
				if (activity.Count > 200)
				{
					activity.Dequeue();
				}
			}
			if (severity != Severity.Info)
			{
				if (severity == Severity.Problem)
				{
					problems++;
				}
				else
				{
					warnings++;
				}
				findings.Add(new Finding
				{
					Utc = DateTime.UtcNow,
					Severity = severity,
					Kind = kind,
					Line = line,
					Extra = extra,
					Context = context
				});
				if (findings.Count > 80)
				{
					findings.RemoveAt(10);
					droppedFindings++;
				}
			}
			Version++;
			Write(fields);
		}

		private static void Write(string[] fields)
		{
			if (writeFailed || directory == null)
			{
				return;
			}
			try
			{
				string text = string.Join("\t", fields.Select(Escape)) + "\n";
				int byteCount = Encoding.UTF8.GetByteCount(text);
				if (writer == null || bytes + byteCount > limit)
				{
					Rotate();
				}
				writer.Write(text);
				writer.Flush();
				bytes += byteCount;
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
			{
				writeFailed = true;
				Close();
				reportedFailures.Add("event log: " + ex.Message);
				writeError = "Diagnostics stopped writing the event log; reports still work from memory. " + ex;
			}
		}

		private static void ReportFailure(string kind, string failure)
		{
			bool flag;
			lock (gate)
			{
				flag = reportedFailures.Add(kind);
			}
			if (flag)
			{
				CompatibilityInstaller.Error("Diagnostics could not record '" + kind + "'; gameplay continues. " + failure);
			}
		}

		internal static (Finding[] Findings, int Dropped, Marker[] Markers, string[] Recent, string[] Activity, KeyValuePair<string, int>[] Counts, string[] Failures, bool WriteFailed) Snapshot(int recentLines)
		{
			lock (gate)
			{
				return (Findings: findings.ToArray(), Dropped: droppedFindings, Markers: markers.ToArray(), Recent: (from entry in recent.Skip(Math.Max(0, recent.Count - recentLines))
					select entry.Line).ToArray(), Activity: (from entry in activity.Skip(Math.Max(0, activity.Count - recentLines))
					select entry.Line).ToArray(), Counts: counts.OrderByDescending<KeyValuePair<string, int>, int>((KeyValuePair<string, int> entry) => entry.Value).ThenBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> entry) => entry.Key, StringComparer.Ordinal).ToArray(), Failures: reportedFailures.ToArray(), WriteFailed: writeFailed);
			}
		}

		internal static string Items(Inventory inventory)
		{
			return string.Join(";", from @group in (from item in inventory.GetAllItems()
					where item?.m_shared != null
					group item by new
					{
						item.m_shared.m_name,
						item.m_quality,
						item.m_worldLevel
					}).OrderBy(@group => @group.Key.m_name, StringComparer.Ordinal).ThenBy(@group => @group.Key.m_quality).ThenBy(@group => @group.Key.m_worldLevel)
				select @group.Key.m_name + ":q" + @group.Key.m_quality + ":w" + @group.Key.m_worldLevel + "=" + @group.Sum((ItemData item) => item.m_stack));
		}

		internal static Dictionary<string, int> Counts(IEnumerable<Inventory> inventories)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
			foreach (Inventory inventory in inventories)
			{
				foreach (ItemData allItem in inventory.GetAllItems())
				{
					if (allItem?.m_shared != null)
					{
						string key = allItem.m_shared.m_name + ":q" + allItem.m_quality + ":w" + allItem.m_worldLevel;
						dictionary[key] = (dictionary.TryGetValue(key, out var value) ? value : 0) + allItem.m_stack;
					}
				}
			}
			return dictionary;
		}

		internal static Dictionary<string, int> Delta(Dictionary<string, int> before, Dictionary<string, int> after)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
			foreach (string item in before.Keys.Union(after.Keys))
			{
				int value;
				int value2;
				int num = (after.TryGetValue(item, out value) ? value : 0) - (before.TryGetValue(item, out value2) ? value2 : 0);
				if (num != 0)
				{
					dictionary[item] = num;
				}
			}
			return dictionary;
		}

		internal static string Format(Dictionary<string, int> delta)
		{
			if (delta.Count != 0)
			{
				return string.Join(";", from entry in delta.OrderBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> entry) => entry.Key, StringComparer.Ordinal)
					select entry.Key + "=" + ((entry.Value > 0) ? "+" : "") + entry.Value);
			}
			return "none";
		}

		internal static string Short(string hash)
		{
			if (hash.Length <= 12)
			{
				return hash;
			}
			return hash.Substring(0, 12);
		}

		internal static string Stack(int skip, int frames)
		{
			StackTrace stackTrace = new StackTrace(skip + 1, fNeedFileInfo: false);
			return string.Join(" < ", (from method in stackTrace.GetFrames()?.Select((StackFrame frame) => frame.GetMethod())
				where method != null
				select (method.DeclaringType?.FullName ?? "?") + "." + method.Name into name
				where !name.StartsWith("DeepNorthCompat.ChestDiagnostics", StringComparison.Ordinal)
				select name).Take(frames) ?? Enumerable.Empty<string>());
		}

		private static string Clip(string value, int length)
		{
			if (value.Length > length)
			{
				return value.Substring(0, length) + "…";
			}
			return value;
		}

		private static string Escape(string value)
		{
			return value.Replace("\\", "\\\\").Replace("\t", "\\t").Replace("\r", "\\r")
				.Replace("\n", "\\n");
		}

		private static void Rotate()
		{
			Close();
			System.IO.Directory.CreateDirectory(directory);
			string[] obj = new string[9] { "DeepNorthCompat-events-", role, "-", null, null, null, null, null, null };
			DateTime started = Started;
			obj[3] = started.ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture);
			obj[4] = "-";
			obj[5] = Session;
			obj[6] = "-";
			int num = ++part;
			obj[7] = num.ToString("D3", CultureInfo.InvariantCulture);
			obj[8] = ".tsv";
			string path = string.Concat(obj);
			writer = new StreamWriter(new FileStream(Path.Combine(directory, path), FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			string[] obj2 = new string[11]
			{
				"# DeepNorthCompat ",
				typeof(Plugin).Assembly.GetName().Version?.ToString(),
				" ",
				role,
				" session ",
				Session,
				" started ",
				null,
				null,
				null,
				null
			};
			started = Started;
			obj2[7] = started.ToString("O", CultureInfo.InvariantCulture);
			obj2[8] = " part ";
			obj2[9] = part.ToString();
			obj2[10] = "\nutc\tsession\trole\tseverity\tevent\toperation\tchest\tpeer\towner\tdata_revision\tloaded_revision\tlocal_use\treplicated_use\tstacks\tfree_slots\titems\tpayload\tdetails\n";
			string text = string.Concat(obj2);
			writer.Write(text);
			bytes = Encoding.UTF8.GetByteCount(text);
			FileInfo[] files = new DirectoryInfo(directory).GetFiles("DeepNorthCompat-events-" + role + "-*.tsv");
			foreach (IGrouping<string, FileInfo> item in (from file in files
				group file by SessionOf(file.Name) into @group
				orderby @group.Max((FileInfo file) => file.LastWriteTimeUtc) descending
				where @group.Key != Session
				select @group).Skip(19))
			{
				foreach (FileInfo item2 in item)
				{
					item2.Delete();
				}
			}
			foreach (FileInfo item3 in from file in files.Where((FileInfo file) => SessionOf(file.Name) == Session).OrderByDescending<FileInfo, string>((FileInfo file) => file.Name, StringComparer.Ordinal).Skip(16)
				where !file.Name.EndsWith("-001.tsv", StringComparison.Ordinal)
				select file)
			{
				item3.Delete();
			}
		}

		private static string SessionOf(string file)
		{
			string[] array = Path.GetFileNameWithoutExtension(file).Split(new char[1] { '-' });
			if (array.Length < 2)
			{
				return file;
			}
			return array[^2];
		}

		internal static void Close()
		{
			StreamWriter streamWriter = writer;
			writer = null;
			try
			{
				streamWriter?.Dispose();
			}
			catch (IOException ex)
			{
				CompatibilityInstaller.Error("Diagnostics could not finish closing the event log: " + ex);
			}
		}

		internal static void Disable()
		{
			lock (gate)
			{
				Close();
				enabled = false;
				directory = null;
			}
		}

		internal static void Clear()
		{
			lock (gate)
			{
				recent.Clear();
				activity.Clear();
				histories.Clear();
				findings.Clear();
				markers.Clear();
				counts.Clear();
				reportedFailures.Clear();
				droppedFindings = (problems = (warnings = 0));
				Version++;
			}
			ItemLedger.Reset();
		}
	}
	internal static class ExpectedBuilds
	{
		internal const string Valheim1020Client = "94998885B103D6E5F5480123EAEE0A093E82AF2DDEEEE37536C15BF555F24F3A";

		internal const string Valheim1021Client = "9F959C0396EC4240D47FCBE5D0D062C428CC627244506DB5EA567F9D77B2B769";

		internal const string Valheim1021WindowsServer = "648F3F8ED7B44C3D3CD612ACD782743D9E03AF7E60B7FE72D5827523E95505FD";

		internal const string Valheim1021LinuxServer = "72F77A0E9C70CF0329E9F1F58687BBA5DC9FC77F203BC1826F3A3CA1A7B81312";

		internal const string GuiUtils1021Client = "08A5AEA10B3E8BF20B60B3AB545B6CB8550DB8B12CFF05E32C90BDD9F45DC244";

		internal const string BetterMap = "BB0A0A2E4E9EA2B388CD55F486A61057BF57F982D5647AA649375D4B1E7BAE04";

		internal const string Cartography = "2379F6884BEC32843DAFA1306F693CAD8FC2FB1208E9D2BEE3D3745EFB2DC529";

		internal const string Vpo123 = "614CD643343E2E2D182BA4B50AA8C96D8FEDB8E09A16C6AA0018BAD222D6EE70";

		internal const string Vpo200 = "5BC06CD13EECAFDE08384DD1DB6B3B56073B93E9EF2F6CB3835782B305E19AC7";

		internal const string Vpo201 = "E7F44265DA04E5809530F1212980DB23BB00645CA51BD2B45907CBDAD82B4F1F";

		internal const string Vpo210 = "749149620CC43ADF048B609DE057D6F8155DF65CE98620C670E0DB02417844E8";

		internal const string Vpo220 = "B44AA55759C0464ED10B0F1AC1E8FC8C5916A537E1FA1BD47A8B473ADFCFBE29";

		internal const string SteadyFrame131 = "92AB5E64BE2827600A03321172AC3D085F63E15D87B2782C2C05C2230D05D2B0";

		internal const string FarLands141 = "5840564ED6910B4648DBE13F2267B38EF609AA96D1D0EFE72B068031B6257BE6";

		internal const string MagicRevamp151 = "B8BD009ED03EEF3BB388ED603474C45F70339DB275564D28EAB6A2A4ABF0E385";

		internal const string Backpacks1310 = "8B87E770095001271EED051065A83E589F8AECCDA46FB7BB0298B92323BA43F4";

		internal static readonly string[] Vpo2 = new string[4] { "5BC06CD13EECAFDE08384DD1DB6B3B56073B93E9EF2F6CB3835782B305E19AC7", "E7F44265DA04E5809530F1212980DB23BB00645CA51BD2B45907CBDAD82B4F1F", "749149620CC43ADF048B609DE057D6F8155DF65CE98620C670E0DB02417844E8", "B44AA55759C0464ED10B0F1AC1E8FC8C5916A537E1FA1BD47A8B473ADFCFBE29" };

		internal static readonly string[] Vpo = Vpo2.Prepend("614CD643343E2E2D182BA4B50AA8C96D8FEDB8E09A16C6AA0018BAD222D6EE70").ToArray();

		internal static readonly string[] VpoGrassAndStreaming = new string[2] { "749149620CC43ADF048B609DE057D6F8155DF65CE98620C670E0DB02417844E8", "B44AA55759C0464ED10B0F1AC1E8FC8C5916A537E1FA1BD47A8B473ADFCFBE29" };

		internal static readonly string[] TeleportEverything = new string[3] { "7E4B67FAEC0A475312745B3ED06FD7754C14AAC4D6BCECFE56FD93E439DE605B", "502411B7A4EB99868ADC13CFB48A784FCEB89C814F8D48AFD3B4C75922798A46", "584DF4B5C285D7AA6B19DABC9E8486AD145EC2975A8678906062E183FEBAE586" };

		internal static readonly string[] PlantEverything = new string[2] { "313D57D5D9DF2A27BFF04AB184487D544A0749BBBE2C10CB1C41A0AE964CAC62", "AE6F90220AC138E9CC90DEEFA530E934007DE4BF899B4AC51712525E268F6147" };

		internal static readonly string[] PlantEasily = new string[2] { "D5AD697931C97E86DBC72AFA3B9BCAC90F3AE249C3A50FE7AD94302C4C2B8416", "9D56DAE0117798E504B0BAE000E4C848AEAF8642648E19CE99E36D59FA173ECB" };

		internal const string NoCultivatorDust = "D3761A25915D573207BF529C7DEF9372E2CABFEBEBFDC932D799837126F4EEB3";

		internal const string NoBuildDust = "80329CE6E96341F59D2CE9C77E4F1826E19B8D171473332A007B68AEA0963604";

		internal static readonly string[] BetterMapGame = new string[9] { "25A0A107DCE4D834C44C2B72D0EAFD5CB7793933BDA81816ACCFA1EA9543DACE", "0DFC7E81436F822121148EFED859BA1E661D58B9484BD45E3B6F33B6DD86BFAD", "E7220DC5D9CF9D38270E751352D94918308E59CCA86E56C4BDA0210016C847FA", "94998885B103D6E5F5480123EAEE0A093E82AF2DDEEEE37536C15BF555F24F3A", "EF8C8D3A1F45694EF7A701E8E2A25BF8A3874C951A2639C81DFE614CE3AA5FA3", "C36B81C1733C48D00DD567E41010E6DC95F8DAC877E0701CDB6B8C213ADE7812", "9F959C0396EC4240D47FCBE5D0D062C428CC627244506DB5EA567F9D77B2B769", "648F3F8ED7B44C3D3CD612ACD782743D9E03AF7E60B7FE72D5827523E95505FD", "72F77A0E9C70CF0329E9F1F58687BBA5DC9FC77F203BC1826F3A3CA1A7B81312" };

		internal static readonly string[] ImpactfulSkillsBowDefect = new string[6] { "D6E0844F3DADE42B23C33A678EB6E3D6DAA288DCC4187F497B8BB2A1F3CF47BA", "52DB5951ADDA57426706A58C9F7C530DFD7519A3E987C73516992111588EF656", "E74CDE9D2F5EC13DE46A301F4FCE2FB0F66932C234A5E8E6F685FB18D454E6D9", "79345A447506C6AE8D13A36DA8FD1FCDCBD965C5DA110B3953B8EA9517F7889D", "5B9CD6A20531E33BCE52E4EFD37631A82B0F0AA40D66860D8E1CDDC597736F66", "C87ACCAF7E710BD2A13E4F766E4EBFACE9495EFDBC7CADB7C847C3707581ADB4" };

		internal static readonly string[] ImpactfulSkillsBowFixed = new string[2] { "928DF592E04F489826DD823619FEDED6A04195CA38103855ED0C3F01C9EFC050", "19B9E4268C68AF645A2812574797EA9579DFBF5E1B3D8AD9FCA3A23F07DF8164" };

		internal static readonly string[] ImpactfulSkills = ImpactfulSkillsBowDefect.Concat(ImpactfulSkillsBowFixed).ToArray();

		internal static readonly string[] CraftyBoxes = new string[2] { "432285A08AA0D43BBD89B36330BEDC19CB6EA93AED439E493D0287EDAECEDEB4", "381883FE4625D1DD119BB425A2F3C7522457FBC08AE1DB60159F8256DE940D6E" };

		internal static readonly string[] AAACrafting = new string[2] { "316C5B47B449B8172627BD48C12830429E38BBD21A704746F86D1053D38D4830", "D511490759B3EE7A1041CBEF9BAF27BAEF9530C6F225323D824628638B62E6AF" };

		internal const string SeaAnimals = "3F57F6AD089D5616A924D5917851A0A7C99715CC0B2062EF23B2FA15D07C721A";

		internal const string AirAnimals = "B29905FFDA5204570D64958CB18D74E08D7CEE8AA361485E1D988B54242F2F85";

		internal static readonly string[] Valheim = new string[4] { "96CFC004F7F4A6F30D070BEF39EAFD79C466A137121C4665A2F19FB9C15C6127", "25A0A107DCE4D834C44C2B72D0EAFD5CB7793933BDA81816ACCFA1EA9543DACE", "94998885B103D6E5F5480123EAEE0A093E82AF2DDEEEE37536C15BF555F24F3A", "9F959C0396EC4240D47FCBE5D0D062C428CC627244506DB5EA567F9D77B2B769" };

		internal static readonly string[] AzuEpi = new string[3] { "0C8702F9F9A3F4AE2A0E9977801F40E1691E42D1B5CE60863C1B01FF5697C52E", "BA743704019F1C693A53A445162C95965854B55EDDC83C5EA45C8F66D938FA5F", "5F026B5DD4529CBA498377D293432157A53082CFD3FC06C2384D23DBA5307AC6" };

		internal const string OdinShip = "5D5817BC169677DB49CAE55986B3F6A178AB3BF0B1D681A2ABA4ECC5DAC067D0";

		internal static readonly string[] OdinShipGame = new string[9] { "25A0A107DCE4D834C44C2B72D0EAFD5CB7793933BDA81816ACCFA1EA9543DACE", "0DFC7E81436F822121148EFED859BA1E661D58B9484BD45E3B6F33B6DD86BFAD", "E7220DC5D9CF9D38270E751352D94918308E59CCA86E56C4BDA0210016C847FA", "94998885B103D6E5F5480123EAEE0A093E82AF2DDEEEE37536C15BF555F24F3A", "EF8C8D3A1F45694EF7A701E8E2A25BF8A3874C951A2639C81DFE614CE3AA5FA3", "C36B81C1733C48D00DD567E41010E6DC95F8DAC877E0701CDB6B8C213ADE7812", "9F959C0396EC4240D47FCBE5D0D062C428CC627244506DB5EA567F9D77B2B769", "648F3F8ED7B44C3D3CD612ACD782743D9E03AF7E60B7FE72D5827523E95505FD", "72F77A0E9C70CF0329E9F1F58687BBA5DC9FC77F203BC1826F3A3CA1A7B81312" };

		internal static readonly string[] Server = new string[8] { "7CAB9B49D31EC064591CA80402DD35C566E03B7297CFB7BF4696C38DA4E24D8B", "50035055F9B158A025CACD25E038B603943F7C2A465DA3021707B5F1E44E39FD", "0DFC7E81436F822121148EFED859BA1E661D58B9484BD45E3B6F33B6DD86BFAD", "E7220DC5D9CF9D38270E751352D94918308E59CCA86E56C4BDA0210016C847FA", "EF8C8D3A1F45694EF7A701E8E2A25BF8A3874C951A2639C81DFE614CE3AA5FA3", "C36B81C1733C48D00DD567E41010E6DC95F8DAC877E0701CDB6B8C213ADE7812", "648F3F8ED7B44C3D3CD612ACD782743D9E03AF7E60B7FE72D5827523E95505FD", "72F77A0E9C70CF0329E9F1F58687BBA5DC9FC77F203BC1826F3A3CA1A7B81312" };
	}
	public static class CompatibilityInstaller
	{
		internal const string ImpactGuid = "MidnightsFX.ImpactfulSkills";

		internal const string CraftyGuid = "Azumatt.AzuCraftyBoxes";

		internal static Action<string> Info = delegate
		{
		};

		internal static Action<string> Warning = delegate
		{
		};

		internal static Action<string> Error = delegate
		{
		};

		public static void Install(Func<string, Assembly?> resolve, Action<string> info, Action<string> warning, Action<string> error)
		{
			Info = info;
			Warning = warning;
			Error = error;
			Assembly impact = resolve("MidnightsFX.ImpactfulSkills");
			Assembly crafty = resolve("Azumatt.AzuCraftyBoxes");
			InstallGroup("Bow", delegate
			{
				if (impact == null)
				{
					Info("Bow: ImpactfulSkills absent; inactive.");
				}
				else if (Guard.KnownServerBuild())
				{
					Info("Bow: client-only patch; inactive on dedicated server.");
				}
				else
				{
					Guard.Build(impact, ExpectedBuilds.ImpactfulSkills);
					if (ExpectedBuilds.ImpactfulSkillsBowFixed.Contains(Guard.Sha256(impact.Location)))
					{
						Info("Bow: fixed upstream in this ImpactfulSkills build; inactive.");
					}
					else
					{
						Guard.Build(typeof(InventoryGui).Assembly, ExpectedBuilds.Valheim);
						BowPatch.Install(impact);
					}
				}
			});
			InstallGroup("Drops.SeaAnimals", delegate
			{
				InstallDrops(resolve("marlthon.SeaAnimals"), "3F57F6AD089D5616A924D5917851A0A7C99715CC0B2062EF23B2FA15D07C721A", "SeaAnimals");
			});
			InstallGroup("Drops.AirAnimals", delegate
			{
				InstallDrops(resolve("marlthon.AirAnimals"), "B29905FFDA5204570D64958CB18D74E08D7CEE8AA361485E1D988B54242F2F85", "AirAnimals");
			});
			InstallGroup("Quality", delegate
			{
				if (impact == null || crafty == null)
				{
					Info("Quality: optional mod absent; inactive.");
				}
				else if (Guard.KnownServerBuild())
				{
					Info("Quality: client-only patch; inactive on dedicated server.");
				}
				else
				{
					Guard.Build(impact, ExpectedBuilds.ImpactfulSkills);
					Guard.Build(crafty, ExpectedBuilds.CraftyBoxes);
					Guard.Build(typeof(InventoryGui).Assembly, ExpectedBuilds.Valheim);
					Assembly assembly = resolve("Azumatt.AzuAntiArthriticCrafting");
					if (assembly != null)
					{
						Guard.Build(assembly, ExpectedBuilds.AAACrafting);
					}
					QualityPatch.Install(impact, crafty, assembly != null);
				}
			});
			InstallGroup("Crafting.ForgeOfPotential", delegate
			{
				ForgeCraftingPatch.Prepare(resolve("Azumatt.AzuAntiArthriticCrafting"));
			});
			InstallGroup("UI.AAARecipeRows", delegate
			{
				AaaRecipeRowsPatch.Prepare(resolve("Azumatt.AzuAntiArthriticCrafting"));
			});
			InstallGroup("Crafting.ReforgedPotential", delegate
			{
				ReforgedPotentialPatch.Prepare(resolve("akuichi.ReforgedPotential"));
			});
			InstallGroup("Preview.AzuEPI", delegate
			{
				if (Guard.KnownServerBuild())
				{
					Info("Preview.AzuEPI: client-only patch; inactive on dedicated server.");
				}
				else
				{
					AzuEpiPreviewPatch.Prepare(resolve("Azumatt.AzuExtendedPlayerInventory"));
				}
			});
			InstallGroup("VPO.Burst", delegate
			{
				VpoBurstPatch.Prepare(resolve("dev.ontrigger.vpo"));
			});
			InstallGroup("VPO.TerrainGrass", delegate
			{
				VpoTerrainGrassPatch.Prepare(resolve("dev.ontrigger.vpo"));
			});
			InstallGroup("VPO.Materials", delegate
			{
				VpoMaterialsPatch.Prepare(resolve("dev.ontrigger.vpo"), resolve("ru.ivest.valheimvisuals"));
			});
			InstallGroup("FarLands.Rendering", delegate
			{
				FarLandsRenderingPatch.Prepare(resolve("ru.ivest.farlands"), resolve("dev.ontrigger.vpo"));
			});
			InstallGroup("SteadyFrame.Structures", delegate
			{
				SteadyFrameStructurePatch.Prepare(resolve("ru.ivest.steadyframe"), resolve("dev.ontrigger.vpo"));
			});
			InstallGroup("VPO.Animation", delegate
			{
				VpoAnimationPatch.Prepare(resolve("dev.ontrigger.vpo"), resolve("ZenDragon.Zen.ModLib"));
			});
			InstallGroup("Performance.IdleSync", IdleSyncPatch.Prepare);
			InstallGroup("RuneMagic.Ice", delegate
			{
				RuneIcePatch.Prepare(resolve("hyleanlegend.RuneMagic"));
			});
			InstallGroup("RuneMagic.SpriteMaterials", delegate
			{
				RuneSpritePatch.Prepare(resolve("hyleanlegend.RuneMagic"));
			});
			InstallGroup(RuneRequirementPatch.Group.Name, delegate
			{
				RuneRequirementPatch.Prepare(resolve("hyleanlegend.RuneMagic"));
			});
			InstallGroup(VisibleLocalizationPatch.Group.Name, VisibleLocalizationPatch.Prepare);
			InstallGroup("UI.TabAudio", TabAudioPatch.Prepare);
			InstallGroup("UI.TeleportEverything", delegate
			{
				TeleportEverythingPatch.Prepare(resolve("odinplus.TeleportEverything"));
			});
			InstallGroup("MyLittleUI.AmmoCount", delegate
			{
				MyLittleUiAmmoPatch.Prepare(resolve("shudnal.MyLittleUI"));
			});
			Assembly magic = resolve("blacks7ar.MagicRevamp");
			Assembly backpacks = resolve("org.bepinex.plugins.backpacks");
			InstallGroup("MagicRevamp.Inventory", delegate
			{
				MagicRevampInventoryPatch.Prepare(magic, backpacks);
			});
			InstallGroup("MagicRevamp.Crafting", delegate
			{
				MagicRevampCraftingPatch.Prepare(magic, backpacks);
			});
			InstallGroup("MagicRevamp.Eitr", delegate
			{
				MagicRevampEitrPatch.Prepare(magic);
			});
			InstallGroup("MagicRevamp.Hud", delegate
			{
				MagicRevampHudPatch.Prepare(magic);
			});
			InstallGroup("MagicRevamp.Cycle", delegate
			{
				MagicRevampCyclePatch.Prepare(magic, backpacks);
			});
			InstallGroup("MagicRevamp.Portal", delegate
			{
				MagicRevampPortalPatch.Prepare(magic);
			});
			InstallGroup("MagicRevamp.AmmoDisplay", delegate
			{
				MagicRevampAmmoDisplayPatch.Prepare(magic, backpacks, resolve("shudnal.MyLittleUI"));
			});
			InstallGroup("PlantEasily.GridCost", delegate
			{
				PlantEasilyCostPatch.Prepare(resolve("advize.PlantEasily"));
			});
			InstallGroup("NoSmokeStayLit.Controls", delegate
			{
				NoSmokeStayLitPatch.Prepare(resolve("TastyChickenLegs.NoSmokeStayLit"));
			});
			InstallGroup("PlantEverything.Dust", delegate
			{
				PlantEverythingDustPatch.Prepare(resolve("advize.PlantEverything"), resolve("Azumatt.NoCultivatorDust"), resolve("Azumatt.NoBuildDust"));
			});
			InstallGroup("Tune.Client", delegate
			{
				TuneClientPatch.Prepare(resolve("akoozie.valheimtune"));
			});
			Assembly hearth = resolve("Azumatt.HearthBelow");
			InstallGroup("Grass.ColliderGround", delegate
			{
				GpuGrassTerrainPatch.Prepare(hearth, resolve("ru.ivest.steadyframe"), resolve("ru.ivest.farlands"), resolve("MidnightsFX.ValheimCommunityPatch"));
			});
			InstallGroup("Terrain.HearthBelow.Replay", delegate
			{
				HearthTerrainPatch.PrepareReplay(hearth);
			});
			InstallGroup("Terrain.HearthBelow", delegate
			{
				HearthTerrainPatch.Prepare(hearth, resolve("hyleanlegend.RuneMagic"));
			});
			InstallGroup("Terrain.PrecisionLimits", delegate
			{
				PrecisionTerrainPatch.PrepareLimits(resolve("Searica.Valheim.TerrainTools"), resolve("digitalroot.mods.heightmapunlimitedjvl"), resolve("Searica.Valheim.AdvancedHeightMap"));
			});
			InstallGroup("Terrain.HearthBelow.Precision", delegate
			{
				PrecisionTerrainPatch.PrepareHearth(resolve("Searica.Valheim.TerrainTools"), hearth);
			});
			InstallGroup("Terrain.FarLands", delegate
			{
				FarLandsTerrainPatch.Prepare(resolve("ru.ivest.farlands"), resolve("digitalroot.mods.heightmapunlimitedjvl"));
			});
			InstallGroup("UsefulPaths.Effects", delegate
			{
				UsefulPathsPatch.PrepareEffects(resolve("RustyMods.UsefulPaths"));
			});
			InstallGroup("UsefulPaths.Cart", delegate
			{
				UsefulPathsPatch.PrepareCart(resolve("RustyMods.UsefulPaths"), impact);
			});
			Assembly odin = resolve("marlthon.OdinShip");
			InstallGroup("OdinShip.Core", delegate
			{
				OdinShipPatch.Prepare(odin);
			});
			InstallGroup("OdinShip.Input", delegate
			{
				OdinShipInputPatch.Prepare(odin);
			});
			InstallGroup("OdinShip.FishPress", delegate
			{
				OdinShipFishPatch.Prepare(odin);
			});
			InstallGroup("OdinShip.Construction", delegate
			{
				OdinShipConstructionPatch.Prepare(odin);
			});
			Assembly betterMap = resolve("xtav1m.BetterMap");
			InstallGroup("Map.Cartography", delegate
			{
				BetterMapCartographyPatch.Prepare(betterMap, resolve("advize.CartographySkill"));
			});
			InstallGroup("Map.Session", delegate
			{
				BetterMapSessionPatch.Prepare(betterMap);
			});
			InstallGroup("Map.Persistence", delegate
			{
				BetterMapPersistencePatch.Prepare(betterMap);
			});
			InstallGroup("Map.Portals", delegate
			{
				BetterMapPortalPatch.Prepare(betterMap);
			});
			InstallGroup("Map.VehicleUpdates", delegate
			{
				BetterMapVehiclePatch.Prepare(betterMap);
			});
			InstallGroup("Chests.Registry", delegate
			{
				ChestRegistry.Install(crafty);
			});
			InstallGroup("ChestCraft", delegate
			{
				ChestCraftPatch.Install(crafty);
			});
			InstallGroup("Chests", delegate
			{
				ChestSyncPatch.Install(resolve("com.maxsch.valheim.MultiUserChest"), resolve("goldenrevolver.quick_stack_store"));
			});
			InstallGroup("Diagnostics", DiagnosticsPatch.Install);
		}

		public static void Verify()
		{
			DropRangePatch.Verify();
			ForgeCraftingPatch.Verify();
			AaaRecipeRowsPatch.Verify();
			ReforgedPotentialPatch.Verify();
			AzuEpiPreviewPatch.Verify();
			VpoBurstPatch.Verify();
			VpoTerrainGrassPatch.Verify();
			VpoMaterialsPatch.Verify();
			FarLandsRenderingPatch.Verify();
			FarLandsTerrainPatch.Verify();
			SteadyFrameStructurePatch.Verify();
			VpoAnimationPatch.Verify();
			IdleSyncPatch.Verify();
			RuneIcePatch.Verify();
			RuneSpritePatch.Verify();
			RuneRequirementPatch.Group.Verify();
			VisibleLocalizationPatch.Group.Verify();
			TabAudioPatch.Verify();
			TeleportEverythingPatch.Verify();
			MyLittleUiAmmoPatch.Verify();
			MagicRevampInventoryPatch.Verify();
			MagicRevampCraftingPatch.Verify();
			MagicRevampEitrPatch.Verify();
			MagicRevampHudPatch.Verify();
			MagicRevampCyclePatch.Verify();
			MagicRevampPortalPatch.Verify();
			MagicRevampAmmoDisplayPatch.Verify();
			PlantEasilyCostPatch.Verify();
			NoSmokeStayLitPatch.Verify();
			PlantEverythingDustPatch.Verify();
			TuneClientPatch.Verify();
			GpuGrassTerrainPatch.Verify();
			HearthTerrainPatch.Verify();
			PrecisionTerrainPatch.Verify();
			UsefulPathsPatch.VerifyEffects();
			UsefulPathsPatch.VerifyCart();
			OdinShipPatch.Verify();
			OdinShipInputPatch.Verify();
			OdinShipFishPatch.Verify();
			OdinShipConstructionPatch.Verify();
			BetterMapCartographyPatch.Verify();
			BetterMapSessionPatch.Verify();
			BetterMapPersistencePatch.Verify();
			BetterMapPortalPatch.Verify();
			BetterMapVehiclePatch.Verify();
			DiagnosticsPatch.Verify();
		}

		private static void InstallDrops(Assembly? assembly, string hash, string name)
		{
			if (assembly == null)
			{
				Info("Drops." + name + ": mod absent; inactive.");
				return;
			}
			Guard.Build(assembly, hash);
			DropRangePatch.Install(assembly, name);
		}

		private static void InstallGroup(string name, Action install)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				install();
			}
			catch (Exception arg)
			{
				try
				{
					new Harmony("DeepNorthCompat." + name).UnpatchSelf();
				}
				catch (Exception arg2)
				{
					Error($"{name}: Harmony rollback failed; some hooks may remain active. {arg2}");
				}
				Error(name + ": NOT APPLIED; expected installed implementation changed or patch failed. " + $"Vendor behavior retained. {arg}");
			}
		}
	}
	public static class Guard
	{
		private static readonly object gate = new object();

		private static readonly Dictionary<string, (long Length, DateTime Written, string Hash)> hashes = new Dictionary<string, (long, DateTime, string)>(StringComparer.Ordinal);

		internal static bool KnownServerBuild()
		{
			return ExpectedBuilds.Server.Contains(Sha256(typeof(ZNet).Assembly.Location));
		}

		public static void Build(Assembly assembly, params string[] expectedHashes)
		{
			string text = Sha256(assembly.Location);
			if (!expectedHashes.Contains(text))
			{
				throw new NotSupportedException(assembly.GetName().Name + " build changed; expected " + string.Join(" or ", expectedHashes) + ", found " + text + ". Re-audit required.");
			}
		}

		internal static string Sha256(string path)
		{
			FileInfo fileInfo = new FileInfo(path);
			long length = fileInfo.Length;
			DateTime lastWriteTimeUtc = fileInfo.LastWriteTimeUtc;
			lock (gate)
			{
				if (hashes.TryGetValue(path, out (long, DateTime, string) value) && value.Item1 == length && value.Item2 == lastWriteTimeUtc)
				{
					return value.Item3;
				}
			}
			string text;
			using (SHA256 sHA = SHA256.Create())
			{
				using FileStream inputStream = File.OpenRead(path);
				text = BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", "");
			}
			lock (gate)
			{
				hashes[path] = (length, lastWriteTimeUtc, text);
				return text;
			}
		}

		internal static Type Type(Assembly assembly, string name)
		{
			return assembly.GetType(name, throwOnError: true);
		}

		internal static MethodInfo Method(Type type, string name, Type returnType, params Type[] parameters)
		{
			MethodInfo method = type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameters, null);
			if (method == null || method.ReturnType != returnType)
			{
				throw new MissingMethodException(type.FullName, name);
			}
			return method;
		}

		internal static HarmonyMethod Hook(Type type, string name, int priority = 400)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return new HarmonyMethod(AccessTools.DeclaredMethod(type, name, (Type[])null, (Type[])null))
			{
				priority = priority
			};
		}

		internal static void Registered(MethodBase target)
		{
			CompatibilityInstaller.Info("Registered: " + Name(target));
		}

		internal unsafe static Patch Sole(MethodBase target, MethodInfo hook, string owner, HarmonyPatchType kind)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			Patches patchInfo = Harmony.GetPatchInfo(target);
			Patch[] array = ((patchInfo == null) ? Array.Empty<Patch>() : (from p in All(patchInfo)
				where p.PatchMethod == hook
				select p).ToArray());
			if (array.Length != 1 || array[0].owner != owner || !Of(patchInfo, kind).Contains(array[0]))
			{
				throw new NotSupportedException("Expected one " + owner + " " + ((object)(*(HarmonyPatchType*)(&kind))/*cast due to .constrained prefix*/).ToString().ToLowerInvariant() + " " + Name(hook) + " on " + Name(target) + ".");
			}
			return array[0];
		}

		internal static void Restore(MethodBase target, Patch patch, HarmonyPatchType kind)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Invalid comparison between Unknown and I4
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Invalid comparison between Unknown and I4
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Invalid comparison between Unknown and I4
			Patches patchInfo = Harmony.GetPatchInfo(target);
			if (patchInfo == null || !All(patchInfo).Any((Patch p) => p.PatchMethod == patch.PatchMethod))
			{
				if ((int)kind != 1 && (int)kind != 2)
				{
					throw new ArgumentOutOfRangeException("kind");
				}
				HarmonyMethod val = new HarmonyMethod(patch.PatchMethod, patch.priority, patch.before, patch.after, (bool?)patch.debug);
				new Harmony(patch.owner).Patch(target, ((int)kind == 1) ? val : null, ((int)kind == 2) ? val : null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static IEnumerable<Patch> All(Patches info)
		{
			return info.Prefixes.Concat(info.Postfixes).Concat(info.Transpilers).Concat(info.Finalizers)
				.Concat(info.ILManipulators);
		}

		private static IEnumerable<Patch> Of(Patches info, HarmonyPatchType kind)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected I4, but got Unknown
			return (kind - 1) switch
			{
				0 => info.Prefixes, 
				1 => info.Postfixes, 
				2 => info.Transpilers, 
				3 => info.Finalizers, 
				_ => throw new ArgumentOutOfRangeException("kind"), 
			};
		}

		internal static string Name(MethodBase target)
		{
			return target.DeclaringType.Assembly.GetName().Name + ":" + target.DeclaringType.FullName + "." + target.Name;
		}
	}
	internal static class DiagnosticReport
	{
		internal enum Access
		{
			Nobody,
			Admins,
			Everyone
		}

		private sealed class Error
		{
			internal string Source = "";

			internal string Level = "";

			internal string Text = "";

			internal int Count;

			internal DateTime First;

			internal DateTime Last;

			internal string[] Context = Array.Empty<string>();
		}

		private sealed class Budget
		{
			internal int Findings;

			internal int Context;

			internal int Errors;

			internal int ErrorText;

			internal int Recent;
		}

		private sealed class Listener : ILogListener, IDisposable
		{
			public void LogEvent(object sender, LogEventArgs eventArgs)
			{
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				ILogSource source = eventArgs.Source;
				Capture(((source != null) ? source.SourceName : null) ?? "", eventArgs.Level, eventArgs.Data?.ToString() ?? "");
			}

			public void Dispose()
			{
			}
		}

		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<string, bool> <>9__32_0;

			public static ConsoleEvent <>9__33_0;

			public static ConsoleEvent <>9__33_1;

			public static Func<bool, string> <>9__49_0;

			public static Func<string, string> <>9__61_0;

			public static Func<string, bool> <>9__61_1;

			public static Func<string, string> <>9__61_2;

			public static Func<FileInfo, bool> <>9__62_0;

			public static Func<FileInfo, DateTime> <>9__62_1;

			public static Func<Error, DateTime> <>9__65_3;

			public static Func<KeyValuePair<string, int>, string> <>9__65_0;

			public static Func<PluginInfo, string> <>9__65_1;

			public static Func<PluginInfo, string> <>9__65_2;

			public static Func<Error, int> <>9__66_0;

			public static Func<string, string> <>9__69_0;

			internal bool <Capture>b__32_0(string line)
			{
				return line.Trim().Length > 0;
			}

			internal void <RegisterCommands>b__33_0(ConsoleEventArgs args)
			{
				if (args.Args.Length > 1 && string.Equals(args.Args[1], "last", StringComparison.OrdinalIgnoreCase))
				{
					SendPrevious(args.Context);
				}
				else
				{
					Collect(args.Context);
				}
			}

			internal void <RegisterCommands>b__33_1(ConsoleEventArgs args)
			{
				MarkCommand(args.Context, string.Join(" ", args.Args.Skip(1)));
			}

			internal string <MarkCommand>b__49_0(bool compact)
			{
				return Snapshot(compact, null);
			}

			internal string <PatchSummary>b__61_0(string line)
			{
				return line.Substring(Math.Min(line.Length, 9));
			}

			internal bool <PatchSummary>b__61_1(string line)
			{
				if (!line.Contains(": APPLIED"))
				{
					return line.Contains("NOT APPLIED");
				}
				return true;
			}

			internal string <PatchSummary>b__61_2(string line)
			{
				if (!line.Contains("NOT APPLIED"))
				{
					return line.Split(new char[1] { ':' })[0].Split(new char[1] { ' ' }).Last();
				}
				return "FAILED " + line.Split(new char[1] { ':' })[0].Split(new char[1] { ' ' }).Last();
			}

			internal bool <Save>b__62_0(FileInfo file)
			{
				if (!file.Name.EndsWith("-latest.md", StringComparison.Ordinal) && !file.Name.EndsWith("-previous.md", StringComparison.Ordinal))
				{
					return !file.Name.EndsWith("-previous-sent.md", StringComparison.Ordinal);
				}
				return false;
			}

			internal DateTime <Save>b__62_1(FileInfo file)
			{
				return file.LastWriteTimeUtc;
			}

			internal DateTime <Build>b__65_3(Error error)
			{
				return error.First;
			}

			internal string <Build>b__65_0(KeyValuePair<string, int> entry)
			{
				return entry.Key + " " + entry.Value;
			}

			internal string <Build>b__65_1(PluginInfo info)
			{
				return info.Metadata.GUID;
			}

			internal string <Build>b__65_2(PluginInfo info)
			{
				return info.Metadata.GUID + " " + info.Metadata.Version;
			}

			internal int <ErrorSummary>b__66_0(Error error)
			{
				return error.Count;
			}

			internal string <RelevantMods>b__69_0(string guid)
			{
				if (!Chainloader.PluginInfos.TryGetValue(guid, out var value))
				{
					return guid + " absent";
				}
				return guid + " " + value.Metadata.Version?.ToString() + " sha256:" + Hash(value.Location);
			}
		}

		private const string HelloRpc = "DeepNorthCompat.Hello.v1";

		private const string MarkerRpc = "DeepNorthCompat.Marker.v1";

		private const string RequestRpc = "DeepNorthCompat.ReportRequest.v1";

		private const string ReplyRpc = "DeepNorthCompat.ReportReply.v1";

		private const string ProbeRpc = "DeepNorthCompat.ReportProbe.v1";

		private const int ReplyLimit = 98304;

		private const int ReportsRetained = 30;

		private const int ErrorLimit = 40;

		private const int StartupLimit = 300;

		private static readonly Budget Full = new Budget
		{
			Findings = 60,
			Context = 12,
			Errors = 30,
			ErrorText = 2500,
			Recent = 60
		};

		private static readonly Budget Compact = new Budget
		{
			Findings = 20,
			Context = 6,
			Errors = 12,
			ErrorText = 1200,
			Recent = 20
		};

		private static readonly string[] Relevant = new string[16]
		{
			"DeepNorthCompat", "com.maxsch.valheim.MultiUserChest", "goldenrevolver.quick_stack_store", "Azumatt.AzuCraftyBoxes", "Azumatt.AzuAntiArthriticCrafting", "akuichi.ReforgedPotential", "MidnightsFX.ImpactfulSkills", "org.serverbound.valheim", "dev.ontrigger.vpo", "MidnightsFX.ValheimCommunityPatch",
			"akoozie.valheimtune", "xtav1m.BetterMap", "advize.CartographySkill", "odinplus.TeleportEverything", "ru.ivest.steadyframe", "ru.ivest.farlands"
		};

		private static readonly object gate = new object();

		private static readonly List<string> startup = new List<string>();

		private static readonly Dictionary<string, Error> errors = new Dictionary<string, Error>(StringComparer.Ordinal);

		private static readonly Dictionary<long, string> hellos = new Dictionary<long, string>();

		private static readonly Dictionary<long, (Vector3 Point, ZDOID Looked)> probes = new Dictionary<long, (Vector3, ZDOID)>();

		private static int droppedErrors;

		private static int writtenVersion = -1;

		private static string serverHello = "";

		private static long request;

		private static string? serverReport;

		private static string serverStatus = "";

		private static float nextAutoWrite;

		private static bool hinted;

		private static readonly Regex Footer = new Regex("<!-- DeepNorthCompat session (\\w+) world (-?\\d+) clean (yes|no) -->\\s*$");

		internal static Access ServerAccess = Access.Admins;

		private static string PluginVersion => typeof(Plugin).Assembly.GetName().Version.ToString(3);

		private static string ReportDirectory => Path.Combine(ChestDiagnostics.Directory ?? ".", "reports");

		internal static void Listen()
		{
			Logger.Listeners.Add((ILogListener)(object)new Listener());
		}

		internal unsafe static void Capture(string source, LogLevel level, string text)
		{
			//IL_0014: 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)
			if (ChestDiagnostics.Recording)
			{
				return;
			}
			bool flag = source == "DeepNorthCompat";
			bool flag2 = (level & 3) != 0 || text.IndexOf("Exception", StringComparison.Ordinal) >= 0 || text.IndexOf("Failed to find rpc method", StringComparison.Ordinal) >= 0;
			if (!flag && !flag2)
			{
				return;
			}
			DateTime utcNow = DateTime.UtcNow;
			string[] context = (flag2 ? ChestDiagnostics.Snapshot(5).Recent : Array.Empty<string>());
			lock (gate)
			{
				if (flag)
				{
					startup.Add(utcNow.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + " " + ((object)(*(LogLevel*)(&level))/*cast due to .constrained prefix*/).ToString() + " " + Clip(text, 700));
					if (startup.Count > 300)
					{
						startup.RemoveAt(100);
					}
				}
				if (!flag2)
				{
					return;
				}
				string[] array = text.Split(new char[1] { '\n' });
				string key = source + "|" + array[0].Trim() + "|" + array.Skip(1).FirstOrDefault((string line) => line.Trim().Length > 0)?.Trim();
				if (errors.TryGetValue(key, out Error value))
				{
					value.Count++;
					value.Last = utcNow;
					return;
				}
				if (errors.Count >= 40)
				{
					droppedErrors++;
					return;
				}
				errors[key] = new Error
				{
					Source = source,
					Level = ((object)(*(LogLevel*)(&level))/*cast due to .constrained prefix*/).ToString(),
					Text = text.TrimEnd(Array.Empty<char>()),
					Count = 1,
					First = utcNow,
					Last = utcNow,
					Context = context
				};
			}
			ChestDiagnostics.RecordText("log-error", source + " " + ((object)(*(LogLevel*)(&level))/*cast due to .constrained prefix*/).ToString() + ": " + Clip(text.Split(new char[1] { '\n' })[0], 300), Severity.Info);
		}

		internal static void RegisterCommands()
		{
			//IL_0033: 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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			object obj = <>c.<>9__33_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					if (args.Args.Length > 1 && string.Equals(args.Args[1], "last", StringComparison.OrdinalIgnoreCase))
					{
						SendPrevious(args.Context);
					}
					else
					{
						Collect(args.Context);
					}
				};
				<>c.<>9__33_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("dnc_report", "DeepNorthCompat: save a diagnostic report, send it to the server operator, and copy it with the server's report to the clipboard. Both describe the terrain, base areas and creatures where you stand. `dnc_report last` sends the report from your previous session instead.", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			object obj2 = <>c.<>9__33_1;
			if (obj2 == null)
			{
				ConsoleEvent val2 = delegate(ConsoleEventArgs args)
				{
					MarkCommand(args.Context, string.Join(" ", args.Args.Skip(1)));
				};
				<>c.<>9__33_1 = val2;
				obj2 = (object)val2;
			}
			new ConsoleCommand("dnc_mark", "DeepNorthCompat: mark a problem now and send it to the server operator, for example: dnc_mark chest showed old items", (ConsoleEvent)obj2, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}

		internal static void GameStarted()
		{
			ZRoutedRpc.instance.Register<ZPackage>("DeepNorthCompat.Hello.v1", (Action<long, ZPackage>)ReceiveHello);
			ZRoutedRpc.instance.Register<ZPackage>("DeepNorthCompat.Marker.v1", (Action<long, ZPackage>)ReceiveMarker);
			ZRoutedRpc.instance.Register<long>("DeepNorthCompat.ReportRequest.v1", (Action<long, long>)ReceiveRequest);
			ZRoutedRpc.instance.Register<ZPackage>("DeepNorthCompat.ReportReply.v1", (Action<long, ZPackage>)ReceiveReply);
			ZRoutedRpc.instance.Register<ZPackage>("DeepNorthCompat.ReportProbe.v1", (Action<long, ZPackage>)ReceiveProbe);
			lock (gate)
			{
				hellos.Clear();
				probes.Clear();
				serverHello = "";
			}
			ReportUpload.WorldStarted();
			ChestDiagnostics.Record("world-start", null, Environment(compact: true));
		}

		internal static void LocalPlayerSpawned(Player player)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			if (!((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer() && ZRoutedRpc.instance != null)
			{
				ZPackage val = new ZPackage();
				val.Write(PluginVersion);
				val.Write(player.GetPlayerName());
				val.Write(player.GetPlayerID());
				val.Write(PatchSummary());
				ZRoutedRpc.instance.InvokeRoutedRPC("DeepNorthCompat.Hello.v1", new object[1] { val });
			}
		}

		private static void ReceiveHello(long sender, ZPackage packet)
		{
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Expected O, but got Unknown
			string text = packet.ReadString();
			string text2 = packet.ReadString();
			long num = packet.ReadLong();
			string text3 = packet.ReadString();
			if (ZNet.instance.IsServer())
			{
				string text4 = "DeepNorthCompat " + text + "; player " + text2 + " (" + num + "); " + text3;
				lock (gate)
				{
					hellos[sender] = text4;
				}
				bool flag = text == PluginVersion;
				ChestDiagnostics.Record("peer-hello", null, "peer=" + sender + ";" + text4, (!flag) ? Severity.Problem : Severity.Info, flag ? "" : ("version-mismatch: server runs DeepNorthCompat " + PluginVersion));
				ZPackage val = new ZPackage();
				val.Write(PluginVersion);
				val.Write("server");
				val.Write(0L);
				val.Write(PatchSummary());
				val.Write(ReportUpload.Accepting);
				ZRoutedRpc.instance.InvokeRoutedRPC(sender, "DeepNorthCompat.Hello.v1", new object[1] { val });
			}
			else
			{
				lock (gate)
				{
					serverHello = "DeepNorthCompat " + text + "; " + text3;
				}
				bool flag2 = text == PluginVersion;
				bool flag3 = (ReportUpload.ServerAccepts = packet.GetPos() < packet.Size() && packet.ReadBool());
				ChestDiagnostics.Record("server-hello", null, "server=" + sender + ";version=" + text + ";accepts_reports=" + flag3 + ";" + text3, (!flag2) ? Severity.Problem : Severity.Info, flag2 ? "" : ("version-mismatch: this client runs DeepNorthCompat " + PluginVersion));
				if (flag3)
				{
					HintPrevious();
				}
			}
		}

		internal static void PeerDisconnecting(ZNetPeer peer)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer())
			{
				ChestDiagnostics.Record("peer-disconnected", null, "peer=" + peer.m_uid + ";player=" + peer.m_playerName);
				lock (gate)
				{
					hellos.Remove(peer.m_uid);
					probes.Remove(peer.m_uid);
				}
				ReportUpload.PeerGone(peer.m_uid);
			}
		}

		internal static void WorldShutdown()
		{
			ChestDiagnostics.Record("world-shutdown", null);
			SaveLatest(clean: true);
		}

		private static void SaveLatest(bool clean)
		{
			Save(Build(Full, includeServer: false) + "\n<!-- DeepNorthCompat session " + ChestDiagnostics.Session + " world " + CurrentWorld().ToString(CultureInfo.InvariantCulture) + " clean " + (clean ? "yes" : "no") + " -->\n", "latest");
		}

		private static long CurrentWorld()
		{
			if (!((Object)(object)ZNet.instance != (Object)null) || ZNet.World == null)
			{
				return 0L;
			}
			return ZNet.World.m_uid;
		}

		internal static void PreservePrevious()
		{
			if (ChestDiagnostics.Directory == null)
			{
				return;
			}
			string text = ReportPath("latest");
			string text2 = ReportPath("previous");
			string path = ReportPath("previous-sent");
			try
			{
				if (File.Exists(text))
				{
					if (File.Exists(text2))
					{
						File.Delete(text2);
					}
					if (File.Exists(path))
					{
						File.Delete(path);
					}
					File.Move(text, text2);
				}
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
			{
				CompatibilityInstaller.Error("Diagnostics could not keep the previous session's report: " + ex);
			}
		}

		private static string ReportPath(string suffix)
		{
			return Path.Combine(ReportDirectory, "DeepNorthCompat-report-" + ChestDiagnostics.Role + "-" + suffix + ".md");
		}

		internal static (string Path, string Text, long World, bool Clean, bool Sent)? Previous()
		{
			if (ChestDiagnostics.Directory == null)
			{
				return null;
			}
			(string, bool)[] array = new(string, bool)[2]
			{
				(ReportPath("previous"), false),
				(ReportPath("previous-sent"), true)
			};
			for (int i = 0; i < array.Length; i++)
			{
				var (text, item) = array[i];
				try
				{
					if (!File.Exists(text))
					{
						continue;
					}
					string text2 = File.ReadAllText(text);
					Match match = Footer.Match(text2);
					return match.Success ? (text, text2, long.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture), match.Groups[3].Value == "yes", item) : (text, text2, 0L, true, item);
				}
				catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is OverflowException)
				{
					return null;
				}
			}
			return null;
		}

		internal static void MarkPreviousSent(string path)
		{
			try
			{
				if (path == ReportPath("previous") && File.Exists(path))
				{
					File.Move(path, ReportPath("previous-sent"));
				}
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
			{
				CompatibilityInstaller.Error("Diagnostics could not mark the previous session's report as sent: " + ex);
			}
		}

		private static void HintPrevious()
		{
			if (hinted || !ReportUpload.Send)
			{
				return;
			}
			(string, string, long, bool, bool)? tuple = Previous();
			if (tuple.HasValue && !tuple.Value.Item5 && !tuple.Value.Item4 && tuple.Value.Item3 != 0L && tuple.Value.Item3 == CurrentWorld())
			{
				hinted = true;
				if ((Object)(object)Chat.instance != (Object)null)
				{
					((Terminal)Chat.instance).AddString("DeepNorthCompat: your last session in this world ended unexpectedly. Type /dnc_report last to send its report to the server.");
				}
			}
		}

		private static void SendPrevious(Terminal context)
		{
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			if (!ChestDiagnostics.Enabled)
			{
				context.AddString("DeepNorthCompat diagnostics are disabled in its config.");
				return;
			}
			if (!ReportUpload.Send)
			{
				context.AddString("DeepNorthCompat: sending reports is off in this client's config (Send reports to server).");
				return;
			}
			if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || ZNet.instance.GetServerPeer() == null)
			{
				context.AddString("DeepNorthCompat: join the server first, then type /dnc_report last.");
				return;
			}
			(string, string, long, bool, bool)? tuple = Previous();
			if (!tuple.HasValue)
			{
				context.AddString("DeepNorthCompat: no report from a previous session was found.");
				return;
			}
			if (tuple.Value.Item5)
			{
				context.AddString("DeepNorthCompat: the previous session's report was already sent to the server.");
				return;
			}
			if (tuple.Value.Item3 != 0L && tuple.Value.Item3 != CurrentWorld())
			{
				context.AddString("DeepNorthCompat: the previous session's report is from a different world. Join that world to send it.");
				return;
			}
			string text = tuple.Value.Item2;
			ReportUpload.Submit(context, "last", "", (bool _) => text, null, ZDOID.None, tuple.Value.Item1);
		}

		internal static void Prewarm()
		{
			if (!ChestDiagnostics.Enabled)
			{
				return;
			}
			try
			{
				Build(Full, includeServer: false);
			}
			catch (Exception ex)
			{
				ChestDiagnostics.RecordText("diagnostics-hook-error", "DiagnosticReport.Prewarm: " + ex, Severity.Info);
			}
		}

		internal static void Tick()
		{
			if (!ChestDiagnostics.Enabled)
			{
				return;
			}
			ReportUpload.Tick();
			try
			{
				ItemLedger.Tick();
			}
			catch (Exception ex)
			{
				ChestDiagnostics.RecordText("diagnostics-hook-error", "ItemLedger.Tick: " + ex, Severity.Info);
			}
			if (nextAutoWrite == 0f)
			{
				nextAutoWrite = Time.realtimeSinceStartup + 300f;
			}
			if (!(Time.realtimeSinceStartup < nextAutoWrite))
			{
				nextAutoWrite = Time.realtimeSinceStartup + 300f;
				if (ChestDiagnostics.Version != writtenVersion)
				{
					writtenVersion = ChestDiagnostics.Version;
					SaveLatest((Object)(object)ZNet.instance == (Object)null);
				}
			}
		}

		private static void MarkCommand(Terminal context, string note)
		{
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			if (!ChestDiagnostics.Enabled)
			{
				context.AddString("DeepNorthCompat diagnostics are disabled in its config.");
				return;
			}
			if (note.Trim().Length == 0)
			{
				note = "(no note)";
			}
			string text = (((Object)(object)Player.m_localPlayer != (Object)null) ? Player.m_localPlayer.GetPlayerName() : "local");
			ChestDiagnostics.Mark(text, note);
			string text2 = ReportUpload.Redact(note);
			if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer() && ZRoutedRpc.instance != null)
			{
				ZPackage val = new ZPackage();
				val.Write(text);
				val.Write(text2);
				ZRoutedRpc.instance.InvokeRoutedRPC("DeepNorthCompat.Marker.v1", new object[1] { val });
			}
			context.AddString("DeepNorthCompat: marked \"" + note + "\". Reproduce if you can, then type /dnc_report.");
			ReportUpload.Submit(context, "marker", text2, (bool compact) => Snapshot(compact, null), null, ZDOID.None);
		}

		private static void ReceiveMarker(long sender, ZPackage packet)
		{
			string text = packet.ReadString();
			ChestDiagnostics.Mark(note: packet.ReadString(), who: text + " (peer " + sender + ")");
		}

		private static void Collect(Terminal context)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			if (!ChestDiagnostics.Enabled)
			{
				context.AddString("DeepNorthCompat diagnostics are disabled in its config.");
				return;
			}
			ZRoutedRpc val = (((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer() && ZNet.instance.GetServerPeer() != null) ? ZRoutedRpc.instance : null);
			string[] array = null;
			Vector3? point = null;
			ZDOID val2 = ZDOID.None;
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && (Object)(object)ZNet.instance != (Object)null)
			{
				Vector3 position = ((Component)localPlayer).transform.position;
				Character hoverCreature = localPlayer.GetHoverCreature();
				val2 = (((Object)(object)hoverCreature == (Object)null) ? ZDOID.None : hoverCreature.GetZDOID());
				point = position;
				array = WorldProbe.Capture(position, val2);
				if (val != null)
				{
					ZPackage val3 = new ZPackage();
					val3.Write(position);
					val3.Write(val2);
					val.InvokeRoutedRPC("DeepNorthCompat.ReportProbe.v1", new object[1] { val3 });
				}
			}
			string[] captured = array;
			ReportUpload.Submit(context, "report", "", (bool compact) => Snapshot(compact, captured), point, val2);
			if (val != null)
			{
				lock (gate)
				{
					request = DateTime.UtcNow.Ticks;
					serverReport = null;
					serverStatus = "no reply within 10 seconds";
				}
				val.InvokeRoutedRPC("DeepNorthCompat.ReportRequest.v1", new object[1] { request });
				context.AddString("DeepNorthCompat: collecting the server's report…");
				((MonoBehaviour)Plugin.Instance).StartCoroutine(Finish(context, request, array));
			}
			else
			{
				lock (gate)
				{
					serverReport = null;
					serverStatus = (((Object)(object)ZNet.instance == (Object)null) ? "not in a world" : "this peer is the server");
				}
				Deliver(context, array);
			}
		}

		private static void ReceiveProbe(long sender, ZPackage packet)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			try
			{
				Vector3 val = packet.ReadVector3();
				ZDOID item = packet.ReadZDOID();
				float f = val.x + val.y + val.z;
				if (float.IsNaN(f) || float.IsInfinity(f))
				{
					return;
				}
				lock (gate)
				{
					probes[sender] = (val, item);
				}
			}
			catch (Exception ex)
			{
				ChestDiagnostics.RecordText("diagnostics-hook-error", "ReceiveProbe: " + ex, Severity.Info);
			}
		}

		private static IEnumerator Finish(Terminal context, long id, string[]? probe)
		{
			float until = Time.realtimeSinceStartup + 10f;
			while (Time.realtimeSinceStartup < until)
			{
				lock (gate)
				{
					if (request != id || serverReport != null)
					{
						break;
					}
					goto IL_005c;
				}
				IL_005c:
				yield return null;
			}
			Deliver(context, probe);
		}

		private static void Deliver(Terminal context, string[]? probe)
		{
			string text = Build(Full, includeServer: true, probe);
			string text2 = Save(text, "combined");
			GUIUtility.systemCopyBuffer = text;
			context.AddString("DeepNorthCompat: report copied to the clipboard (" + (text.Length / 1024 + 1) + " KB)." + ((text2 == null) ? "" : (" Saved to " + text2.Replace('\\', '/'))));
		}

		private static void ReceiveRequest(long sender, long id)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Expected O, but got Unknown
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer())
			{
				ZNetPeer peer = ZNet.instance.GetPeer(sender);
				bool flag = ServerAccess == Access.Everyone || (ServerAccess == Access.Admins && peer != null && ZNet.instance.IsAdmin(peer.m_socket.GetHostName()));
				bool flag2;
				(Vector3, ZDOID) value;
				lock (gate)
				{
					flag2 = probes.TryGetValue(sender, out value);
					probes.Remove(sender);
				}
				string[] probe = ((flag2 && flag) ? WorldProbe.Capture(value.Item1, value.Item2) : null);
				string text = Build(Full, includeServer: false, probe);
				Save(text, "requested");
				if (Encoding.UTF8.GetByteCount(text) > 98304)
				{
					text = Build(Compact, includeServer: false, probe);
				}
				if (Encoding.UTF8.GetByteCount(text) > 98304)
				{
					text = text.Substring(0, 49152) + "\n\n(truncated to fit the network limit)\n";
				}
				ChestDiagnostics.Record("report-request", null, "peer=" + sender + ";player=" + peer?.m_playerName + ";allowed=" + flag + ";access=" + ServerAccess);
				ZPackage val = new ZPackage();
				val.Write(id);
				val.Write(flag);
				val.Write(flag ? text : ("The server saved its report in " + ReportDirectory + ". It sends reports only to " + ((ServerAccess == Access.Admins) ? "admins (adminlist.txt)" : "nobody") + ". Change `Server report access` in the server's BepInEx/config/DeepNorthCompat.cfg to allow this."));
				ZRoutedRpc.instance.InvokeRoutedRPC(sender, "DeepNorthCompat.ReportReply.v1", new object[1] { val });
			}
		}

		private static void ReceiveReply(long sender, ZPackage packet)
		{
			long num = packet.ReadLong();
			bool flag = packet.ReadBool();
			string text = packet.ReadString();
			lock (gate)
			{
				if (num == request)
				{
					if (flag)
					{
						serverReport = text;
						serverStatus = "received";
					}
					else
					{
						serverReport = "";
						serverStatus = "refused: " + text;
					}
				}
			}
		}

		private static string PatchSummary()
		{
			lock (gate)
			{
				return string.Join(", ", from line in startup
					select line.Substring(Math.Min(line.Length, 9)) into line
					where line.Contains(": APPLIED") || line.Contains("NOT APPLIED")
					select (!line.Contains("NOT APPLIED")) ? line.Split(new char[1] { ':' })[0].Split(new char[1] { ' ' }).Last() : ("FAILED " + line.Split(new char[1] { ':' })[0].Split(new char[1] { ' ' }).Last()));
			}
		}

		internal static string? Save(string text, string kind)
		{
			if (ChestDiagnostics.Directory == null)
			{
				return null;
			}
			try
			{
				Directory.CreateDirectory(ReportDirectory);
				string role = ChestDiagnostics.Role;
				string path = ((kind == "latest") ? ("DeepNorthCompat-report-" + role + "-latest.md") : ("DeepNorthCompat-report-" + role + "-" + DateTime.UtcNow.ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture) + "-" + kind + ".md"));
				string text2 = Path.Combine(ReportDirectory, path);
				File.WriteAllText(text2, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				foreach (FileInfo item in (from file in new DirectoryInfo(ReportDirectory).GetFiles("DeepNorthCompat-report-*.md")
					where !file.Name.EndsWith("-latest.md", StringComparison.Ordinal) && !file.Name.EndsWith("-previous.md", StringComparison.Ordinal) && !file.Name.EndsWith("-previous-sent.md", StringComparison.Ordinal)
					orderby file.LastWriteTimeUtc descending
					select file).Skip(30))
				{
					item.Delete();
				}
				return text2;
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
			{
				CompatibilityInstaller.Error("Diagnostics could not save a report: " + ex);
				return null;
			}
		}

		internal static string Build(bool includeServer)
		{
			return Build(Full, includeServer);
		}

		internal static string Snapshot(bool compact, string[]? probe)
		{
			return Build(compact ? Compact : Full, includeServer: false, probe);
		}

		private static string Build(Budget budget, bool includeServer, string[]? probe = null)
		{
			(ChestDiagnostics.Finding[], int, ChestDiagnostics.Marker[], string[], string[], KeyValuePair<string, int>[], string[], bool) tuple = ChestDiagnostics.Snapshot(budget.Recent);
			StringBuilder stringBuilder = new StringBuilder();
			string role = ChestDiagnostics.Role;
			DateTime utcNow = DateTime.UtcNow;
			stringBuilder.Append("# DeepNorthCompat diagnostic report (").Append(role).AppendLine(")")
				.AppendLine();
			stringBuilder.AppendLine("Times are UTC. Chest IDs match across peers; owner and peer values are network session IDs. Detailed event logs: `" + (ChestDiagnostics.Directory ?? "disabled") + "`.").AppendLine();
			stringBuilder.AppendLine("Event lines read `time [severity] event [operation] chest=<id> owner=self|none|<peer> rev=<data revision>/<loaded revision> use=<local>/<replicated> payload=<item data hash> items=<name:quality:world level=count> | details`. A chest shows current contents when both revisions match. Finding blocks list that chest's earlier events, then the finding after `>`.").AppendLine();
			stringBuilder.AppendLine("## Overview").AppendLine();
			string[] obj = new string[9]
			{
				"- Generated ",
				utcNow.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
				"; session ",
				ChestDiagnostics.Session,
				" started ",
				null,
				null,
				null,
				null
			};
			DateTime started = ChestDiagnostics.Started;
			obj[5] = started.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
			obj[6] = " (";
			obj[7] = ((int)(utcNow - ChestDiagnostics.Started).TotalMinutes).ToString();
			obj[8] = " min ago).";
			stringBuilder.AppendLine(string.Concat(obj));
			stringBuilder.AppendLine("- " + Environment(compact: false));
			lock (gate)
			{
				if (role == "client")
				{
					stringBuilder.AppendLine("- Server: " + ((serverHello.Length == 0) ? "no DeepNorthCompat reply this session. The server may lack DeepNorthCompat 1.1.3 or later." : serverHello));
				}
			}
			stringBuilder.AppendLine("- Findings: " + ChestDiagnostics.Problems + " problems, " + ChestDiagnostics.Warnings + " warnings" + ((tuple.Item2 > 0) ? (" (" + tuple.Item2 + " middle findings omitted)") : "") + ". Errors: " + ErrorSummary() + ". Markers: " + tuple.Item3.Length + ".");
			if (tuple.Item7.Length != 0)
			{
				stringBuilder.AppendLine("- Diagnostics faults: " + string.Join("; ", tuple.Item7));
			}
			stringBuilder.AppendLine();
			if (probe != null)
			{
				stringBuilder.AppendLine("## World probe").AppendLine();
				stringBuilder.AppendLine("What this peer holds at the position the report was requested from. The client and server reports each carry this block for the same point, so compare them line by line. `ground` is the terrain collider that creatures and spawn checks use. `generated` is the height before any edit, `stored` is the saved terrain edit and `applied` is how much of it this peer's terrain shows. `LIMITED` marks a peer that applies less than it stores, which happens when its terrain height limit is lower than the one used to make the edit. `owner` is `self`, `server`, `none` or a peer ID. A creature line ends with `BELOW GROUND` when the creature is more than 1 m under this peer's terrain. In the synced-object census, `settled` means the next vanilla sync would change nothing, and `skipped` counts sync calls the patch avoided.").AppendLine();
				Block(stringBuilder, probe);
			}
			if (tuple.Item3.Length != 0)
			{
				stringBuilder.AppendLine("## Player markers").AppendLine();
				ChestDiagnostics.Marker[] item = tuple.Item3;
				foreach (ChestDiagnostics.Marker marker in item)
				{
					stringBuilder.AppendLine("### " + marker.Utc.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + " " + marker.Who + ": " + marker.Note).AppendLine();
					if (marker.Activity.Length != 0)
					{
						stringBuilder.AppendLine("Item movements in the 20 minutes before:").AppendLine();
						Block(stringBuilder, marker.Activity.Skip(Math.Max(0, marker.Activity.Length - budget.Recent)));
						stringBuilder.AppendLine("Events in the 90 seconds before:").AppendLine();
					}
					Block(stringBuilder, marker.Context.Skip(Math.Max(0, marker.Context.Length - budget.Recent)));
				}
			}
			stringBuilder.AppendLine("## Problems and warnings").AppendLine();
			if (tuple.Item1.Length == 0)
			{
				stringBuilder.AppendLine("None recorded.").AppendLine();
			}
			ChestDiagnostics.Finding[] array = tuple.Item1.Skip(Math.Max(0, tuple.Item1.Length - budget.Findings)).ToArray();
			if (array.Length < tuple.Item1.Length)
			{
				stringBuilder.AppendLine("Showing the newest " + array.Length + " of " + tuple.Item1.Length + ".").AppendLine();
			}
			ChestDiagnostics.Finding[] array2 = array;
			foreach (ChestDiagnostics.Finding finding in array2)
			{
				stringBuilder.AppendLine("### " + finding.Severity.ToString().ToUpperInvariant() + " " + finding.Kind + " at " + finding.Utc.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)).AppendLine();
				Block(stringBuilder, finding.Context.Skip(Math.Max(0, finding.Context.Length - budget.Context)).Concat(new string[1] { "> " + finding.Line }).Concat((finding.Extra.Length == 0) ? ((IEnumerable<string>)Array.Empty<string>()) : ((IEnumerable<string>)new string[1] { Clip(finding.Extra, budget.ErrorText) })));
			}
			stringBuilder.AppendLine("## Errors and exceptions from all mods").AppendLine();
			Error[] array3;
			lock (gate)
			{
				array3 = errors.Values.OrderBy((Error error) => error.First).ToArray();
			}
			if (array3.Length == 0)
			{
				stringBuilder.AppendLine("None recorded.").AppendLine();
			}
			foreach (Error item2 in array3.Skip(Math.Max(0, array3.Length - budget.Errors)))
			{
				stringBuilder.AppendLine("### " + item2.Level + " from " + ((item2.Source.Length == 0) ? "unknown" : item2.Source) + ", " + item2.Count + "x, first " + item2.First.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + ", last " + item2.Last.ToString("HH:mm:ss", CultureInfo.InvariantCulture)).AppendLine();
				Block(stringBuilder, new string[1] { Clip(item2.Text, budget.ErrorText) });
				if (item2.Context.Length != 0)
				{
					stringBuilder.AppendLine("Events before the first occurrence:").AppendLine();
					Block(stringBuilder, item2.Context);
				}
			}
			if (role == "server" && (Object)(object)ZNet.instance != (Object)null)
			{
				stringBuilder.AppendLine("## Connected peers").AppendLine();
				lock (gate)
				{
					foreach (ZNetPeer peer in ZNet.instance.GetPeers())
					{
						stringBuilder.AppendLine("- " + peer.m_uid + " " + peer.m_playerName + ": " + (hellos.TryGetValue(peer.m_uid, out string value) ? value : "no DeepNorthCompat hello. This peer lacks DeepNorthCompat 1.1.3 or later."));
					}
				}
				stringBuilder.AppendLine();
			}
			if (tuple.Item5.Length != 0)
			{
				stringBuilder.AppendLine("## Item movements").AppendLine();
				stringBuilder.AppendLine("Quick Stack, restock and crafting results and other changes to the player's items, newest last. `operation-settled` nets a burst of presses after MultiUserChest returns what a chest could not hold; `unaccounted` must be `none`.").AppendLine();
				Block(stringBuilder, tuple.Item5);
			}
			stringBuilder.AppendLine("## Recent events").AppendLine();
			Block(stringBuilder, tuple.Item4);
			stringBuilder.AppendLine("## Event counts").AppendLine();
			stringBuilder.AppendLine(string.Join(", ", tuple.Item6.Select((KeyValuePair<string, int> entry) => entry.Key + " " + entry.Value))).AppendLine();
			stringBuilder.AppendLine("## DeepNorthCompat log").AppendLine();
			lock (gate)
			{
				Block(stringBuilder, startup.ToArray());
			}
			stringBuilder.AppendLine("## Settings and mods").AppendLine();
			stringBuilder.AppendLine("- " + Settings());
			stringBuilder.AppendLine("- Relevant mods: " + RelevantMods());
			stringBuilder.AppendLine("- All plugins: " + string.Join(", ", from info in Chainloader.PluginInfos.Values.OrderBy<PluginInfo, string>((PluginInfo info) => info.Metadata.GUID, StringComparer.OrdinalIgnoreCase)
				select info.Metadata.GUID + " " + info.Metadata.Version));
			stringBuilder.AppendLine();
			if (includeServer)
			{
				string text;
				string value2;
				lock (gate)
				{
					text = serverStatus;
					value2 = serverReport;
				}
				stringBuilder.AppendLine("---").AppendLine();
				if (!string.IsNullOrEmpty(value2))
				{
					stringBuilder.Append(value2);
				}
				else
				{
					stringBuilder.AppendLine("# Server report unavailable").AppendLine().AppendLine("Status: " + text + ". The server writes `BepInEx/DeepNorthCompat/diagnostics/reports/DeepNorthCompat-report-server-latest.md` every five minutes and on shutdown; attach that file instead.");
				}
			}
			return stringBuilder.ToString();
		}

		private static string ErrorSummary()
		{
			lock (gate)
			{
				return errors.Count + " unique, " + errors.Values.Sum((Error error) => error.Count) + " total" + ((droppedErrors > 0) ? (", " + droppedErrors + " more not kept") : "");
			}
		}

		private static string Environment(bool compact)
		{
			string text = "DeepNorthCompat " + PluginVersion + " " + ChestDiagnostics.Role + "; Valheim " + Version.GetVersionString(false) + "; peer " + ((ZDOMan.instance == null) ? "none" : ZDOMan.GetSessionID().ToString(CultureInfo.InvariantCulture));
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				text = text + "; player " + Player.m_localPlayer.GetPlayerName() + " (" + Player.m_localPlayer.GetPlayerID() + ")";
			}
			if (compact)
			{
				return text;
			}
			return text + "; game assembly " + Hash(typeof(ZNet).Assembly.Location) + "; " + SystemInfo.operatingSystem;
		}

		private static string Settings()
		{
			return "Crafty range " + ChestCraftPatch.Range.ToString(CultureInfo.InvariantCulture) + " m, leave one " + ChestCraftPatch.LeavingOne + "; crafting handoff " + (ChestCraftPatch.Active ? "active" : "inactive") + "; Quick Stack range " + ChestSyncPatch.StackRange.ToString(CultureInfo.InvariantCulture) + " m, restock range " + ChestSyncPatch.RestockRange.ToString(CultureInfo.InvariantCulture) + " m; server report access " + ServerAccess.ToString() + "; tracked chests " + ChestRegistry.Count;
		}

		private static string RelevantMods()
		{
			PluginInfo value;
			return string.Join(", ", Relevant.Select((string guid) => (!Chainloader.PluginInfos.TryGetValue(guid, out value)) ? (guid + " absent") : (guid + " " + value.Metadata.Version?.ToString() + " sha256:" + Hash(value.Location))));
		}

		private static string Hash(string path)
		{
			try
			{
				return Guard.Sha256(path).Substring(0, 16);
			}
			catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is ArgumentException)
			{
				return "unreadable";
			}
		}

		private static void Block(StringBuilder b, IEnumerable<string> lines)
		{
			b.AppendLine("```text");
			foreach (string line in lines)
			{
				b.AppendLine(line.Replace("```", "'''"));
			}
			b.AppendLine("```").AppendLine();
		}

		private static string Clip(string value, int length)
		{
			if (value.Length > length)
			{
				return value.Substring(0, length) + "…";
			}
			return value;
		}

		internal static void Clear()
		{
			lock (gate)
			{
				errors.Clear();
				droppedErrors = 0;
				hellos.Clear();
				probes.Clear();
				serverHello = "";
				serverReport = null;
				serverStatus = "";
			}
			hinted = false;
			ReportUpload.Clear();
		}
	}
	internal static class ILMatch
	{
		private static readonly OpCode[] shortLoads = new OpCode[4]
		{
			OpCodes.Ldloc_0,
			OpCodes.Ldloc_1,
			OpCodes.Ldloc_2,
			OpCodes.Ldloc_3
		};

		private static readonly OpCode[] shortStores = new OpCode[4]
		{
			OpCodes.Stloc_0,
			OpCodes.Stloc_1,
			OpCodes.Stloc_2,
			OpCodes.Stloc_3
		};

		internal static int Site(List<CodeInstruction> code, Func<int, bool> matches)
		{
			int num = Unique(code, matches);
			if (num < 0 || !Plain(code[num]))
			{
				return -1;
			}
			return num;
		}

		internal static int Unique(List<CodeInstruction> code, Func<int, bool> matches)
		{
			int[] array = Enumerable.Range(0, code.Count).Where(matches).ToArray();
			if (array.Length != 1)
			{
				return -1;
			}
			return array[0];
		}

		internal static bool Plain(CodeInstruction code)
		{
			if (code.labels.Count == 0)
			{
				return code.blocks.Count == 0;
			}
			return false;
		}

		internal static bool Shape(List<CodeInstruction> code, int start, params Func<CodeInstruction, bool>[] pattern)
		{
			if (start >= 0 && start + pattern.Length <= code.Count)
			{
				return Enumerable.Range(0, pattern.Length).All((int i) => pattern[i](code[start + i]));
			}
			return false;
		}

		internal static bool Locals(MethodBase method, int count, params (int Index, Type Type)[] expected)
		{
			IList<LocalVariableInfo> locals = method.GetMethodBody().LocalVariables;
			if (locals.Count == count)
			{
				return expected.All(((int Index, Type Type) local) => locals[local.Index].LocalType == local.Type);
			}
			return false;
		}

		internal static Func<CodeInstruction, bool> Is(OpCode opcode)
		{
			return (CodeInstruction code) => code.opcode == opcode;
		}

		internal static Func<CodeInstruction, bool> Loads(FieldInfo field)
		{
			return (CodeInstruction code) => CodeInstructionExtensions.LoadsField(code, field, false);
		}

		internal static Func<CodeInstruction, bool> Calls(MethodInfo method)
		{
			return (CodeInstruction code) => CodeInstructionExtensions.Calls(code, method);
		}

		internal static Func<CodeInstruction, bool> IsLoad(int index)
		{
			return (CodeInstruction code) => (index < shortLoads.Length && code.opcode == shortLoads[index]) || ((code.opcode == OpCodes.Ldloc || code.opcode == OpCodes.Ldloc_S) && Local(code) == index);
		}

		internal static Func<CodeInstruction, bool> IsStore(int index)
		{
			return (CodeInstruction code) => (index < shortStores.Length && code.opcode == shortStores[index]) || ((code.opcode == OpCodes.Stloc || code.opcode == OpCodes.Stloc_S) && Local(code) == index);
		}

		private static int Local(CodeInstruction code)
		{
			if (!(code.operand is LocalVariableInfo localVariableInfo))
			{
				return Convert.ToInt32(code.operand);
			}
			return localVariableInfo.LocalIndex;
		}

		internal static void Lost(ref bool enabled, string group, string reason)
		{
			if (enabled)
			{
				enabled = false;
				CompatibilityInstaller.Error(group + ": NO LONGER APPLIED; " + reason + "; vendor behavior retained.");
			}
		}
	}
	internal static class ItemLedger
	{
		private sealed class Burst
		{
			internal float Last;

			internal int Count;

			internal DateTime Started;

			internal readonly List<string> Operations = new List<string>();

			internal Dictionary<string, int> Player;

			internal readonly Dictionary<ZDOID, (Container Chest, Dictionary<string, int> Before)> Chests = new Dictionary<ZDOID, (Container, Dictionary<string, int>)>();

			internal Dictionary<string, (ZDOID Chest, float Distance)> Beyond = new Dictionary<string, (ZDOID, float)>();
		}

		private const float PlayerQuiet = 0.5f;

		private const float BurstQuiet = 3f;

		private const float BurstLimit = 15f;

		private static readonly FieldInfo? openChest = AccessTools.Field(typeof(InventoryGui), "m_currentContainer");

		private static Burst? burst;

		private static Inventory? watched;

		private static Dictionary<string, int> baseline = new Dictionary<string, int>(StringComparer.Ordinal);

		private static float changed = -1f;

		internal static void InventoryChanged(Inventory inventory)
		{
			if (watched != null && inventory == watched)
			{
				changed = Time.unscaledTime;
			}
		}

		internal static Container[] BeginOperation(string name, Player player, IEnumerable<Container> chests, IEnumerable<(Container Chest, float Distance)> outside)
		{
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			if (player != Player.m_localPlayer)
			{
				return Array.Empty<Container>();
			}
			Watch(((Humanoid)player).GetInventory());
			Flush();
			if (burst == null)
			{
				burst = new Burst
				{
					Started = DateTime.UtcNow,
					Player = Counts(((Humanoid)player).GetInventory())
				};
			}
			burst.Last