Decompiled source of ValheimAdmin v0.4.1

plugins/ValheimAdmin.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using ValheimAdmin.Shared;
using ValheimAdmin.Web;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Valheim Admin")]
[assembly: AssemblyProduct("Valheim Admin")]
[assembly: AssemblyFileVersion("0.4.1.0")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.4.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ValheimAdmin
{
	[BepInPlugin("neocor.ValheimAdmin", "Valheim Admin", "0.4.1")]
	public class BepInExPlugin : BaseUnityPlugin
	{
		public const string pluginGuid = "neocor.ValheimAdmin";

		public const string pluginName = "Valheim Admin";

		public const string pluginVersion = "0.4.1";

		private static ManualLogSource logger;

		public static ConfigEntry<int> AgentPort;

		public static ConfigEntry<string> AgentSecretFile;

		public static ConfigEntry<bool> AllowServerCommands;

		public static ConfigEntry<bool> AllowRestore;

		public static ConfigEntry<bool> SharePins;

		public static ConfigEntry<bool> IsDebug;

		public static ConfigEntry<bool> WebEnabled;

		public static ConfigEntry<int> WebPort;

		public static ConfigEntry<string> WebBind;

		public static ConfigEntry<string> WebAdminPassword;

		public static ConfigEntry<string> WebAdminPasswordHash;

		public static ConfigEntry<string> WebLanguage;

		public static ConfigEntry<string> WebDataDir;

		public static ConfigEntry<int> WebKeepAllDays;

		public static ConfigEntry<int> WebKeepDailyDays;

		public static ConfigEntry<string> WebIgnoreDataKeys;

		public static ConfigEntry<bool> MapEnabled;

		public static ConfigEntry<int> MapTextureSize;

		public static ConfigEntry<float> MapPixelSize;

		public static ConfigEntry<bool> MapDrawInBackground;

		public static ConfigEntry<bool> MapPublicFog;

		public static ConfigEntry<string> MapPublicPlayers;

		public static ConfigEntry<bool> MapPublicPortals;

		public static ConfigEntry<bool> MapPublicLocations;

		public static ConfigEntry<bool> MapPublicSpawners;

		public static BepInExPlugin Instance { get; private set; }

		public static void Log(string str)
		{
			if (logger != null)
			{
				logger.LogInfo((object)str);
			}
		}

		public static void Warn(string str)
		{
			if (logger != null)
			{
				logger.LogWarning((object)str);
			}
		}

		public static void Dbgl(string str)
		{
			if (logger != null && IsDebug != null && IsDebug.Value)
			{
				logger.LogInfo((object)str);
			}
		}

		public void Awake()
		{
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Expected O, but got Unknown
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Expected O, but got Unknown
			//IL_03b5: Unknown result type (might be due to invalid IL or missing references)
			logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			AgentPort = ((BaseUnityPlugin)this).Config.Bind<int>("Server", "AgentPort", 0, "Port of the Valheim Admin agent on 127.0.0.1. Only needed when the server is started without the agent; the agent passes it through the VA_AGENT_PORT environment variable. 0 = disabled.");
			AgentSecretFile = ((BaseUnityPlugin)this).Config.Bind<string>("Server", "AgentSecretFile", "", "File holding the agent's bridge secret (data\\bridge.secret next to the agent). Only needed together with AgentPort.");
			AllowServerCommands = ((BaseUnityPlugin)this).Config.Bind<bool>("Client", "AllowServerCommands", true, "Let the server admin run console commands (god, fly, spawn, ...) on this character through the admin panel.");
			AllowRestore = ((BaseUnityPlugin)this).Config.Bind<bool>("Client", "AllowRestore", true, "Let the server admin restore items and skills of this character from a snapshot.");
			SharePins = ((BaseUnityPlugin)this).Config.Bind<bool>("Client", "SharePins", true, "Show the pins of your in-game map to the server admin on the admin panel's map (never on the public map).");
			IsDebug = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Debug", false, "Verbose logging.");
			WebEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Web", "Enabled", true, "Standalone mode: when the server runs without the Valheim Admin agent (rented hosts, Linux), serve the web panel from the game itself. Ignored when the agent is present; it serves the panel then.");
			WebPort = ((BaseUnityPlugin)this).Config.Bind<int>("Web", "Port", 8095, "TCP port of the web panel in standalone mode. Your host must allow incoming connections to it.");
			WebBind = ((BaseUnityPlugin)this).Config.Bind<string>("Web", "Bind", "*", "Address to listen on: * for all, or one IP address.");
			WebAdminPassword = ((BaseUnityPlugin)this).Config.Bind<string>("Web", "AdminPassword", "", "Put a new admin password here; on start (or the next sign-in) it is replaced by a hash in AdminPasswordHash. When neither is set, a random password is written to the BepInEx log.");
			WebAdminPasswordHash = ((BaseUnityPlugin)this).Config.Bind<string>("Web", "AdminPasswordHash", "", "Hash of the admin password (PBKDF2). Clear it and set AdminPassword to change the password.");
			WebLanguage = ((BaseUnityPlugin)this).Config.Bind<string>("Web", "Language", "en", new ConfigDescription("Language of event log texts.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[2] { "en", "ru" }), Array.Empty<object>()));
			WebDataDir = ((BaseUnityPlugin)this).Config.Bind<string>("Web", "DataDir", "", "Folder for the event log, snapshots and icons in standalone mode. Empty = BepInEx/config/ValheimAdmin.");
			WebKeepAllDays = ((BaseUnityPlugin)this).Config.Bind<int>("Web", "SnapshotKeepAllDays", 3, "Keep every snapshot this many days (standalone mode).");
			WebKeepDailyDays = ((BaseUnityPlugin)this).Config.Bind<int>("Web", "SnapshotKeepDailyDays", 60, "Then keep one snapshot per day for this many days (standalone mode).");
			WebIgnoreDataKeys = ((BaseUnityPlugin)this).Config.Bind<string>("Web", "IgnoreDataKeys", "", "Comma-separated item custom data keys (or prefix*) that Compare ignores (standalone mode), for mods that change item data during play.");
			MapEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Map", "Enabled", true, "Draw the world map on the dedicated server for the web panel. The admin always sees the whole map, also with the nomap world key.");
			MapTextureSize = ((BaseUnityPlugin)this).Config.Bind<int>("Map", "TextureSize", 2048, "Map picture size in pixels (power of two). With PixelSize 12 the default covers the vanilla world; raise it for worlds enlarged by mods.");
			MapPixelSize = ((BaseUnityPlugin)this).Config.Bind<float>("Map", "PixelSize", 12f, "Metres per map pixel (the game's minimap uses 12).");
			MapDrawInBackground = ((BaseUnityPlugin)this).Config.Bind<bool>("Map", "DrawInBackground", true, "Draw the map on a background thread. Turn off if a world generation mod misbehaves; it is then drawn a few milliseconds per frame.");
			MapPublicFog = ((BaseUnityPlugin)this).Config.Bind<bool>("Map", "PublicFog", true, "Starting value, the panel's public map settings override it. The public map (no login) shows only areas that players have been near. The admin sees everything.");
			MapPublicPlayers = ((BaseUnityPlugin)this).Config.Bind<string>("Map", "PublicPlayers", "respect", new ConfigDescription("Starting value, the panel's public map settings override it. Players on the public map: respect = only those with \"Visible on map\" on in the game, all, none.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "respect", "all", "none" }), Array.Empty<object>()));
			MapPublicPortals = ((BaseUnityPlugin)this).Config.Bind<bool>("Map", "PublicPortals", false, "Starting value, the panel's public map settings override it. Show portals (with their tags) on the public map, in explored areas.");
			MapPublicLocations = ((BaseUnityPlugin)this).Config.Bind<bool>("Map", "PublicLocations", false, "Starting value, the panel's public map settings override it. Show the world's locations (boss altars, dungeons, traders, runestones, camps, ...) on the public map, in explored areas.");
			MapPublicSpawners = ((BaseUnityPlugin)this).Config.Bind<bool>("Map", "PublicSpawners", false, "Starting value, the panel's public map settings override it. Show mob spawners (greydwarf nests, bone piles, ...) on the public map, in explored areas.");
			new Harmony("neocor.ValheimAdmin").PatchAll(typeof(BepInExPlugin).Assembly);
			AgentLink.Start();
			Log("Ready.");
		}

		public void Update()
		{
			MainThread.Pump();
			ServerRole.Update();
			DropCleaner.Update();
			CreatureCleaner.Update();
		}

		public void OnDestroy()
		{
			AgentLink.Stop();
			StandaloneServer.Stop();
		}
	}
	public static class ClientRole
	{
		[HarmonyPatch(typeof(Player), "OnSpawned")]
		private static class Player_OnSpawned_Patch
		{
			private static void Postfix(Player __instance)
			{
				if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && IsClient && ZRoutedRpc.instance != null)
				{
					PlayerProfile playerProfile = Game.instance.GetPlayerProfile();
					ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "VA_Hello", new object[3]
					{
						"0.4.1",
						playerProfile.GetPlayerID(),
						__instance.GetPlayerName()
					});
				}
			}
		}

		[HarmonyPatch(typeof(Player), "OnDeath")]
		private static class Player_OnDeath_Patch
		{
			private static void Prefix(Player __instance)
			{
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
				//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || !IsClient || ZRoutedRpc.instance == null)
				{
					return;
				}
				try
				{
					HitData lastHit = ((Character)__instance).m_lastHit;
					Character val = ((lastHit != null) ? lastHit.GetAttacker() : null);
					Vector3 position = ((Component)__instance).transform.position;
					Dictionary<string, object> dictionary = new Dictionary<string, object>();
					dictionary.Add("player", __instance.GetPlayerName());
					dictionary.Add("cause", (lastHit != null) ? ((object)Unsafe.As<HitType, HitType>(ref lastHit.m_hitType)/*cast due to .constrained prefix*/).ToString() : "Unknown");
					dictionary.Add("attacker", ((Object)(object)val != (Object)null) ? val.GetHoverName() : null);
					dictionary.Add("attackerIsPlayer", (Object)(object)val != (Object)null && val.IsPlayer());
					dictionary.Add("pos", new double[3]
					{
						Math.Round(position.x),
						Math.Round(position.y),
						Math.Round(position.z)
					});
					string text = Json.Serialize(dictionary);
					ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "VA_Death", new object[1] { text });
				}
				catch (Exception ex)
				{
					BepInExPlugin.Warn("Death report failed: " + ex.Message);
				}
			}
		}

		private static bool IsClient
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return !ZNet.instance.IsServer();
				}
				return false;
			}
		}

		public static void Register()
		{
			ZRoutedRpc.instance.Register<long, string>("VA_Cmd", (Action<long, long, string>)RPC_Command);
			ZRoutedRpc.instance.Register<long, ZPackage>("VA_Run", (Action<long, long, ZPackage>)RPC_Run);
			ZRoutedRpc.instance.Register<long, string, int, int>("VA_Give", (Method<long, string, int, int>)RPC_Give);
			ZRoutedRpc.instance.Register<long, string>("VA_SnapReq", (Action<long, long, string>)RPC_SnapshotRequest);
			ZRoutedRpc.instance.Register<long, ZPackage>("VA_Restore", (Action<long, long, ZPackage>)RPC_Restore);
			ZRoutedRpc.instance.Register<string>("VA_Chat", (Action<long, string>)RPC_Chat);
			ZRoutedRpc.instance.Register<long, ZPackage>("VA_Icons", (Action<long, long, ZPackage>)RPC_Icons);
			ZRoutedRpc.instance.Register<long>("VA_Pins", (Action<long, long>)RPC_Pins);
		}

		private static bool FromServer(long sender)
		{
			if (IsClient)
			{
				return sender == ZRoutedRpc.instance.GetServerPeerID();
			}
			return false;
		}

		private static void Reply(long requestId, bool ok, object data)
		{
			string json = ((data is string text && !ok) ? text : Json.Serialize(data));
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "VA_Reply", new object[3]
			{
				requestId,
				ok,
				Rpc.Pack(json)
			});
		}

		private static Player LivePlayer(long requestId)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				Reply(requestId, ok: false, "The character is not spawned");
				return null;
			}
			if (((Character)localPlayer).IsDead())
			{
				Reply(requestId, ok: false, "The character is dead");
				return null;
			}
			return localPlayer;
		}

		private static void RPC_Command(long sender, long requestId, string command)
		{
			if (FromServer(sender))
			{
				RunCommand(requestId, command, confirmCheats: false);
			}
		}

		private static void RPC_Run(long sender, long requestId, ZPackage payload)
		{
			if (FromServer(sender))
			{
				Dictionary<string, object> d;
				try
				{
					d = Json.ParseObject(Rpc.Unpack(payload));
				}
				catch (Exception ex)
				{
					Reply(requestId, ok: false, "Bad request: " + ex.Message);
					return;
				}
				RunCommand(requestId, d.Str("line", ""), d.Bool("confirmCheats"));
			}
		}

		private static void RunCommand(long requestId, string line, bool confirmCheats)
		{
			if (!BepInExPlugin.AllowServerCommands.Value)
			{
				Reply(requestId, ok: false, "The player disabled remote commands in the Valheim Admin config");
				return;
			}
			if ((Object)(object)Console.instance == (Object)null)
			{
				Reply(requestId, ok: false, "The game console is not available");
				return;
			}
			ConsoleCommand val = ConsoleRunner.Find(line);
			if (val == null)
			{
				Reply(requestId, ok: false, "Unknown console command on the player's game: " + ConsoleRunner.FirstWord(line));
				return;
			}
			if (!ConsoleRunner.IsValidHere((Terminal)(object)Console.instance, val))
			{
				if (val.OnlyServer || val.RemoteCommand)
				{
					Reply(requestId, ok: true, new Dictionary<string, object> { { "runOnServer", true } });
				}
				else
				{
					Reply(requestId, ok: false, "'" + val.Command + "' can't run on the player's game right now");
				}
				return;
			}
			if (val.IsCheat && !confirmCheats && !Achievements.IsCheatedAtAll())
			{
				Reply(requestId, ok: true, new Dictionary<string, object>
				{
					{ "needsConfirm", true },
					{ "command", val.Command }
				});
				return;
			}
			BepInExPlugin.Log("Admin command: " + line);
			try
			{
				ConsoleRunner.Result result = ConsoleRunner.Run((Terminal)(object)Console.instance, line, confirmCheats);
				Reply(requestId, ok: true, new Dictionary<string, object> { { "output", result.Output } });
			}
			catch (Exception ex)
			{
				BepInExPlugin.Warn("Admin command failed: " + ex);
				Reply(requestId, ok: false, ex.Message);
			}
		}

		private static void RPC_Give(long sender, long requestId, string prefab, int count, int quality)
		{
			if (!FromServer(sender))
			{
				return;
			}
			if (!BepInExPlugin.AllowRestore.Value)
			{
				Reply(requestId, ok: false, "The player disabled restores");
				return;
			}
			Player val = LivePlayer(requestId);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefab);
			ItemDrop val2 = (((Object)(object)itemPrefab != (Object)null) ? itemPrefab.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val2 == (Object)null)
			{
				Reply(requestId, ok: false, "Unknown item: " + prefab);
				return;
			}
			Restorer.Report report = new Restorer.Report();
			int val3 = Math.Max(1, val2.m_itemData.m_shared.m_maxStackSize);
			int num = count;
			while (num > 0)
			{
				int num2 = Math.Min(num, val3);
				num -= num2;
				ItemData val4 = val2.m_itemData.Clone();
				val4.m_dropPrefab = itemPrefab;
				val4.m_stack = num2;
				val4.m_quality = quality;
				val4.m_durability = val4.GetMaxDurability();
				Restorer.AddOrDrop(val, val4, report);
			}
			((Character)val).Message((MessageType)2, Texts.Given(Localization.instance.Localize(val2.m_itemData.m_shared.m_name), count), 0, (Sprite)null, false);
			Reply(requestId, ok: true, report.ToJson());
		}

		private static void RPC_SnapshotRequest(long sender, long requestId, string trigger)
		{
			if (!FromServer(sender))
			{
				return;
			}
			Player val = LivePlayer(requestId);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			try
			{
				Reply(requestId, ok: true, Snapshot.Build(val, trigger));
			}
			catch (Exception ex)
			{
				BepInExPlugin.Warn("Snapshot failed: " + ex);
				Reply(requestId, ok: false, "Snapshot failed: " + ex.Message);
			}
		}

		private static void RPC_Restore(long sender, long requestId, ZPackage payload)
		{
			if (!FromServer(sender))
			{
				return;
			}
			if (!BepInExPlugin.AllowRestore.Value)
			{
				Reply(requestId, ok: false, "The player disabled restores");
				return;
			}
			Player val = LivePlayer(requestId);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			try
			{
				Dictionary<string, object> request = Json.ParseObject(Rpc.Unpack(payload));
				Reply(requestId, ok: true, Restorer.Apply(val, request).ToJson());
			}
			catch (Exception ex)
			{
				BepInExPlugin.Warn("Restore failed: " + ex);
				Reply(requestId, ok: false, "Restore failed: " + ex.Message);
			}
		}

		private static void RPC_Icons(long sender, long requestId, ZPackage payload)
		{
			if (!FromServer(sender))
			{
				return;
			}
			try
			{
				Dictionary<string, object> d = Json.ParseObject(Rpc.Unpack(payload));
				Reply(requestId, ok: true, Icons.Render(d.List("items")));
			}
			catch (Exception ex)
			{
				BepInExPlugin.Warn("Icon rendering failed: " + ex);
				Reply(requestId, ok: false, "Icon rendering failed: " + ex.Message);
			}
		}

		private static void RPC_Pins(long sender, long requestId)
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Expected I4, but got Unknown
			if (!FromServer(sender))
			{
				return;
			}
			if (!BepInExPlugin.SharePins.Value)
			{
				Reply(requestId, ok: true, new Dictionary<string, object> { { "disabled", true } });
				return;
			}
			if ((Object)(object)Minimap.instance == (Object)null)
			{
				Reply(requestId, ok: false, "The map is not available");
				return;
			}
			List<object> list = new List<object>();
			foreach (PinData pin in Minimap.instance.m_pins)
			{
				if (pin.m_save && pin.m_ownerID == 0L)
				{
					list.Add(new Dictionary<string, object>
					{
						{
							"name",
							pin.m_name ?? ""
						},
						{
							"type",
							(int)pin.m_type
						},
						{
							"x",
							Math.Round(pin.m_pos.x, 1)
						},
						{
							"z",
							Math.Round(pin.m_pos.z, 1)
						},
						{ "checked", pin.m_checked }
					});
				}
			}
			Reply(requestId, ok: true, new Dictionary<string, object> { { "pins", list } });
		}

		private static void RPC_Chat(long sender, string text)
		{
			if (FromServer(sender) && !((Object)(object)Chat.instance == (Object)null))
			{
				((Terminal)Chat.instance).AddString("<color=orange>" + Texts.ServerTag + "</color>", text, (Type)2, false);
				Chat.instance.m_hideTimer = 0f;
			}
		}
	}
	public static class Icons
	{
		public const int Size = 64;

		public static Dictionary<string, object> Render(List<object> items)
		{
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			foreach (object item in items ?? new List<object>())
			{
				Dictionary<string, object> d = item as Dictionary<string, object>;
				string text = d.Str("prefab");
				int variant = d.Int("variant");
				if (string.IsNullOrEmpty(text))
				{
					continue;
				}
				string text2 = text + "|" + variant;
				if (dictionary.ContainsKey(text2))
				{
					continue;
				}
				try
				{
					string text3 = Render(text, variant);
					if (text3 != null)
					{
						dictionary[text2] = text3;
					}
				}
				catch (Exception ex)
				{
					BepInExPlugin.Dbgl("Icon of " + text2 + " failed: " + ex.Message);
				}
			}
			return dictionary;
		}

		private static string Render(string prefabName, int variant)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Expected O, but got Unknown
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab(prefabName) : null);
			Sprite[] array = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>() : null)?.m_itemData?.m_shared?.m_icons;
			if (array == null || array.Length == 0)
			{
				return null;
			}
			Sprite val2 = array[Mathf.Clamp(variant, 0, array.Length - 1)];
			if ((Object)(object)val2 == (Object)null || (Object)(object)val2.texture == (Object)null)
			{
				return null;
			}
			Texture texture = (Texture)(object)val2.texture;
			Rect textureRect = val2.textureRect;
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor(((Rect)(ref textureRect)).width / (float)texture.width, ((Rect)(ref textureRect)).height / (float)texture.height);
			Vector2 val4 = default(Vector2);
			((Vector2)(ref val4))..ctor(((Rect)(ref textureRect)).x / (float)texture.width, ((Rect)(ref textureRect)).y / (float)texture.height);
			RenderTexture active = RenderTexture.active;
			RenderTexture temporary = RenderTexture.GetTemporary(64, 64, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
			Texture2D val5 = null;
			try
			{
				RenderTexture.active = temporary;
				GL.Clear(true, true, Color.clear);
				Graphics.Blit(texture, temporary, val3, val4);
				RenderTexture.active = temporary;
				val5 = new Texture2D(64, 64, (TextureFormat)4, false);
				val5.ReadPixels(new Rect(0f, 0f, 64f, 64f), 0, 0);
				val5.Apply();
				return Convert.ToBase64String(ImageConversion.EncodeToPNG(val5));
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
				if ((Object)(object)val5 != (Object)null)
				{
					Object.Destroy((Object)(object)val5);
				}
			}
		}
	}
	public static class Snapshot
	{
		public const int FormatVersion = 2;

		public unsafe static Dictionary<string, object> Build(Player player, string trigger)
		{
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_0387: Unknown result type (might be due to invalid IL or missing references)
			//IL_0397: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Expected I4, but got Unknown
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			Inventory inventory = ((Humanoid)player).GetInventory();
			List<object> list = new List<object>();
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				AddItem(list, player, allItem, null);
			}
			List<object> list2 = new List<object>();
			foreach (ExtraInventories.Found item in ExtraInventories.Find(player))
			{
				list2.Add(new Dictionary<string, object>
				{
					{ "key", item.Key },
					{
						"w",
						item.Inventory.GetWidth()
					},
					{
						"h",
						item.Inventory.GetHeight()
					}
				});
				foreach (ItemData allItem2 in item.Inventory.GetAllItems())
				{
					AddItem(list, player, allItem2, item.Key);
				}
			}
			List<object> list3 = new List<object>();
			foreach (Skill skill2 in ((Character)player).GetSkills().GetSkillList())
			{
				if (skill2?.m_info != null)
				{
					SkillType skill = skill2.m_info.m_skill;
					list3.Add(new Dictionary<string, object>
					{
						{
							"type",
							(int)skill
						},
						{
							"name",
							((object)(*(SkillType*)(&skill))/*cast due to .constrained prefix*/).ToString()
						},
						{
							"displayName",
							SkillName(skill)
						},
						{ "level", skill2.m_level },
						{ "acc", skill2.m_accumulator }
					});
				}
			}
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			if (player.m_customData != null)
			{
				foreach (KeyValuePair<string, string> customDatum in player.m_customData)
				{
					dictionary[customDatum.Key] = customDatum.Value;
				}
			}
			Vector3 position = ((Component)player).transform.position;
			Dictionary<string, object> dictionary2 = new Dictionary<string, object>();
			dictionary2.Add("v", 2);
			dictionary2.Add("trigger", trigger);
			dictionary2.Add("name", player.GetPlayerName());
			dictionary2.Add("characterId", Game.instance.GetPlayerProfile().GetPlayerID());
			dictionary2.Add("takenAt", DateTime.UtcNow.ToString("o"));
			dictionary2.Add("itemVersion", ItemBytes.Version);
			dictionary2.Add("inventory", new Dictionary<string, object>
			{
				{
					"w",
					inventory.GetWidth()
				},
				{
					"h",
					inventory.GetHeight()
				}
			});
			dictionary2.Add("containers", list2);
			dictionary2.Add("items", list);
			dictionary2.Add("skills", list3);
			dictionary2.Add("playerData", dictionary);
			dictionary2.Add("health", Math.Round(((Character)player).GetHealth(), 1));
			dictionary2.Add("pos", new double[3]
			{
				Math.Round(position.x),
				Math.Round(position.y),
				Math.Round(position.z)
			});
			return dictionary2;
		}

		public unsafe static string SkillName(SkillType type)
		{
			try
			{
				return Localization.instance.Localize("$skill_" + ((object)(*(SkillType*)(&type))/*cast due to .constrained prefix*/).ToString().ToLower());
			}
			catch
			{
				return ((object)(*(SkillType*)(&type))/*cast due to .constrained prefix*/).ToString();
			}
		}

		private static void AddItem(List<object> items, Player player, ItemData item, string container)
		{
			GameObject val = (((Object)(object)item.m_dropPrefab != (Object)null) ? item.m_dropPrefab : ItemBytes.FindPrefab(item));
			if ((Object)(object)val == (Object)null)
			{
				BepInExPlugin.Dbgl("Snapshot skips an item without a prefab: " + item.m_shared?.m_name);
			}
			else
			{
				items.Add(Item(player, item, val, container));
			}
		}

		private static Dictionary<string, object> Item(Player player, ItemData item, GameObject prefab, string container)
		{
			string value = null;
			try
			{
				value = Localization.instance.Localize(item.GetTooltip(-1));
			}
			catch (Exception ex)
			{
				BepInExPlugin.Dbgl("Tooltip of " + ((Object)prefab).name + " failed: " + ex.Message);
			}
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			if (item.m_customData != null)
			{
				foreach (KeyValuePair<string, string> customDatum in item.m_customData)
				{
					dictionary[customDatum.Key] = customDatum.Value;
				}
			}
			string value2 = null;
			try
			{
				value2 = ItemBytes.Save(item, prefab);
			}
			catch (Exception ex2)
			{
				BepInExPlugin.Warn("Saving " + ((Object)prefab).name + " failed: " + ex2.Message);
			}
			Dictionary<string, object> dictionary2 = new Dictionary<string, object>
			{
				{
					"prefab",
					((Object)prefab).name
				},
				{
					"token",
					item.m_shared.m_name
				},
				{
					"label",
					Localization.instance.Localize(item.m_shared.m_name)
				},
				{ "tooltip", value },
				{
					"itemType",
					((object)Unsafe.As<ItemType, ItemType>(ref item.m_shared.m_itemType)/*cast due to .constrained prefix*/).ToString()
				},
				{
					"maxStack",
					item.m_shared.m_maxStackSize
				},
				{ "stack", item.m_stack },
				{ "durability", item.m_durability },
				{
					"maxDurability",
					item.GetMaxDurability()
				},
				{
					"x",
					item.m_gridPos.x
				},
				{
					"y",
					item.m_gridPos.y
				},
				{
					"equipped",
					((Humanoid)player).IsItemEquiped(item)
				},
				{ "quality", item.m_quality },
				{ "variant", item.m_variant },
				{ "crafterId", item.m_crafterID },
				{ "crafterName", item.m_crafterName },
				{ "worldLevel", item.m_worldLevel },
				{ "pickedUp", item.m_pickedUp },
				{ "cheated", item.m_cheated },
				{ "data", dictionary },
				{ "raw", value2 }
			};
			if (container != null)
			{
				dictionary2["container"] = container;
			}
			return dictionary2;
		}
	}
	public static class ItemBytes
	{
		private static int version;

		public static int Version
		{
			get
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Expected O, but got Unknown
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				if (version == 0)
				{
					ZPackage val = new ZPackage();
					new Inventory("ValheimAdmin", (Sprite)null, 1, 1).Save(val);
					val.SetPos(0);
					version = val.ReadInt();
				}
				return version;
			}
		}

		public static string Save(ItemData item, GameObject prefab)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			GameObject dropPrefab = item.m_dropPrefab;
			item.m_dropPrefab = prefab;
			try
			{
				ZPackage val = new ZPackage();
				item.Save(val);
				return Convert.ToBase64String(val.GetArray());
			}
			finally
			{
				item.m_dropPrefab = dropPrefab;
			}
		}

		public static ItemData Load(string raw, int itemVersion)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: 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_0060: Expected O, but got Unknown
			byte[] array = Convert.FromBase64String(raw);
			ZPackage val = new ZPackage();
			val.Write(itemVersion);
			val.Write((ushort)1);
			byte[] array2 = val.GetArray();
			byte[] array3 = new byte[array2.Length + array.Length];
			Buffer.BlockCopy(array2, 0, array3, 0, array2.Length);
			Buffer.BlockCopy(array, 0, array3, array2.Length, array.Length);
			Inventory val2 = new Inventory("ValheimAdmin restore", (Sprite)null, 8, 4);
			val2.Load(new ZPackage(array3));
			return val2.GetAllItems().FirstOrDefault();
		}

		public static GameObject FindPrefab(ItemData item)
		{
			string text = item.m_shared?.m_name;
			if (string.IsNullOrEmpty(text) || (Object)(object)ObjectDB.instance == (Object)null)
			{
				return null;
			}
			foreach (GameObject item2 in ObjectDB.instance.m_items)
			{
				ItemDrop val = (((Object)(object)item2 != (Object)null) ? item2.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val != (Object)null && val.m_itemData.m_shared.m_name == text)
				{
					return item2;
				}
			}
			return null;
		}
	}
	public static class ExtraInventories
	{
		public sealed class Found
		{
			public string Key;

			public Inventory Inventory;
		}

		public static List<Found> Find(Player player)
		{
			List<Found> list = new List<Found>();
			HashSet<Inventory> hashSet = new HashSet<Inventory> { ((Humanoid)player).GetInventory() };
			Assembly assembly = typeof(Player).Assembly;
			Component[] components = ((Component)player).GetComponents<Component>();
			foreach (Component val in components)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Type type = ((object)val).GetType();
				if (type.Assembly == assembly || type.Assembly == typeof(Component).Assembly)
				{
					continue;
				}
				try
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					foreach (FieldInfo fieldInfo in fields)
					{
						if (!(fieldInfo.FieldType != typeof(Inventory)))
						{
							object? value = fieldInfo.GetValue(val);
							Inventory val2 = (Inventory)((value is Inventory) ? value : null);
							if (val2 != null && hashSet.Add(val2))
							{
								list.Add(new Found
								{
									Key = type.FullName + "." + fieldInfo.Name,
									Inventory = val2
								});
							}
						}
					}
				}
				catch (Exception ex)
				{
					BepInExPlugin.Dbgl("Looking for inventories on " + type.FullName + " failed: " + ex.Message);
				}
			}
			return list;
		}
	}
	public static class Restorer
	{
		public class Report
		{
			public int Added;

			public int Dropped;

			public int Skills;

			public readonly List<object> Failed = new List<object>();

			public Dictionary<string, object> ToJson()
			{
				return new Dictionary<string, object>
				{
					{ "added", Added },
					{ "dropped", Dropped },
					{ "skills", Skills },
					{ "failed", Failed }
				};
			}
		}

		public static Report Apply(Player player, Dictionary<string, object> request)
		{
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			Report report = new Report();
			bool flag = request.Str("mode", "add") == "replace";
			int itemVersion = request.Int("itemVersion");
			Inventory inventory = ((Humanoid)player).GetInventory();
			Dictionary<string, Inventory> dictionary = ExtraInventories.Find(player).ToDictionary((ExtraInventories.Found f) => f.Key, (ExtraInventories.Found f) => f.Inventory);
			if (flag)
			{
				((Humanoid)player).UnequipAllItems();
				inventory.RemoveAll();
				foreach (object item in request.List("containers") ?? new List<object>())
				{
					string text = (item as Dictionary<string, object>).Str("key");
					if (text != null && dictionary.TryGetValue(text, out var value))
					{
						value.RemoveAll();
					}
				}
			}
			List<ItemData> list = new List<ItemData>();
			foreach (object item2 in request.List("items") ?? new List<object>())
			{
				Dictionary<string, object> dictionary2 = item2 as Dictionary<string, object>;
				ItemData val = null;
				try
				{
					val = Make(dictionary2, itemVersion);
				}
				catch (Exception ex)
				{
					BepInExPlugin.Warn("Rebuilding " + dictionary2.Str("prefab") + " failed: " + ex);
				}
				if (val == null)
				{
					report.Failed.Add(new Dictionary<string, object>
					{
						{
							"prefab",
							dictionary2.Str("prefab")
						},
						{ "reason", "unknown prefab (is its mod installed?)" }
					});
					continue;
				}
				bool flag2 = dictionary2.Bool("equipped");
				val.m_equipped = false;
				Inventory value2 = inventory;
				string text2 = dictionary2.Str("container");
				if (text2 != null && (!flag || !dictionary.TryGetValue(text2, out value2)))
				{
					value2 = inventory;
				}
				bool flag3 = false;
				if (flag && (text2 == null || value2 != inventory))
				{
					int num = dictionary2.Int("x", -1);
					int num2 = dictionary2.Int("y", -1);
					if (num >= 0 && num2 >= 0 && num < value2.GetWidth() && num2 < value2.GetHeight() && value2.GetItemAt(num, num2) == null)
					{
						flag3 = value2.AddItem(val, new Vector2i(num, num2));
					}
					if (flag3)
					{
						report.Added++;
						if (flag2 && value2 == inventory)
						{
							list.Add(val);
						}
					}
				}
				if (!flag3)
				{
					AddOrDrop(player, val, report);
					if (flag && flag2 && inventory.ContainsItem(val))
					{
						list.Add(val);
					}
				}
			}
			foreach (ItemData item3 in list)
			{
				((Humanoid)player).EquipItem(item3, false);
			}
			string text3 = request.Str("skillMode", "none");
			if (text3 != "none")
			{
				RestoreSkills(player, request.List("skills"), text3 == "set", report);
			}
			((Character)player).Message((MessageType)2, Texts.Restored(report.Added + report.Dropped, report.Dropped, report.Skills), 0, (Sprite)null, false);
			BepInExPlugin.Log("Restore: added " + report.Added + ", dropped " + report.Dropped + ", skills " + report.Skills + ", failed " + report.Failed.Count);
			return report;
		}

		public static ItemData Make(Dictionary<string, object> j, int itemVersion)
		{
			if (j == null)
			{
				return null;
			}
			string text = j.Str("raw");
			if (!string.IsNullOrEmpty(text) && itemVersion > 0)
			{
				ItemData val = ItemBytes.Load(text, itemVersion);
				if (val == null)
				{
					return null;
				}
				int num = j.Int("stack", val.m_stack);
				if (num > 0 && num < val.m_stack)
				{
					val.m_stack = num;
				}
				return val;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(j.Str("prefab", ""));
			ItemDrop val2 = (((Object)(object)itemPrefab != (Object)null) ? itemPrefab.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val2 == (Object)null)
			{
				return null;
			}
			ItemData val3 = val2.m_itemData.Clone();
			val3.m_dropPrefab = itemPrefab;
			val3.m_stack = Math.Max(1, j.Int("stack", 1));
			val3.m_quality = Math.Max(1, j.Int("quality", 1));
			val3.m_variant = j.Int("variant");
			val3.m_durability = (float)j.Double("durability", val3.GetMaxDurability());
			val3.m_crafterID = j.Long("crafterId", 0L);
			val3.m_crafterName = j.Str("crafterName", "");
			val3.m_worldLevel = j.Int("worldLevel");
			val3.m_pickedUp = j.Bool("pickedUp", def: true);
			val3.m_cheated = j.Bool("cheated");
			val3.m_equipped = false;
			val3.m_customData = new Dictionary<string, string>();
			Dictionary<string, object> dictionary = j.Obj("data");
			if (dictionary != null)
			{
				foreach (KeyValuePair<string, object> item in dictionary)
				{
					val3.m_customData[item.Key] = (item.Value as string) ?? Json.Serialize(item.Value);
				}
			}
			return val3;
		}

		public static void AddOrDrop(Player player, ItemData item, Report report)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory.CanAddItem(item, item.m_stack) && inventory.AddItem(item))
			{
				report.Added++;
				return;
			}
			Transform transform = ((Component)player).transform;
			ItemDrop.DropItem(item, item.m_stack, transform.position + transform.forward + Vector3.up, transform.rotation);
			report.Dropped++;
		}

		private static void RestoreSkills(Player player, List<object> skills, bool exact, Report report)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			if (skills == null)
			{
				return;
			}
			Skills skills2 = ((Character)player).GetSkills();
			foreach (object skill2 in skills)
			{
				if (!(skill2 is Dictionary<string, object> d))
				{
					continue;
				}
				SkillType val = (SkillType)d.Int("type");
				try
				{
					if (skills2.GetSkillDef(val) == null)
					{
						report.Failed.Add(new Dictionary<string, object>
						{
							{
								"skill",
								d.Str("displayName") ?? d.Str("name")
							},
							{ "reason", "skill not available (is its mod installed?)" }
						});
						continue;
					}
					Skill skill = skills2.GetSkill(val);
					float num = (float)d.Double("level");
					if (exact || !(num <= skill.m_level))
					{
						skill.m_level = num;
						skill.m_accumulator = (float)d.Double("acc");
						report.Skills++;
					}
				}
				catch (Exception ex)
				{
					report.Failed.Add(new Dictionary<string, object>
					{
						{
							"skill",
							d.Str("displayName") ?? d.Str("name")
						},
						{ "reason", ex.Message }
					});
				}
			}
		}
	}
	public static class Texts
	{
		private static bool Russian
		{
			get
			{
				try
				{
					return Localization.instance != null && Localization.instance.GetSelectedLanguage() == "Russian";
				}
				catch
				{
					return false;
				}
			}
		}

		public static string ServerTag
		{
			get
			{
				if (!Russian)
				{
					return "[Server]";
				}
				return "[Сервер]";
			}
		}

		public static string Given(string item, int count)
		{
			return (Russian ? "Администратор выдал: " : "The admin gave you: ") + item + " x" + count;
		}

		public static string Restored(int items, int dropped, int skills)
		{
			string text = (Russian ? "Администратор восстановил персонажа: предметов " : "The admin restored your character: items ") + items;
			if (dropped > 0)
			{
				text += (Russian ? (" (" + dropped + " на земле)") : (" (" + dropped + " on the ground)"));
			}
			if (skills > 0)
			{
				text = text + (Russian ? ", навыков " : ", skills ") + skills;
			}
			return text;
		}
	}
	public static class ConsoleRunner
	{
		public sealed class Result
		{
			public readonly List<string> Output = new List<string>();
		}

		[HarmonyPatch(typeof(Terminal), "AddString", new Type[] { typeof(string) })]
		private static class Terminal_AddString_Patch
		{
			private static void Postfix(string text)
			{
				capture?.Add(Plain(text));
			}
		}

		[HarmonyPatch(typeof(Terminal), "IsCheatsEnabled")]
		private static class Terminal_IsCheatsEnabled_Patch
		{
			private static bool Prefix(ref bool __result)
			{
				if (!forceCheats)
				{
					return true;
				}
				__result = true;
				return false;
			}
		}

		[HarmonyPatch(typeof(Achievements), "IsCheatedAtAll")]
		private static class Achievements_IsCheatedAtAll_Patch
		{
			private static bool Prefix(ref bool __result)
			{
				if (!bypassCheatMark)
				{
					return true;
				}
				__result = true;
				return false;
			}
		}

		private static List<string> capture;

		private static bool forceCheats;

		private static bool bypassCheatMark;

		public static ConsoleCommand Find(string line)
		{
			string text = FirstWord(line);
			if (text.Length == 0)
			{
				return null;
			}
			if (!Terminal.commands.TryGetValue(text.ToLowerInvariant(), out var value))
			{
				return null;
			}
			return value;
		}

		public static string FirstWord(string line)
		{
			line = (line ?? "").Trim();
			int num = line.IndexOf(' ');
			if (num >= 0)
			{
				return line.Substring(0, num);
			}
			return line;
		}

		public static bool IsValidHere(Terminal context, ConsoleCommand cmd)
		{
			bool flag = forceCheats;
			forceCheats = true;
			try
			{
				return cmd.IsValid(context, true);
			}
			finally
			{
				forceCheats = flag;
			}
		}

		public static Result Run(Terminal context, string line, bool allowCheatMark)
		{
			Result result = new Result();
			bool cheat = Terminal.m_cheat;
			capture = result.Output;
			forceCheats = true;
			bypassCheatMark = allowCheatMark;
			try
			{
				Terminal.m_cheat = true;
				context.TryRunCommand(line.Trim(), false, true);
				return result;
			}
			finally
			{
				capture = null;
				forceCheats = false;
				bypassCheatMark = false;
				Terminal.m_cheat = cheat;
			}
		}

		public static List<object> List()
		{
			return ((IEnumerable<ConsoleCommand>)(from c in Terminal.commands.Values
				where c != null && !c.IsSecret
				group c by c.Command.ToLowerInvariant() into g
				select g.First()).OrderBy<ConsoleCommand, string>((ConsoleCommand c) => c.Command, StringComparer.OrdinalIgnoreCase)).Select((Func<ConsoleCommand, object>)((ConsoleCommand c) => new Dictionary<string, object>
			{
				{ "name", c.Command },
				{
					"description",
					c.Description ?? ""
				},
				{ "cheat", c.IsCheat },
				{ "network", c.IsNetwork },
				{ "serverOnly", c.OnlyServer }
			})).ToList();
		}

		public static string Plain(string text)
		{
			if (string.IsNullOrEmpty(text) || text.IndexOf('<') < 0)
			{
				return text ?? "";
			}
			StringBuilder stringBuilder = new StringBuilder(text.Length);
			int num = 0;
			while (num < text.Length)
			{
				if (text[num] == '<')
				{
					int num2 = text.IndexOf('>', num);
					if (num2 > num && num2 - num < 40 && IsTag(text.Substring(num + 1, num2 - num - 1)))
					{
						num = num2 + 1;
						continue;
					}
				}
				stringBuilder.Append(text[num++]);
			}
			return stringBuilder.ToString();
		}

		private static bool IsTag(string inner)
		{
			string text = inner.TrimStart(new char[1] { '/' }).Split('=', ' ')[0].ToLowerInvariant();
			switch (text)
			{
			default:
				return text == "voffset";
			case "color":
			case "b":
			case "i":
			case "size":
			case "u":
			case "s":
			case "sprite":
				return true;
			}
		}
	}
	public static class Rpc
	{
		public const string Hello = "VA_Hello";

		public const string Reply = "VA_Reply";

		public const string Death = "VA_Death";

		public const string Command = "VA_Cmd";

		public const string Run = "VA_Run";

		public const string Give = "VA_Give";

		public const string SnapshotRequest = "VA_SnapReq";

		public const string Restore = "VA_Restore";

		public const string Chat = "VA_Chat";

		public const string Icons = "VA_Icons";

		public const string Pins = "VA_Pins";

		public static ZPackage Pack(string json)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(Deflate(Encoding.UTF8.GetBytes(json ?? "")));
			return val;
		}

		public static string Unpack(ZPackage pkg)
		{
			return Encoding.UTF8.GetString(Inflate(pkg.ReadByteArray()));
		}

		public static byte[] Deflate(byte[] data)
		{
			using MemoryStream memoryStream = new MemoryStream();
			using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
			{
				deflateStream.Write(data, 0, data.Length);
			}
			return memoryStream.ToArray();
		}

		public static byte[] Inflate(byte[] data)
		{
			using MemoryStream stream = new MemoryStream(data);
			using DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress);
			using MemoryStream memoryStream = new MemoryStream();
			deflateStream.CopyTo(memoryStream);
			return memoryStream.ToArray();
		}
	}
	public static class MainThread
	{
		private static readonly Queue<Action> queue = new Queue<Action>();

		public static void Post(Action action)
		{
			lock (queue)
			{
				queue.Enqueue(action);
			}
		}

		public static void Pump()
		{
			while (true)
			{
				Action action;
				lock (queue)
				{
					if (queue.Count == 0)
					{
						break;
					}
					action = queue.Dequeue();
				}
				try
				{
					action();
				}
				catch (Exception ex)
				{
					BepInExPlugin.Warn("Queued action failed: " + ex);
				}
			}
		}
	}
	public static class AgentLink
	{
		private const int MaxBuffered = 2000;

		private static Thread thread;

		private static volatile bool running;

		private static TcpClient client;

		private static StreamWriter writer;

		private static readonly object sendLock = new object();

		private static readonly Queue<string> buffered = new Queue<string>();

		private static int port;

		private static string secret;

		private static volatile string refusedReason;

		private static volatile bool welcomed;

		private static bool refusedLogged;

		public static Action<string, Dictionary<string, object>> LocalEvent;

		public static bool Enabled => thread != null;

		public static bool Connected { get; private set; }

		public static void Start()
		{
			if (thread == null)
			{
				string environmentVariable = Environment.GetEnvironmentVariable("VA_AGENT_PORT");
				string environmentVariable2 = Environment.GetEnvironmentVariable("VA_AGENT_SECRET");
				if (!string.IsNullOrEmpty(environmentVariable) && !string.IsNullOrEmpty(environmentVariable2))
				{
					int.TryParse(environmentVariable, NumberStyles.Integer, CultureInfo.InvariantCulture, out port);
					secret = environmentVariable2;
				}
				else if (BepInExPlugin.AgentPort.Value > 0 && File.Exists(BepInExPlugin.AgentSecretFile.Value))
				{
					port = BepInExPlugin.AgentPort.Value;
					secret = File.ReadAllText(BepInExPlugin.AgentSecretFile.Value).Trim();
				}
				if (port <= 0 || string.IsNullOrEmpty(secret))
				{
					BepInExPlugin.Log("No agent configured; admin panel link disabled.");
					return;
				}
				running = true;
				thread = new Thread(Run)
				{
					IsBackground = true,
					Name = "ValheimAdmin.AgentLink"
				};
				thread.Start();
				BepInExPlugin.Log("Agent link started on 127.0.0.1:" + port);
			}
		}

		public static void Stop()
		{
			running = false;
			try
			{
				client?.Close();
			}
			catch
			{
			}
		}

		private static void Run()
		{
			while (running)
			{
				try
				{
					using TcpClient tcpClient = new TcpClient();
					tcpClient.NoDelay = true;
					tcpClient.Connect("127.0.0.1", port);
					client = tcpClient;
					NetworkStream stream = tcpClient.GetStream();
					StreamReader streamReader = new StreamReader(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
					lock (sendLock)
					{
						writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false))
						{
							AutoFlush = true,
							NewLine = "\n"
						};
						writer.WriteLine(Json.Serialize(new Dictionary<string, object>
						{
							{ "t", "hello" },
							{ "secret", secret },
							{ "version", "0.4.1" },
							{
								"pid",
								Process.GetCurrentProcess().Id
							}
						}));
					}
					string line;
					while (running && (line = streamReader.ReadLine()) != null)
					{
						Receive(line);
					}
				}
				catch (Exception ex)
				{
					if (welcomed || BepInExPlugin.IsDebug.Value)
					{
						BepInExPlugin.Warn("Agent link: " + ex.Message);
					}
				}
				finally
				{
					lock (sendLock)
					{
						writer = null;
						Connected = false;
					}
					welcomed = false;
					client = null;
				}
				if (!running)
				{
					break;
				}
				string text = refusedReason;
				refusedReason = null;
				if (text != null)
				{
					if (!refusedLogged)
					{
						BepInExPlugin.Warn("The agent refused the link: " + text);
					}
					refusedLogged = true;
					Thread.Sleep(30000);
				}
				else
				{
					Thread.Sleep(3000);
				}
			}
		}

		private static void Receive(string line)
		{
			Dictionary<string, object> d;
			try
			{
				d = Json.ParseObject(line);
			}
			catch (Exception ex)
			{
				BepInExPlugin.Warn("Bad message from agent: " + ex.Message);
				return;
			}
			string text = d.Str("t");
			if (!(text == "welcome"))
			{
				if (text == "refused")
				{
					refusedReason = d.Str("reason", "");
				}
				else
				{
					if (d.Str("t") != "req")
					{
						return;
					}
					long id = d.Long("id", 0L);
					string cmd = d.Str("cmd", "");
					Dictionary<string, object> args = d.Obj("args") ?? new Dictionary<string, object>();
					MainThread.Post(delegate
					{
						Commands.Handle(delegate(bool ok, object data, string error)
						{
							Reply(id, ok, data, error);
						}, cmd, args);
					});
				}
				return;
			}
			lock (sendLock)
			{
				if (writer == null)
				{
					return;
				}
				while (buffered.Count > 0)
				{
					writer.WriteLine(buffered.Dequeue());
				}
				Connected = true;
			}
			welcomed = true;
			refusedLogged = false;
			BepInExPlugin.Log("Connected to agent.");
		}

		public static void Send(Dictionary<string, object> msg, bool bufferIfOffline = false)
		{
			if (!Enabled)
			{
				return;
			}
			string text = Json.Serialize(msg);
			lock (sendLock)
			{
				if (writer != null && Connected)
				{
					try
					{
						writer.WriteLine(text);
						return;
					}
					catch (Exception ex)
					{
						BepInExPlugin.Dbgl("Agent send failed: " + ex.Message);
						writer = null;
					}
				}
				if (bufferIfOffline)
				{
					if (buffered.Count >= 2000)
					{
						buffered.Dequeue();
					}
					buffered.Enqueue(text);
				}
			}
		}

		public static void Reply(long id, bool ok, object data, string error = null)
		{
			Send(new Dictionary<string, object>
			{
				{ "t", "res" },
				{ "id", id },
				{ "ok", ok },
				{ "data", data },
				{ "error", error }
			});
		}

		public static void Event(string kind, Dictionary<string, object> data)
		{
			LocalEvent?.Invoke(kind, data);
			Send(new Dictionary<string, object>
			{
				{ "t", "ev" },
				{ "kind", kind },
				{
					"ts",
					DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture)
				},
				{ "data", data }
			}, bufferIfOffline: true);
		}
	}
	public delegate void Responder(bool ok, object data, string error);
	public static class Commands
	{
		public static void Handle(Responder reply, string cmd, Dictionary<string, object> args)
		{
			try
			{
				if (cmd != "status" && !ServerRole.IsServer)
				{
					reply(ok: false, null, "The world is not loaded yet");
				}
				else
				{
					Run(reply, cmd, args);
				}
			}
			catch (Exception ex)
			{
				BepInExPlugin.Warn("Command " + cmd + " failed: " + ex);
				reply(ok: false, null, ex.Message);
			}
		}

		private static void Ok(Responder reply, object data = null)
		{
			reply(ok: true, data, null);
		}

		private static void Fail(Responder reply, string error)
		{
			reply(ok: false, null, error);
		}

		private static void Run(Responder reply, string cmd, Dictionary<string, object> args)
		{
			switch (cmd)
			{
			case "status":
				Ok(reply, ServerRole.Stats());
				break;
			case "players":
				Ok(reply, Players());
				break;
			case "save":
				ZNet.instance.Save(false, true, false);
				Ok(reply, new Dictionary<string, object> { { "saving", true } });
				break;
			case "shutdown":
				Shutdown(reply, args.Str("message"));
				break;
			case "kick":
				ZNet.instance.Kick(Required(args, "player"));
				Ok(reply);
				break;
			case "ban":
				ZNet.instance.Ban(Required(args, "player"));
				Ok(reply);
				break;
			case "unban":
				ZNet.instance.Unban(Required(args, "player"));
				Ok(reply);
				break;
			case "list":
				Ok(reply, ListOf(Required(args, "list")).GetList());
				break;
			case "list_add":
				ListOf(Required(args, "list")).Add(Required(args, "value"));
				Ok(reply);
				break;
			case "list_remove":
				ListOf(Required(args, "list")).Remove(Required(args, "value"));
				Ok(reply);
				break;
			case "broadcast":
				Broadcast(Required(args, "text"), args.Bool("center", def: true));
				Ok(reply, new Dictionary<string, object> { 
				{
					"recipients",
					ZNet.instance.GetNrOfPlayers()
				} });
				break;
			case "exec":
				Exec(reply, Required(args, "line"));
				break;
			case "commands":
				Ok(reply, ConsoleRunner.List());
				break;
			case "objects":
				Ok(reply, WorldObjects.Run(args));
				break;
			case "drops":
				Ok(reply, DropCleaner.Run(args));
				break;
			case "despawn_enemies":
				Ok(reply, CreatureCleaner.Run(args));
				break;
			case "keys":
				Ok(reply, ZoneSystem.instance.GetGlobalKeys());
				break;
			case "key_set":
				ZoneSystem.instance.SetGlobalKey(Required(args, "key"));
				Ok(reply);
				break;
			case "key_remove":
				ZoneSystem.instance.RemoveGlobalKey(Required(args, "key"));
				Ok(reply);
				break;
			case "sleep":
				EnvMan.instance.SkipToMorning();
				Ok(reply);
				break;
			case "events":
				Ok(reply, RandEventSystem.instance.m_events.Select((RandomEvent e) => e.m_name).ToList());
				break;
			case "event_start":
				StartEvent(reply, args);
				break;
			case "event_stop":
				RandEventSystem.instance.ResetRandomEvent();
				Ok(reply);
				break;
			case "items":
				Ok(reply, (from go in ObjectDB.instance.m_items.Where(delegate(GameObject go)
					{
						if ((Object)(object)go != (Object)null)
						{
							ItemDrop component = go.GetComponent<ItemDrop>();
							if (component != null && component.m_itemData.m_shared.m_icons != null)
							{
								return component.m_itemData.m_shared.m_icons.Length != 0;
							}
						}
						return false;
					})
					select new Dictionary<string, object>
					{
						{
							"prefab",
							((Object)go).name
						},
						{
							"token",
							go.GetComponent<ItemDrop>().m_itemData.m_shared.m_name
						},
						{
							"type",
							((object)Unsafe.As<ItemType, ItemType>(ref go.GetComponent<ItemDrop>().m_itemData.m_shared.m_itemType)/*cast due to .constrained prefix*/).ToString()
						}
					}).ToList());
				break;
			case "plugins":
				Ok(reply, Chainloader.PluginInfos.Values.Select((PluginInfo p) => new Dictionary<string, object>
				{
					{
						"guid",
						p.Metadata.GUID
					},
					{
						"name",
						p.Metadata.Name
					},
					{
						"version",
						p.Metadata.Version.ToString()
					},
					{
						"file",
						Path.GetFileName(p.Location)
					}
				}).ToList());
				break;
			case "cheat":
				PlayerCommand(reply, args);
				break;
			case "give":
				Give(reply, args);
				break;
			case "snapshot":
				Snapshot(reply, args);
				break;
			case "icons":
				RenderIcons(reply, args);
				break;
			case "restore":
				if (!args.ContainsKey("payload"))
				{
					throw new ArgumentException("payload is required");
				}
				ForwardToClient(reply, args, "VA_Restore", 30f, Rpc.Pack(Json.Serialize(args["payload"])));
				break;
			default:
			{
				if (MapService.Handle(cmd, args, out var result))
				{
					Ok(reply, result);
				}
				else
				{
					Fail(reply, "Unknown command: " + cmd);
				}
				break;
			}
			}
		}

		private static string Required(Dictionary<string, object> args, string key)
		{
			string text = args.Str(key);
			if (string.IsNullOrEmpty(text))
			{
				throw new ArgumentException(key + " is required");
			}
			return text;
		}

		private static SyncedList ListOf(string name)
		{
			return (SyncedList)(name switch
			{
				"admin" => ZNet.instance.m_adminList, 
				"banned" => ZNet.instance.m_bannedList, 
				"permitted" => ZNet.instance.m_permittedList, 
				_ => throw new ArgumentException("Unknown list: " + name), 
			});
		}

		private static List<object> Players()
		{
			List<object> list = new List<object>();
			float num2 = default(float);
			float num3 = default(float);
			float num4 = default(float);
			float num5 = default(float);
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer.IsReady())
				{
					int num = -1;
					try
					{
						peer.m_socket.GetConnectionQuality(ref num2, ref num3, ref num, ref num4, ref num5);
					}
					catch
					{
					}
					Dictionary<string, object> dictionary = Hooks.PeerInfo(peer);
					dictionary["ping"] = num;
					dictionary["pos"] = new double[3]
					{
						Math.Round(peer.m_refPos.x),
						Math.Round(peer.m_refPos.y),
						Math.Round(peer.m_refPos.z)
					};
					dictionary["admin"] = ZNet.instance.IsAdmin(Hooks.HostOf(peer));
					if (ServerRole.Modded.TryGetValue(peer.m_uid, out var value))
					{
						dictionary["mod"] = value.Version;
						dictionary["characterId"] = value.CharacterId;
					}
					list.Add(dictionary);
				}
			}
			return list;
		}

		private static void Shutdown(Responder reply, string message)
		{
			Ok(reply);
			if (!string.IsNullOrEmpty(message))
			{
				Broadcast(message, center: true);
			}
			ServerRole.SnapshotAll("shutdown", delegate
			{
				ServerRole.SuppressSaveSnapshots = true;
				AgentLink.Event("stopping", new Dictionary<string, object>());
				ZNet.instance.Save(true, true, false);
				Application.Quit();
			});
		}

		public static void Broadcast(string text, bool center)
		{
			if (center)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "ShowMessage", new object[2] { 2, text });
			}
			foreach (long item in ServerRole.Modded.Keys.ToList())
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(item, "VA_Chat", new object[1] { text });
			}
		}

		private static void StartEvent(Responder reply, Dictionary<string, object> args)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			string name = Required(args, "name");
			ZNetPeer val = ServerRole.FindPeer(Required(args, "player"));
			if (val == null)
			{
				Fail(reply, "Player is not online");
				return;
			}
			if (!RandEventSystem.instance.m_events.Any((RandomEvent e) => e.m_name == name))
			{
				Fail(reply, "Unknown event: " + name);
				return;
			}
			RandEventSystem.instance.SetRandomEventByName(name, val.m_refPos);
			Ok(reply);
		}

		private static void ForwardToClient(Responder reply, Dictionary<string, object> args, string rpc, float timeout, params object[] rpcArgs)
		{
			ZNetPeer val = ServerRole.FindPeer(Required(args, "player"));
			if (val == null)
			{
				Fail(reply, "Player is not online");
				return;
			}
			if (!ServerRole.Modded.ContainsKey(val.m_uid))
			{
				Fail(reply, "Player does not have the Valheim Admin mod");
				return;
			}
			ServerRole.SendToClient(val.m_uid, rpc, timeout, delegate(bool ok, string json)
			{
				if (ok)
				{
					Ok(reply, new Json.Raw(json));
				}
				else
				{
					Fail(reply, json);
				}
			}, rpcArgs);
		}

		private static void Exec(Responder reply, string line, bool ranForPlayer = false)
		{
			string text = ConsoleRunner.FirstWord(line).ToLowerInvariant();
			if (!ranForPlayer)
			{
				switch (text)
				{
				case "objects":
				case "delobjects":
				case "drops":
				case "cleardrops":
				case "despawnenemycreatures":
				{
					KeyValuePair<string, Dictionary<string, object>> keyValuePair = ConsoleLine.Parse(line);
					Run(reply, keyValuePair.Key, keyValuePair.Value);
					return;
				}
				}
			}
			if ((Object)(object)Console.instance == (Object)null)
			{
				Fail(reply, "The game console is not available on this server");
				return;
			}
			if (ConsoleRunner.Find(line) == null)
			{
				Fail(reply, "Unknown game command: " + ConsoleRunner.FirstWord(line));
				return;
			}
			BepInExPlugin.Log("Admin command on the server: " + line);
			ConsoleRunner.Result result = ConsoleRunner.Run((Terminal)(object)Console.instance, line, allowCheatMark: true);
			Dictionary<string, object> dictionary = new Dictionary<string, object> { { "output", result.Output } };
			if (ranForPlayer)
			{
				dictionary["ranOnServer"] = true;
			}
			Ok(reply, dictionary);
		}

		private static void PlayerCommand(Responder reply, Dictionary<string, object> args)
		{
			string line = Required(args, "command");
			ZNetPeer val = ServerRole.FindPeer(Required(args, "player"));
			if (val == null)
			{
				Fail(reply, "Player is not online");
				return;
			}
			if (!ServerRole.Modded.TryGetValue(val.m_uid, out var value))
			{
				Fail(reply, "Player does not have the Valheim Admin mod, so commands can't run on their game. Server commands work without it.");
				return;
			}
			Action<bool, string> callback = delegate(bool ok, string text)
			{
				if (!ok)
				{
					Fail(reply, text);
				}
				else
				{
					Dictionary<string, object> dictionary = null;
					try
					{
						dictionary = Json.ParseObject(text);
					}
					catch
					{
					}
					if (dictionary != null && dictionary.Bool("runOnServer"))
					{
						try
						{
							Exec(reply, line, ranForPlayer: true);
							return;
						}
						catch (Exception ex)
						{
							BepInExPlugin.Warn("Command " + line + " failed: " + ex);
							Fail(reply, ex.Message);
							return;
						}
					}
					Ok(reply, new Json.Raw(text));
				}
			};
			if (ServerRole.AtLeast(value, 0, 3))
			{
				string json = Json.Serialize(new Dictionary<string, object>
				{
					{ "line", line },
					{
						"confirmCheats",
						args.Bool("confirmCheats")
					}
				});
				ServerRole.SendToClient(val.m_uid, "VA_Run", 20f, callback, Rpc.Pack(json));
			}
			else
			{
				ServerRole.SendToClient(val.m_uid, "VA_Cmd", 20f, callback, line);
			}
		}

		private static void RenderIcons(Responder reply, Dictionary<string, object> args)
		{
			ZNetPeer val = null;
			string text = args.Str("player");
			if (!string.IsNullOrEmpty(text))
			{
				val = ServerRole.FindPeer(text);
			}
			else
			{
				foreach (ZNetPeer peer in ZNet.instance.GetPeers())
				{
					if (peer.IsReady() && ServerRole.Modded.TryGetValue(peer.m_uid, out var value) && ServerRole.AtLeast(value, 0, 3))
					{
						val = peer;
						break;
					}
				}
			}
			if (val == null || !ServerRole.Modded.TryGetValue(val.m_uid, out var value2) || !ServerRole.AtLeast(value2, 0, 3))
			{
				Fail(reply, "No online player with the Valheim Admin mod 0.3+ to render icons");
				return;
			}
			string json = Json.Serialize(new Dictionary<string, object> { 
			{
				"items",
				args.List("items") ?? new List<object>()
			} });
			ServerRole.SendToClient(val.m_uid, "VA_Icons", 30f, delegate(bool ok, string text2)
			{
				if (ok)
				{
					Ok(reply, new Json.Raw(text2));
				}
				else
				{
					Fail(reply, text2);
				}
			}, Rpc.Pack(json));
		}

		private static void Give(Responder reply, Dictionary<string, object> args)
		{
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			string text = Required(args, "prefab");
			int num = Math.Max(1, args.Int("count", 1));
			int num2 = Math.Max(1, args.Int("quality", 1));
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text);
			if ((Object)(object)itemPrefab == (Object)null || (Object)(object)itemPrefab.GetComponent<ItemDrop>() == (Object)null)
			{
				Fail(reply, "Unknown item: " + text);
				return;
			}
			ZNetPeer val = ServerRole.FindPeer(Required(args, "player"));
			if (val == null)
			{
				Fail(reply, "Player is not online");
				return;
			}
			if (ServerRole.Modded.ContainsKey(val.m_uid))
			{
				ForwardToClient(reply, args, "VA_Give", 20f, text, num, num2);
				return;
			}
			int val2 = Math.Max(1, itemPrefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxStackSize);
			int num3 = num;
			while (num3 > 0)
			{
				int num4 = Math.Min(num3, val2);
				num3 -= num4;
				Vector3 val3 = val.m_refPos + Vector3.up + Random.insideUnitSphere * 0.5f;
				ItemDrop component = Object.Instantiate<GameObject>(itemPrefab, val3, Quaternion.identity).GetComponent<ItemDrop>();
				component.m_itemData.m_stack = num4;
				component.m_itemData.m_quality = num2;
				component.m_itemData.m_durability = component.m_itemData.GetMaxDurability();
				component.Save();
			}
			Ok(reply, new Dictionary<string, object> { { "dropped", num } });
		}

		private static void Snapshot(Responder reply, Dictionary<string, object> args)
		{
			string trigger = args.Str("trigger", "manual");
			string text = args.Str("player");
			if (string.IsNullOrEmpty(text))
			{
				Ok(reply, new Dictionary<string, object> { 
				{
					"requested",
					ServerRole.SnapshotAll(trigger)
				} });
				return;
			}
			ZNetPeer val = ServerRole.FindPeer(text);
			if (val == null)
			{
				Fail(reply, "Player is not online");
				return;
			}
			if (!ServerRole.Modded.ContainsKey(val.m_uid))
			{
				Fail(reply, "Player does not have the Valheim Admin mod");
				return;
			}
			ServerRole.RequestSnapshot(val, trigger, delegate(bool ok, string json)
			{
				if (ok)
				{
					Ok(reply, new Json.Raw(json));
				}
				else
				{
					Fail(reply, json);
				}
			});
		}
	}
	public static class CreatureCleaner
	{
		private const int BatchSize = 100;

		private const float BatchInterval = 0.25f;

		private const int TopPrefabs = 25;

		private static readonly Queue<ZDOID> queue = new Queue<ZDOID>();

		private static HashSet<int> kinds;

		private static float timer;

		private static int total;

		private static int removed;

		public static bool Busy => queue.Count > 0;

		public static Dictionary<string, object> Run(Dictionary<string, object> args)
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			if (ZDOMan.instance == null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				throw new InvalidOperationException("The world is not loaded yet");
			}
			if (Busy)
			{
				throw new InvalidOperationException("A despawn is still running: " + queue.Count + " of " + total + " creatures left. Wait for it to finish.");
			}
			Vector3? val = null;
			float num = 0f;
			if (args.ContainsKey("radius") || !string.IsNullOrEmpty(args.Str("player")))
			{
				num = (float)args.Double("radius");
				if (num <= 0f)
				{
					throw new ArgumentException("The radius must be positive");
				}
				val = WorldObjects.Center(args);
			}
			HashSet<int> hashSet = HostileKinds();
			Dictionary<int, int> dictionary = new Dictionary<int, int>();
			List<ZDOID> list = new List<ZDOID>();
			foreach (ZDO value2 in ZDOMan.instance.m_objectsByID.Values)
			{
				int prefab = value2.GetPrefab();
				if (hashSet.Contains(prefab) && !value2.GetBool(ZDOVars.s_tamed, false) && (!val.HasValue || !(WorldObjects.Flat(value2.GetPosition(), val.Value) > num)))
				{
					list.Add(value2.m_uid);
					dictionary.TryGetValue(prefab, out var value);
					dictionary[prefab] = value + 1;
				}
			}
			string text = (val.HasValue ? (" within " + num.ToString("0.#", CultureInfo.InvariantCulture) + " m of " + WorldObjects.Describe(val.Value)) : " in the whole world");
			List<string> list2 = new List<string> { list.Count + " hostile creatures" + text };
			foreach (KeyValuePair<int, int> item in dictionary.OrderByDescending((KeyValuePair<int, int> p) => p.Value).Take(25))
			{
				GameObject prefab2 = ZNetScene.instance.GetPrefab(item.Key);
				list2.Add("  " + item.Value + " x " + (((Object)(object)prefab2 != (Object)null) ? ((Object)prefab2).name : item.Key.ToString(CultureInfo.InvariantCulture)));
			}
			if (dictionary.Count > 25)
			{
				list2.Add("  ... and " + (dictionary.Count - 25) + " more kinds");
			}
			if (list.Count == 0)
			{
				list2.Add("Nothing to despawn.");
			}
			else
			{
				foreach (ZDOID item2 in list)
				{
					queue.Enqueue(item2);
				}
				total = list.Count;
				removed = 0;
				timer = 0f;
				list2.Add("Despawning in the background, about " + (int)Math.Ceiling((double)list.Count / 100.0 * 0.25) + " s (no loot drops). Not touched: bosses, Dverger, animals, tamed creatures, traders. Then save.");
				BepInExPlugin.Log("Admin despawn of hostile creatures started: " + list.Count + " creatures" + text);
			}
			return new Dictionary<string, object>
			{
				{ "output", list2 },
				{ "found", list.Count },
				{ "removing", list.Count }
			};
		}

		public static void Update()
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			if (queue.Count == 0)
			{
				return;
			}
			if (ZDOMan.instance == null || (Object)(object)ZNet.instance == (Object)null)
			{
				queue.Clear();
				return;
			}
			timer -= Time.unscaledDeltaTime;
			if (timer > 0f)
			{
				return;
			}
			timer = 0.25f;
			long sessionID = ZDOMan.GetSessionID();
			for (int i = 0; i < 100; i++)
			{
				if (queue.Count <= 0)
				{
					break;
				}
				ZDO zDO = ZDOMan.instance.GetZDO(queue.Dequeue());
				if (zDO != null && zDO.IsValid() && HostileKinds().Contains(zDO.GetPrefab()) && !zDO.GetBool(ZDOVars.s_tamed, false))
				{
					zDO.SetOwner(sessionID);
					ZDOMan.instance.DestroyZDO(zDO);
					removed++;
				}
			}
			if (queue.Count == 0)
			{
				BepInExPlugin.Log("Admin despawn of hostile creatures finished: " + removed + " of " + total + " creatures removed");
			}
		}

		private static HashSet<int> HostileKinds()
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			if (kinds != null)
			{
				return kinds;
			}
			HashSet<int> hashSet = new HashSet<int>();
			foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
			{
				if (!((Object)(object)prefab == (Object)null))
				{
					Character component = prefab.GetComponent<Character>();
					if (!((Object)(object)component == (Object)null) && !component.m_boss && IsMonsterFaction(component.m_faction) && !((Object)(object)prefab.GetComponent<Trader>() != (Object)null))
					{
						hashSet.Add(StringExtensionMethods.GetStableHashCode(((Object)prefab).name));
					}
				}
			}
			kinds = hashSet;
			BepInExPlugin.Dbgl("Despawn: " + hashSet.Count + " hostile creature prefabs");
			return kinds;
		}

		private static bool IsMonsterFaction(Faction f)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Invalid comparison between Unknown and I4
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Invalid comparison between Unknown and I4
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Invalid comparison between Unknown and I4
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			if ((int)f != 2 && (int)f != 3 && (int)f != 4 && (int)f != 7 && (int)f != 5 && (int)f != 13 && (int)f != 6)
			{
				return (int)f == 9;
			}
			return true;
		}
	}
	public static class DropCleaner
	{
		private const int BatchSize = 100;

		private const float BatchInterval = 0.25f;

		private const int TopPrefabs = 25;

		private static readonly Queue<ZDOID> queue = new Queue<ZDOID>();

		private static HashSet<int> kinds;

		private static float timer;

		private static int total;

		private static int removed;

		public static bool Busy => queue.Count > 0;

		public static Dictionary<string, object> Run(Dictionary<string, object> args)
		{
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_037a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0381: Unknown result type (might be due to invalid IL or missing references)
			if (ZDOMan.instance == null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				throw new InvalidOperationException("The world is not loaded yet");
			}
			bool flag = args.Bool("delete");
			double num = args.Double("minutes");
			if (Busy)
			{
				throw new InvalidOperationException("A cleanup is still running: " + queue.Count + " of " + total + " items left. Check again with drops.");
			}
			HashSet<int> hashSet = DropKinds();
			Dictionary<int, int> dictionary = new Dictionary<int, int>();
			List<ZDOID> list = new List<ZDOID>();
			DateTime time = ZNet.instance.GetTime();
			int num2 = 0;
			foreach (ZDO value2 in ZDOMan.instance.m_objectsByID.Values)
			{
				int prefab = value2.GetPrefab();
				if (!hashSet.Contains(prefab) || value2.GetBool(ZDOVars.s_piece, false))
				{
					continue;
				}
				if (num > 0.0)
				{
					long num3 = value2.GetLong(ZDOVars.s_spawnTime, 0L);
					if (num3 > 0 && (time - new DateTime(num3)).TotalMinutes < num)
					{
						continue;
					}
					if (num3 <= 0)
					{
						num2++;
					}
				}
				list.Add(value2.m_uid);
				dictionary.TryGetValue(prefab, out var value);
				dictionary[prefab] = value + 1;
			}
			List<string> list2 = new List<string>();
			string text = ((num > 0.0) ? (" older than " + num.ToString("0.#", CultureInfo.InvariantCulture) + " min") : "");
			list2.Add(list.Count + " dropped items" + text + " in the whole world");
			foreach (KeyValuePair<int, int> item in dictionary.OrderByDescending((KeyValuePair<int, int> p) => p.Value).Take(25))
			{
				GameObject prefab2 = ZNetScene.instance.GetPrefab(item.Key);
				list2.Add("  " + item.Value + " x " + (((Object)(object)prefab2 != (Object)null) ? ((Object)prefab2).name : item.Key.ToString(CultureInfo.InvariantCulture)));
			}
			if (dictionary.Count > 25)
			{
				list2.Add("  ... and " + (dictionary.Count - 25) + " more kinds");
			}
			if (num2 > 0)
			{
				list2.Add(num2 + " of them have no spawn time recorded and count as old");
			}
			list2.Add("Not touched: fish, food placed as decoration, items in chests, on stands and in tombstones.");
			if (!flag)
			{
				if (list.Count > 0)
				{
					list2.Add("Remove them with: cleardrops" + ((num > 0.0) ? (" " + num.ToString("0.#", CultureInfo.InvariantCulture)) : ""));
				}
			}
			else if (list.Count == 0)
			{
				list2.Add("Nothing to remove.");
			}
			else
			{
				foreach (ZDOID item2 in list)
				{
					queue.Enqueue(item2);
				}
				total = list.Count;
				removed = 0;
				timer = 0f;
				list2.Add("Removing in the background, about " + (int)Math.Ceiling((double)list.Count / 100.0 * 0.25) + " s. Check progress with drops, then save.");
				BepInExPlugin.Log("Admin cleanup of dropped items started: " + list.Count + " items" + text);
			}
			return new Dictionary<string, object>
			{
				{ "output", list2 },
				{ "found", list.Count },
				{
					"removing",
					flag ? list.Count : 0
				}
			};
		}

		public static void Update()
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			if (queue.Count == 0)
			{
				return;
			}
			if (ZDOMan.instance == null || (Object)(object)ZNet.instance == (Object)null)
			{
				queue.Clear();
				return;
			}
			timer -= Time.unscaledDeltaTime;
			if (timer > 0f)
			{
				return;
			}
			timer = 0.25f;
			long sessionID = ZDOMan.GetSessionID();
			for (int i = 0; i < 100; i++)
			{
				if (queue.Count <= 0)
				{
					break;
				}
				ZDO zDO = ZDOMan.instance.GetZDO(queue.Dequeue());
				if (zDO != null && zDO.IsValid() && DropKinds().Contains(zDO.GetPrefab()) && !zDO.GetBool(ZDOVars.s_piece, false))
				{
					zDO.SetOwner(sessionID);
					ZDOMan.instance.DestroyZDO(zDO);
					removed++;
				}
			}
			if (queue.Count == 0)
			{
				BepInExPlugin.Log("Admin cleanup of dropped items finished: " + removed + " of " + total + " items removed");
			}
		}

		private static HashSet<int> DropKinds()
		{
			if (kinds != null)
			{
				return kinds;
			}
			HashSet<int> hashSet = new HashSet<int>();
			foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
			{
				if (!((Object)(object)prefab == (Object)null))
				{
					ItemDrop component = prefab.GetComponent<ItemDrop>();
					if (!((Object)(object)component == (Object)null) && component.m_autoDestroy && !((Object)(object)prefab.GetComponent<Fish>() != (Object)null) && (!((Object)(object)prefab.GetComponent<Piece>() != (Object)null) || !((Object)(object)prefab.GetComponent<Rigidbody>() == (Object)null)))
					{
						hashSet.Add(StringExtensionMethods.GetStableHashCode(((Object)prefab).name));
					}
				}
			}
			kinds = hashSet;
			BepInExPlugin.Dbgl("Drops: " + hashSet.Count + " item prefabs");
			return kinds;
		}
	}
	public static class Hooks
	{
		[HarmonyPatch(typeof(Game), "Start")]
		private static class Game_Start_Patch
		{
			private static void Postfix()
			{
				if (ZRoutedRpc.instance != null && !((Object)(object)ZNet.instance == (Object)null))
				{
					if (ZNet.instance.IsDedicated())
					{
						ServerRole.Register();
						StandaloneServer.Start();
						AgentLink.Event("started", new Dictionary<string, object> { 
						{
							"world",
							ZNet.instance.GetWorldName()
						} });
					}
					else
					{
						ClientRole.Register();
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private static class ZNet_RPC_PeerInfo_Patch
		{
			private static void Postfix(ZNet __instance, ZRpc rpc)
			{
				if (ServerRole.IsServer)
				{
					ZNetPeer peer = __instance.GetPeer(rpc);
					if (peer != null && peer.IsReady() && joined.Add(peer.m_uid))
					{
						BepInExPlugin.Log("Joined: " + peer.m_playerName + " (" + HostOf(peer) + ")");
						AgentLink.Event("join", PeerInfo(peer));
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static class ZNet_Disconnect_Patch
		{
			private static void Prefix(ZNetPeer peer)
			{
				if (ServerRole.IsServer && peer != null)
				{
					ServerRole.OnPeerLeft(peer.m_uid);
					if (joined.Remove(peer.m_uid))
					{
						AgentLink.Event("leave", PeerInfo(peer));
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "SaveWorld")]
		private static class ZNet_SaveWorld_Patch
		{
			private static void Postfix()
			{
				if (ServerRole.IsServer)
				{
					MapService.Save();
					int num = ((!ServerRole.SuppressSaveSnapshots) ? ServerRole.SnapshotAll("save") : 0);
					AgentLink.Event("save", new Dictionary<string, object> { { "snapshots", num } });
				}
			}
		}

		[HarmonyPatch(typeof(ZRoutedRpc), "RPC_RoutedRPC")]
		private static class ZRoutedRpc_RPC_RoutedRPC_Patch
		{
			private unsafe static void Prefix(ZPackage pkg)
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Expected O, but got Unknown
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Expected O, but got Unknown
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0054: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Expected O, but got Unknown
				//IL_006c: Unknown result type (might be due to invalid IL or missing references)
				//IL_006f: Invalid comparison between Unknown and I4
				//IL_0119: Unknown result type (might be due to invalid IL or missing references)
				//IL_0128: Unknown result type (might be due to invalid IL or missing references)
				//IL_0137: Unknown result type (might be due to invalid IL or missing references)
				if (!ServerRole.IsServer || pkg == null)
				{
					return;
				}
				try
				{
					ZPackage val = new ZPackage(pkg.GetArray());
					RoutedRPCData val2 = new RoutedRPCData();
					val2.Deserialize(val);
					if (val2.m_methodHash == chatHash)
					{
						ZPackage parameters = val2.m_parameters;
						parameters.SetPos(0);
						Vector3 val3 = parameters.ReadVector3();
						Type val4 = (Type)parameters.ReadInt();
						UserInfo val5 = new UserInfo();
						val5.Deserialize(ref parameters);
						string value = parameters.ReadString();
						if ((int)val4 != 3)
						{
							ZNetPeer peer = ZNet.instance.GetPeer(val2.m_senderPeerID);
							AgentLink.Event("chat", new Dictionary<string, object>
							{
								{ "uid", val2.m_senderPeerID },
								{
									"player",
									peer?.m_playerName ?? val5.Name
								},
								{
									"host",
									HostOf(peer)
								},
								{
									"type",
									((object)(*(Type*)(&val4))/*cast due to .constrained prefix*/).ToString()
								},
								{ "text", value },
								{
									"pos",
									new double[3]
									{
										Math.Round(val3.x),
										Math.Round(val3.y),
										Math.Round(val3.z)
									}
								}
							});
						}
					}
				}
				catch (Exception ex)
				{
					BepInExPlugin.Dbgl("Chat peek failed: " + ex.Message);
				}
			}
		}

		[HarmonyPatch(typeof(ZoneSystem), "RPC_SetGlobalKey")]
		private static class ZoneSystem_RPC_SetGlobalKey_Patch
		{
			private static void Prefix(ZoneSystem __instance, string name, out bool __state)
			{
				__state = __instance.m_globalKeys.Contains(name);
			}

			private static void Postfix(ZoneSystem __instance, long sender, string name, bool __state)
			{
				if (!(!ServerRole.IsServer || __state) && __instance.m_globalKeys.Contains(name))
				{
					ZNetPeer peer = ZNet.instance.GetPeer(sender);
					AgentLink.Event(name.StartsWith("defeated_", StringComparison.OrdinalIgnoreCase) ? "boss" : "globalkey", new Dictionary<string, object>
					{
						{ "key", name },
						{
							"player",
							peer?.m_playerName
						}
					});
				}
			}
		}

		[HarmonyPatch(typeof(RandEventSystem), "SetRandomEvent")]
		private static class RandEventSystem_SetRandomEvent_Patch
		{
			private static void Postfix(RandomEvent ev, Vector3 pos)
			{
				//IL_0043: 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_006b: Unknown result type (might be due to invalid IL or missing references)
				//IL_007a: Unknown result type (might be due to invalid IL or missing references)
				if (!ServerRole.IsServer)
				{
					return;
				}
				string text = ev?.m_name;
				if (!(text == lastEventName))
				{
					if (text != null)
					{
						AgentLink.Event("raid", new Dictionary<string, object>
						{
							{ "name", text },
							{
								"near",
								NearestPlayer(pos)
							},
							{
								"pos",
								new double[3]
								{
									Math.Round(pos.x),
									Math.Round(pos.y),
									Math.Round(pos.z)
								}
							}
						});
					}
					else
					{
						AgentLink.Event("raid_end", new Dictionary<string, object> { { "name", lastEventName } });
					}
					lastEventName = text;
				}
			}
		}

		[HarmonyPatch(typeof(TombStone), "Awake")]
		private static class TombStone_Awake_Patch
		{
			private static void Postfix(TombStone __instance)
			{
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				//IL_00af: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b4: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
				//IL_010f: Unknown result type (might be due to invalid IL or missing references)
				if (!ServerRole.IsServer)
				{
					return;
				}
				try
				{
					ZNetView nview = __instance.m_nview;
					ZDO val = ((nview != null) ? nview.GetZDO() : null);
					if (val == null || !reportedTombstones.Add(val.m_uid))
					{
						return;
					}
					long num = val.GetLong(ZDOVars.s_timeOfDeath, 0L);
					if (num != 0L && !((ZNet.instance.GetTime() - new DateTime(num)).TotalSeconds > 60.0))
					{
						string text = val.GetString(ZDOVars.s_ownerName, "");
						if (!recentDeaths.TryGetValue(text, out var value) || !(Time.realtimeSinceStartup - value < 120f))
						{
							NoteDeath(text);
							Vector3 position = val.GetPosition();
							AgentLink.Event("death", new Dictionary<string, object>
							{
								{ "player", text },
								{ "cause", "unknown" },
								{
									"pos",
									new double[3]
									{
										Math.Round(position.x),
										Math.Round(position.y),
										Math.Round(position.z)
									}
								}
							});
						}
					}
				}
				catch (Exception ex)
				{
					BepInExPlugin.Dbgl("Tombstone check failed: " + ex.Message);
				}
			}
		}

		private static readonly HashSet<long> joined = new HashSet<long>();

		private static readonly Dictionary<string, float> recentDeaths = new Dictionary<string, float>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<ZDOID> reportedTombstones = new HashSet<ZDOID>();

		private static readonly int chatHash = StringExtensionMethods.GetStableHashCode("ChatMessage");

		private static string lastEventName;

		public static string HostOf(ZNetPeer peer)
		{
			try
			{
				object obj;
				if (peer == null)
				{
					obj = null;
				}
				else
				{
					ISocket socket = peer.m_socket;
					obj = ((socket != null) ? socket.GetHostName() : null);
				}
				if (obj == null)
				{
					obj = "";
				}
				return (string)obj;
			}
			catch
			{
				return "";
			}
		}

		public static Dictionary<string, object> PeerInfo(ZNetPeer peer)
		{
			return new Dictionary<string, object>
			{
				{ "uid", peer.m_uid },
				{ "player", peer.m_playerName },
				{
					"host",
					HostOf(peer)
				}
			};
		}

		public static void NoteDeath(string player)
		{
			if (!string.IsNullOrEmpty(player))
			{
				recentDeaths[player] = Time.realtimeSinceStartup;
			}
		}

		private static string NearestPlayer(Vector3 pos)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			string result = null;
			float num = float.MaxValue;
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer.IsReady())
				{
					float num2 = Vector3.Distance(peer.m_refPos, pos);
					if (num2 < num)
					{
						num = num2;
						result = peer.m_playerName;
					}
				}
			}
			return result;
		}
	}
	public sealed class FogTracker
	{
		private const float Interval = 2f;

		private const float Radius = 100f;

		private static readonly TimeSpan PngInterval = TimeSpan.FromSeconds(30.0);

		private readonly string file;

		private readonly int size;

		private readonly float pixelSize;

		private readonly BitArray explored;

		private float timer;

		private bool unsaved;

		private long version;

		private long pngVersion = -1L;

		private int encoding;

		private DateTime lastEncode = DateTime.MinValue;

		public string PngFile => Path.ChangeExtension(file, ".png");

		public long PngVersion => Interlocked.Read(in pngVersion);

		public string PublicMapFile => Path.Combine(Path.GetDirectoryName(file), "map-public.png");

		public FogTracker(string file, int size, float pixelSize)
		{
			this.file = file;
			this.size = size;
			this.pixelSize = pixelSize;
			explored = new BitArray(size * size);
			Load();
		}

		public void Update(float dt)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			timer += dt;
			if (timer < 2f)
			{
				return;
			}
			timer = 0f;
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer.IsReady())
				{
					Explore(MapMarkers.PositionOf(peer));
				}
			}
		}

		public bool IsExplored(float wx, float wz)
		{
			int num = Mathf.RoundToInt(wx / pixelSize + (float)(size / 2));
			int num2 = Mathf.RoundToInt(wz / pixelSize + (float)(size / 2));
			if (num >= 0 && num2 >= 0 && num < size && num2 < size)
			{
				return explored[num2 * size + num];
			}
			return false;
		}

		public BitArray Resample(BitArray other, int otherSize, float otherPixelSize)
		{
			BitArray bitArray = new BitArray(size * size);
			for (int i = 0; i < size; i++)
			{
				int num = Mathf.RoundToInt((float)(i - size / 2) * pixelSize / otherPixelSize + (float)(otherSize / 2));
				if (num < 0 || num >= otherSize)
				{
					continue;
				}
				for (int j = 0; j < size; j++)
				{
					int num2 = Mathf.RoundToInt((float)(j - size / 2) * pixelSize / otherPixelSize + (float)(otherSize / 2));
					if (num2 >= 0 && num2 < otherSize && other[num * otherSize + num2])
					{
						bitArray[i * size + j] = true;
					}
				}
			}
			return bitArray;
		}

		public void MergeExplored(BitArray bits)
		{
			if (bits.Length == explored.Length)
			{
				explored.Or(bits);
				unsaved = true;
				version++;
			}
		}

		private void Explore(Vector3 p)
		{
			//IL_0012: 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)
			int num = Mathf.CeilToInt(100f / pixelSize);
			int num2 = Mathf.RoundToInt(p.x / pixelSize + (float)(size / 2));
			int num3 = Mathf.RoundToInt(p.z / pixelSize + (float)(size / 2));
			bool flag = false;
			for (int i = num3 - num; i <= num3 + num; i++)
			{
				if (i < 0 || i >= size)
				{
					continue;
				}
				for (int j = num2 - num; j <= num2 + num; j++)
				{
					if (j >= 0 && j < size && (j - num2) * (j - num2) + (i - num3) * (i - num3) <= num * num)
					{
						int index = i * size + j;
						if (!explored[index])
						{
							explored[index] = true;
							flag = true;
						}
					}
				}
			}
			if (flag)
			{
				unsaved = true;
				version++;
			}
		}

		public void RefreshPngs(MapGenerator map)
		{
			long wanted = version * 1000003 + map.Version;
			if (map.State != MapGenerator.Status.Ready || (wanted == PngVersion && File.Exists(PngFile) && File.Exists(PublicMapFile)) || (DateTime.UtcNow - lastEncode < PngInterval && File.Exists(PngFile) && File.Exists(PublicMapFile)) || Interlocked.CompareExchange(ref encoding, 1, 0) != 0)
			{
				return;
			}
			lastEncode = DateTime.UtcNow;
			BitArray copy = (BitArray)explored.Clone();
			ThreadPool.QueueUserWorkItem(delegate
			{
				try
				{
					Write(PngFile, EncodeFog(copy));
					byte[] array = map.Pixels();
					if (array != null)
					{
						Write(PublicMapFile, EncodePublicMap(copy, array));
					}
					Interlocked.Exchange(ref pngVersion, wanted);
				}
				catch (Exception ex)
				{
					BepInExPlugin.Warn("Writing the public map failed: " + ex.Message);
				}
				finally
				{
					Interlocked.Exchange(ref encoding, 0);
				}
			});
		}

		private static void Write(string path, byte[] data)
		{
			string text = path + ".tmp";
			File.WriteAllBytes(text, data);
			if (File.Exists(path))
			{
				File.Delete(path);
			}
			File.Move(text, path);
		}

		private byte[] EncodeFog(BitArray bits)
		{
			byte[] array = new byte[size * size * 2];
			for (int i = 0; i < size; i++)
			{
				int num = size - 1 - i;
				for (int j = 0; j < size; j++)
				{
					if (!bits[i * size + j])
					{
						int num2 = (num * size + j) * 2;
						array[num2] = 24;
						array[num2 + 1] = byte.MaxValue;
					}
				}
			}
			return Png.Encode(array, size, size, 4);
		}

		private byte[] EncodePublicMap(BitArray bits, byte[] map)
		{
			byte[] array = (byte[])map.Clone();
			for (int i = 0; i < size; i++)
			{
				int num = size - 1 - i;
				for (int j = 0; j < size; j++)
				{
					if (!bits[i * size + j])
					{
						int num2 = (num * size + j) * 3;
						array[num2] = 24;
						array[num2 + 1] = 26;
						array[num2 + 2] = 30;
					}
				}
			}
			return Png.Encode(array, size, size, 2);
		}

		public void Save()
		{
			if (!unsaved)
			{
				return;
			}
			try
			{
				byte[] array = new byte[(explored.Length + 7) / 8];
				explored.CopyTo(array, 0);
				using (MemoryStream memoryStream = new MemoryStream())
				{
					using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
					{
						deflateStream.Write(array, 0, array.Length);
					}
					string text = file + ".tmp";
					File.WriteAllBytes(text, memoryStream.ToArray());
					if (File.Exists(file))
					{
						File.Delete(file);
					}
					File.Move(text, file);
				}
				unsaved = false;
			}
			catch (Exception ex)
			{
				BepInExPlugin.Warn("Saving the explored map failed: " + ex.Message);
			}
		}

		private void Load()
		{
			if (!File.Exists(file))
			{
				return;
			}
			try
			{
				using (DeflateStream deflateStream = new DeflateStream(new MemoryStream(File.ReadAllBytes(file)), CompressionMode.Decompress))
				{
					using MemoryStream memoryStream = new MemoryStream();
					deflateStream.CopyTo(memoryStream);
					BitArray bitArray = new BitArray(memoryStream.ToArray());
					for (int i = 0; i < explored.Length && i < bitArray.Length; i++)
					{
						explored[i] = bitArray[i];
					}
				}
				version = 1L;
			}
			catch (Exception ex)
			{
				BepInExPlugin.Warn("Loading the explored map failed: " + ex.Message);
			}
		}
	}
	public sealed class GamePins
	{
		private sealed class Table
		{
			public uint Revision;

			public List<SharedMapData.Pin> Pins = new List<SharedMapData.Pin>();
		}

		private const float PollInterval = 60f;

		private const float GamePixelSize = 12f;

		private const int MaxPinsPerPlayer = 2000;

		private readonly string file;

		private readonly FogTracker fog;

		private readonly Dictionary<ZDOID, Table> tables = new Dictionary<ZDOID, Table>();

		private List<SharedMapData.Pin> tablePins = new List<SharedMapData.Pin>();

		private readonly Dictionary<long, Dictionary<string, object>> players = new Dictionary<long, Dictionary<string, object>>();

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

		private float pollTimer = 50f;

		private bool unsaved;

		public int TableCount => tables.Count;

		public GamePins(string file, FogTracker fog)
		{
			this.file = file;
			this.fog = fog;
			Load();
		}

		public void Update(float dt)
		{
			pollTimer += dt;
			if (pollTimer < 60f)
			{
				return;
			}
			pollTimer = 0f;
			LearnNames();
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer.IsReady() && ServerRole.Modded.TryGetValue(peer.m_uid, out var value) && ServerRole.AtLeast(value, 0, 4))
				{
					long characterId = value.CharacterId;
					string player = peer.m_playerName;
					ServerRole.SendToClient(peer.m_uid, "VA_Pins", 20f, delegate(bool ok, string json)
					{
						OnPlayerPins(characterId, player, ok, json);
					});
				}
			}
		}

		private void LearnNames()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer.IsReady() && !((ZDOID)(ref peer.m_characterID)).IsNone())
				{
					ZDO zDO = ZDOMan.instance.GetZDO(peer.m_characterID);
					long num = ((zDO != null) ? zDO.GetLong(ZDOVars.s_playerID, 0L) : 0);
					if (num != 0L)
					{
						Name(num, peer.m_playerName);
					}
				}
			}
			foreach (ServerRole.ModdedPeer value in ServerRole.Modded.Values)
			{
				Name(value.CharacterId, value.CharacterName);
			}
		}

		private void Name(long characterId, string name)
		{
			if (characterId != 0L && !string.IsNullOrEmpty(name) && (!names.TryGetValue(characterId, out var value) || !(value == name)))
			{
				names[characterId] = name;
				unsaved = true;
			}
		}

		public void SaveIfChanged()
		{
			if (unsaved)
			{
				Save();
			}
		}

		private void OnPlayerPins(long characterId, string player, bool ok, string json)
		{
			if (!ok)
			{
				BepInExPlugin.Dbgl("Map pins of " + player + ": " + json);
				return;
			}
			Dictionary<string, object> d;
			try
			{
				d = Json.ParseObject(json);
			}
			catch (Exception ex)
			{
				BepInExPlugin.Dbgl("Map pins of " + player + ": " + ex.Message);
				return;
			}
			Name(characterId, player);
			if (d.Bool("disabled"))
			{
				if (players.Remove(characterId))
				{
					Save();
				}
				return;
			}
			List<object> list = new List<object>();