Decompiled source of BuildStats v1.2.0

BuildStats.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BuildStats
{
	internal static class Backfill
	{
		internal const string IdPrefix = "id:";

		private static readonly FieldInfo ObjectsField = AccessTools.Field(typeof(ZDOMan), "m_objectsByID");

		internal static bool Ready
		{
			get
			{
				if (ZDOMan.instance != null)
				{
					return (Object)(object)ZNetScene.instance != (Object)null;
				}
				return false;
			}
		}

		internal static IEnumerable WorldObjects()
		{
			return (ObjectsField?.GetValue(ZDOMan.instance) as IDictionary)?.Values;
		}

		internal static void Run(StatsStore store)
		{
			IEnumerable enumerable = WorldObjects();
			if (enumerable == null)
			{
				Plugin.Log.LogWarning((object)"Could not read the world's objects; skipping the count of existing builds.");
				return;
			}
			int num = 0;
			foreach (object item in enumerable)
			{
				ZDO val = (ZDO)((item is ZDO) ? item : null);
				if (val == null)
				{
					continue;
				}
				long num2 = val.GetLong("creator", 0L);
				if (num2 == 0L)
				{
					continue;
				}
				GameObject prefab = ZNetScene.instance.GetPrefab(val.GetPrefab());
				Piece val2 = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<Piece>() : null);
				if ((Object)(object)val2 == (Object)null || val2.m_resources == null || val2.m_resources.Length == 0)
				{
					continue;
				}
				string player = "id:" + num2;
				store.Add(player, Category.Built, val2.m_name, 1);
				Requirement[] resources = val2.m_resources;
				foreach (Requirement val3 in resources)
				{
					if ((Object)(object)val3?.m_resItem != (Object)null)
					{
						store.Add(player, Category.BuildMaterials, val3.m_resItem.m_itemData.m_shared.m_name, val3.m_amount);
					}
				}
				num++;
			}
			Plugin.Log.LogInfo((object)$"Counted {num} pieces already built in this world.");
		}
	}
	internal static class CraftBackfill
	{
		internal const string WorldFlag = "crafted-backfill";

		private static readonly MethodInfo LoadFromZdo = AccessTools.Method(typeof(ItemDrop), "LoadFromZDO", new Type[2]
		{
			typeof(ItemData),
			typeof(ZDO)
		}, (Type[])null);

		private static readonly MethodInfo LoadSlotFromZdo = AccessTools.Method(typeof(ItemDrop), "LoadFromZDO", new Type[3]
		{
			typeof(int),
			typeof(ItemData),
			typeof(ZDO)
		}, (Type[])null);

		private static readonly int ItemsKey = StringExtensionMethods.GetStableHashCode("items");

		private static readonly int ItemKey = StringExtensionMethods.GetStableHashCode("item");

		internal static bool Ready
		{
			get
			{
				if (Backfill.Ready && (Object)(object)ObjectDB.instance != (Object)null && ObjectDB.instance.m_items != null)
				{
					return ObjectDB.instance.m_items.Count > 0;
				}
				return false;
			}
		}

		internal static string PlayerFlag(long playerId)
		{
			return "crafted-backfill-player:" + playerId;
		}

		internal static void ScanWorld(StatsStore store)
		{
			IEnumerable enumerable = Backfill.WorldObjects();
			if (enumerable == null)
			{
				Plugin.Log.LogWarning((object)"Could not read the world's objects; skipping the count of past crafts.");
				return;
			}
			int num = 0;
			int num2 = 0;
			foreach (object item in enumerable)
			{
				ZDO val = (ZDO)((item is ZDO) ? item : null);
				if (val != null)
				{
					try
					{
						num += ScanObject(store, val);
					}
					catch (Exception)
					{
						num2++;
					}
				}
			}
			Plugin.Log.LogInfo((object)($"Counted {num} crafted items already in this world." + ((num2 > 0) ? $" {num2} objects could not be read and were skipped." : "")));
		}

		private static int ScanObject(StatsStore store, ZDO zdo)
		{
			//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_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			int num = 0;
			string text = zdo.GetString(ItemsKey, "");
			if (!string.IsNullOrEmpty(text))
			{
				Inventory val = new Inventory("BuildStats scan", (Sprite)null, 64, 64);
				val.Load(new ZPackage(text));
				foreach (ItemData allItem in val.GetAllItems())
				{
					num += Count(store, allItem);
				}
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(zdo.GetPrefab());
			if ((Object)(object)prefab == (Object)null)
			{
				return num;
			}
			ItemDrop val2 = default(ItemDrop);
			if (prefab.TryGetComponent<ItemDrop>(ref val2) && LoadFromZdo != null)
			{
				ItemData val3 = val2.m_itemData.Clone();
				LoadFromZdo.Invoke(null, new object[2] { val3, zdo });
				num += Count(store, val3);
			}
			ItemStand val4 = default(ItemStand);
			if (prefab.TryGetComponent<ItemStand>(ref val4) && LoadFromZdo != null)
			{
				num += CountSaved(store, zdo, zdo.GetString(ItemKey, ""), delegate(ItemData item)
				{
					LoadFromZdo.Invoke(null, new object[2] { item, zdo });
				});
			}
			ArmorStand val5 = default(ArmorStand);
			if (prefab.TryGetComponent<ArmorStand>(ref val5) && LoadSlotFromZdo != null && val5.m_slots != null)
			{
				for (int num2 = 0; num2 < val5.m_slots.Count; num2++)
				{
					int slot = num2;
					num += CountSaved(store, zdo, zdo.GetString(slot + "_item", ""), delegate(ItemData item)
					{
						LoadSlotFromZdo.Invoke(null, new object[3] { slot, item, zdo });
					});
				}
			}
			return num;
		}

		private static int CountSaved(StatsStore store, ZDO zdo, string itemName, Action<ItemData> load)
		{
			if (string.IsNullOrEmpty(itemName))
			{
				return 0;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(itemName);
			ItemDrop val = default(ItemDrop);
			if ((Object)(object)itemPrefab == (Object)null || !itemPrefab.TryGetComponent<ItemDrop>(ref val))
			{
				return 0;
			}
			ItemData val2 = val.m_itemData.Clone();
			load(val2);
			return Count(store, val2);
		}

		internal static StatsStore ScanInventory(Player player)
		{
			StatsStore statsStore = new StatsStore();
			Inventory val = ((player != null) ? ((Humanoid)player).GetInventory() : null);
			if (val == null)
			{
				return statsStore;
			}
			foreach (ItemData allItem in val.GetAllItems())
			{
				Count(statsStore, allItem);
			}
			return statsStore;
		}

		private static int Count(StatsStore store, ItemData item)
		{
			if (item?.m_shared == null || item.m_crafterID == 0L)
			{
				return 0;
			}
			string player = ((!string.IsNullOrEmpty(item.m_crafterName)) ? item.m_crafterName : ("id:" + item.m_crafterID));
			store.Add(player, Category.Crafted, Tracking.Group(((object)Unsafe.As<ItemType, ItemType>(ref item.m_shared.m_itemType)/*cast due to .constrained prefix*/).ToString()), Math.Max(1, item.m_stack));
			if (item.m_quality > 1)
			{
				store.Add(player, Category.Crafted, "Upgrades", item.m_quality - 1);
			}
			return 1;
		}
	}
	internal static class Guard
	{
		private static readonly HashSet<string> Reported = new HashSet<string>();

		internal static void Run(string what, Action action)
		{
			try
			{
				action();
			}
			catch (Exception arg)
			{
				if (Reported.Add(what))
				{
					Plugin.Log.LogError((object)$"BuildStats: {what} failed and was skipped: {arg}");
				}
			}
		}
	}
	internal static class NameFinder
	{
		private static readonly string[][] Pairs = new string[3][]
		{
			new string[2] { "owner", "ownerName" },
			new string[2] { "creator", "creatorName" },
			new string[2] { "playerID", "playerName" }
		};

		internal static Dictionary<long, string> FromWorld()
		{
			Dictionary<long, string> dictionary = new Dictionary<long, string>();
			IEnumerable enumerable = Backfill.WorldObjects();
			if (enumerable == null)
			{
				return dictionary;
			}
			foreach (object item in enumerable)
			{
				ZDO val = (ZDO)((item is ZDO) ? item : null);
				if (val != null)
				{
					string[][] pairs = Pairs;
					foreach (string[] array in pairs)
					{
						Note(dictionary, val.GetLong(array[0], 0L), val.GetString(array[1], ""));
					}
					int num = val.GetInt("permitted", 0);
					for (int j = 0; j < num && j < 100; j++)
					{
						Note(dictionary, val.GetLong("pu_id" + j, 0L), val.GetString("pu_name" + j, ""));
					}
				}
			}
			return dictionary;
		}

		internal static Dictionary<long, string> FromOnlinePlayers()
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<long, string> dictionary = new Dictionary<long, string>();
			if ((Object)(object)ZNet.instance == (Object)null || ZDOMan.instance == null)
			{
				return dictionary;
			}
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				ZDO zDO = ZDOMan.instance.GetZDO(peer.m_characterID);
				if (zDO != null)
				{
					Note(dictionary, zDO.GetLong("playerID", 0L), zDO.GetString("playerName", ""));
				}
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				Note(dictionary, localPlayer.GetPlayerID(), localPlayer.GetPlayerName());
			}
			return dictionary;
		}

		private static void Note(Dictionary<long, string> names, long id, string name)
		{
			if (id != 0L && !string.IsNullOrEmpty(name) && !names.ContainsKey(id))
			{
				names[id] = name;
			}
		}
	}
	[BepInPlugin("dcarrigg.buildstats", "BuildStats", "1.2.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "dcarrigg.buildstats";

		public const string Name = "BuildStats";

		public const string Version = "1.2.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<KeyCode> ToggleKey;

		internal static ConfigEntry<bool> CountCrafting;

		private Harmony _harmony;

		private bool _syncFailed;

		private void Awake()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ToggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "ToggleKey", (KeyCode)288, "Key that opens and closes the stats window.");
			CountCrafting = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "CountCrafting", true, "Also count materials used at crafting stations (tools, weapons, armor, food, upgrades). Applies to what this player sends; the server keeps whatever it receives.");
			_harmony = new Harmony("dcarrigg.buildstats");
			Type[] types = typeof(Plugin).Assembly.GetTypes();
			foreach (Type type in types)
			{
				if (type.GetCustomAttributes(typeof(HarmonyPatch), inherit: false).Length != 0)
				{
					try
					{
						_harmony.CreateClassProcessor(type).Patch();
					}
					catch (Exception ex)
					{
						Log.LogError((object)("BuildStats: could not hook " + type.Name + " (game update?); that part is disabled. " + ex.Message));
					}
				}
			}
			Log.LogInfo((object)"BuildStats 1.2.0 loaded");
		}

		private void Update()
		{
			try
			{
				StatsSync.Tick();
			}
			catch (Exception arg)
			{
				if (!_syncFailed)
				{
					Log.LogError((object)$"Stats sync failed: {arg}");
				}
				_syncFailed = true;
			}
			Guard.Run("the stats window hotkey", StatsWindow.Tick);
		}

		private void OnGUI()
		{
			Guard.Run("drawing the stats window", StatsWindow.Draw);
		}

		private void OnApplicationQuit()
		{
			StatsSync.SaveNow();
		}

		private void OnDestroy()
		{
			StatsSync.SaveNow();
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal enum Category
	{
		Built,
		BuildMaterials,
		CraftMaterials,
		Crafted
	}
	internal sealed class StatsStore
	{
		internal const int CategoryCount = 4;

		private readonly Dictionary<string, Dictionary<string, int>[]> _players = new Dictionary<string, Dictionary<string, int>[]>(StringComparer.Ordinal);

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

		private const string FlagPrefix = "#! ";

		internal IEnumerable<string> Players => _players.Keys.OrderBy<string, string>((string p) => p, StringComparer.OrdinalIgnoreCase);

		internal bool IsEmpty => _players.Count == 0;

		internal bool HasFlag(string flag)
		{
			return _flags.Contains(flag);
		}

		internal void SetFlag(string flag)
		{
			_flags.Add(Clean(flag));
		}

		internal void Add(string player, Category category, string token, int amount)
		{
			if (string.IsNullOrEmpty(player) || string.IsNullOrEmpty(token) || amount <= 0)
			{
				return;
			}
			if (!_players.TryGetValue(player, out var value))
			{
				value = new Dictionary<string, int>[4];
				for (int i = 0; i < 4; i++)
				{
					value[i] = new Dictionary<string, int>(StringComparer.Ordinal);
				}
				_players[player] = value;
			}
			Dictionary<string, int> obj = value[(int)category];
			obj.TryGetValue(token, out var value2);
			obj[token] = value2 + amount;
		}

		internal void AddAll(StatsStore other)
		{
			foreach (KeyValuePair<string, Dictionary<string, int>[]> player in other._players)
			{
				for (int i = 0; i < 4; i++)
				{
					foreach (KeyValuePair<string, int> item in player.Value[i])
					{
						Add(player.Key, (Category)i, item.Key, item.Value);
					}
				}
			}
		}

		internal bool Rename(string from, string to)
		{
			if (from == to || !_players.TryGetValue(from, out var value))
			{
				return false;
			}
			_players.Remove(from);
			for (int i = 0; i < 4; i++)
			{
				foreach (KeyValuePair<string, int> item in value[i])
				{
					Add(to, (Category)i, item.Key, item.Value);
				}
			}
			return true;
		}

		internal int Get(string player, Category category, string token)
		{
			if (!_players.TryGetValue(player, out var value) || !value[(int)category].TryGetValue(token, out var value2))
			{
				return 0;
			}
			return value2;
		}

		internal IEnumerable<string> Tokens(Category category)
		{
			return _players.Values.SelectMany((Dictionary<string, int>[] c) => c[(int)category].Keys).Distinct();
		}

		internal void Clear()
		{
			_players.Clear();
		}

		internal void Write(ZPackage pkg)
		{
			pkg.Write(_players.Count);
			foreach (KeyValuePair<string, Dictionary<string, int>[]> player in _players)
			{
				pkg.Write(player.Key);
				for (int i = 0; i < 4; i++)
				{
					pkg.Write(player.Value[i].Count);
					foreach (KeyValuePair<string, int> item in player.Value[i])
					{
						pkg.Write(item.Key);
						pkg.Write(item.Value);
					}
				}
			}
		}

		internal static StatsStore Read(ZPackage pkg)
		{
			StatsStore statsStore = new StatsStore();
			int num = pkg.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string player = pkg.ReadString();
				for (int j = 0; j < 4; j++)
				{
					int num2 = pkg.ReadInt();
					for (int k = 0; k < num2; k++)
					{
						string token = pkg.ReadString();
						int amount = pkg.ReadInt();
						statsStore.Add(player, (Category)j, token, amount);
					}
				}
			}
			return statsStore;
		}

		internal void Save(string path)
		{
			Directory.CreateDirectory(Path.GetDirectoryName(path));
			string text = path + ".tmp";
			using (StreamWriter streamWriter = new StreamWriter(text))
			{
				streamWriter.WriteLine("# BuildStats: player, category (Built, BuildMaterials, CraftMaterials, Crafted), name, count");
				foreach (string flag in _flags)
				{
					streamWriter.WriteLine("#! " + flag);
				}
				foreach (KeyValuePair<string, Dictionary<string, int>[]> player in _players)
				{
					for (int i = 0; i < 4; i++)
					{
						foreach (KeyValuePair<string, int> item in player.Value[i])
						{
							streamWriter.WriteLine($"{Clean(player.Key)}\t{(Category)i}\t{Clean(item.Key)}\t{item.Value}");
						}
					}
				}
			}
			if (File.Exists(path))
			{
				File.Delete(path);
			}
			File.Move(text, path);
		}

		internal static StatsStore Load(string path)
		{
			StatsStore statsStore = new StatsStore();
			if (!File.Exists(path))
			{
				return statsStore;
			}
			string[] array = File.ReadAllLines(path);
			foreach (string text in array)
			{
				if (text.StartsWith("#! "))
				{
					statsStore._flags.Add(text.Substring("#! ".Length));
				}
				if (!text.StartsWith("#"))
				{
					string[] array2 = text.Split(new char[1] { '\t' });
					if (array2.Length == 4 && Enum.TryParse<Category>(array2[1], out var result) && int.TryParse(array2[3], out var result2))
					{
						statsStore.Add(array2[0], result, array2[2], result2);
					}
				}
			}
			return statsStore;
		}

		private static string Clean(string s)
		{
			return s.Replace('\t', ' ').Replace('\n', ' ').Replace('\r', ' ');
		}
	}
	[HarmonyPatch]
	internal static class StatsSync
	{
		private const int Protocol = 2;

		private const string RpcHello = "BuildStats_Hello";

		private const string RpcAdd = "BuildStats_Add";

		private const string RpcSync = "BuildStats_Sync";

		private const string RpcScan = "BuildStats_Scan";

		private const long Everybody = 0L;

		private const float SendInterval = 2f;

		private const float BroadcastInterval = 2f;

		private const float SaveInterval = 60f;

		private const float ServerAnswerTimeout = 15f;

		private const float HelloRetry = 5f;

		private const float OnlineCheckInterval = 10f;

		private static readonly StatsStore Pending = new StatsStore();

		private static readonly StatsStore Session = new StatsStore();

		private static StatsStore _fromServer = new StatsStore();

		private static float _helloSentAt = -1f;

		private static float _lastHello;

		private static float _lastSend;

		private static bool _serverHasMod;

		private static bool _inventorySent;

		private static readonly MethodInfo GetServerPeerIdMethod = AccessTools.Method(typeof(ZRoutedRpc), "GetServerPeerID", (Type[])null, (Type[])null);

		private static StatsStore _world;

		private static string _worldPath;

		private static bool _changed;

		private static bool _unsaved;

		private static float _lastBroadcast;

		private static float _lastSave;

		private static float _lastOnlineCheck;

		internal static StatsStore View
		{
			get
			{
				if (!_serverHasMod)
				{
					return Session;
				}
				return _fromServer;
			}
		}

		internal static bool ServerHasMod => _serverHasMod;

		internal static bool Waiting
		{
			get
			{
				if (!_serverHasMod && _helloSentAt >= 0f)
				{
					return Time.realtimeSinceStartup - _helloSentAt < 15f;
				}
				return false;
			}
		}

		private static long ServerPeerId(ZRoutedRpc rpc)
		{
			return (long)GetServerPeerIdMethod.Invoke(rpc, null);
		}

		internal static void Record(Category category, string token, int amount)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null))
			{
				string playerName = localPlayer.GetPlayerName();
				Pending.Add(playerName, category, token, amount);
				Session.Add(playerName, category, token, amount);
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		[HarmonyPostfix]
		private static void RegisterRpcs()
		{
			Guard.Run("setting up stats sync", Register);
		}

		private static void Register()
		{
			ResetSession();
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance == null)
			{
				return;
			}
			instance.Register<ZPackage>("BuildStats_Hello", (Action<long, ZPackage>)delegate(long from, ZPackage pkg)
			{
				Guard.Run("answering a player", delegate
				{
					OnHello(from, pkg);
				});
			});
			instance.Register<ZPackage>("BuildStats_Add", (Action<long, ZPackage>)delegate(long from, ZPackage pkg)
			{
				Guard.Run("adding stats from a player", delegate
				{
					OnAdd(from, pkg);
				});
			});
			instance.Register<ZPackage>("BuildStats_Sync", (Action<long, ZPackage>)delegate(long from, ZPackage pkg)
			{
				Guard.Run("reading stats from the server", delegate
				{
					OnSync(from, pkg);
				});
			});
			instance.Register<ZPackage>("BuildStats_Scan", (Action<long, ZPackage>)delegate(long from, ZPackage pkg)
			{
				Guard.Run("adding a player's past crafts", delegate
				{
					OnScan(from, pkg);
				});
			});
		}

		[HarmonyPatch(typeof(ZNet), "OnDestroy")]
		[HarmonyPrefix]
		private static void OnLeave()
		{
			Guard.Run("saving stats on leaving", delegate
			{
				SaveNow();
				ResetSession();
			});
		}

		private static void ResetSession()
		{
			Pending.Clear();
			Session.Clear();
			_fromServer = new StatsStore();
			_helloSentAt = -1f;
			_serverHasMod = false;
			_inventorySent = false;
			_world = null;
			_worldPath = null;
			_changed = (_unsaved = false);
		}

		internal static void Tick()
		{
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Expected O, but got Unknown
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Expected O, but got Unknown
			ZNet instance = ZNet.instance;
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if ((Object)(object)instance == (Object)null || rpc == null)
			{
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (instance.IsServer())
			{
				EnsureWorldLoaded();
				if (_world != null && !_world.HasFlag("crafted-backfill") && CraftBackfill.Ready)
				{
					_world.SetFlag("crafted-backfill");
					Guard.Run("counting past crafts in the world", delegate
					{
						CraftBackfill.ScanWorld(_world);
					});
					_changed = (_unsaved = true);
					SaveNow();
				}
				if (_changed && realtimeSinceStartup - _lastBroadcast >= 2f)
				{
					_changed = false;
					_lastBroadcast = realtimeSinceStartup;
					rpc.InvokeRoutedRPC(0L, "BuildStats_Sync", new object[1] { Snapshot() });
				}
				if (_unsaved && realtimeSinceStartup - _lastSave >= 60f)
				{
					SaveNow();
				}
				if (_world != null && realtimeSinceStartup - _lastOnlineCheck >= 10f)
				{
					_lastOnlineCheck = realtimeSinceStartup;
					Guard.Run("finding names of online players", delegate
					{
						NameUnknowns(NameFinder.FromOnlinePlayers());
					});
				}
			}
			Player me = Player.m_localPlayer;
			if ((Object)(object)me == (Object)null || me.GetPlayerID() == 0L || string.IsNullOrEmpty(me.GetPlayerName()))
			{
				return;
			}
			if (_helloSentAt < 0f || (!_serverHasMod && realtimeSinceStartup - _lastHello >= 5f && realtimeSinceStartup - _helloSentAt < 15f))
			{
				if (_helloSentAt < 0f)
				{
					_helloSentAt = realtimeSinceStartup;
				}
				_lastHello = realtimeSinceStartup;
				ZPackage val = new ZPackage();
				val.Write(2);
				val.Write(Player.m_localPlayer.GetPlayerID());
				val.Write(Player.m_localPlayer.GetPlayerName());
				rpc.InvokeRoutedRPC(ServerPeerId(rpc), "BuildStats_Hello", new object[1] { val });
			}
			if (_serverHasMod && !_inventorySent)
			{
				_inventorySent = true;
				Guard.Run("counting past crafts in your inventory", delegate
				{
					//IL_0000: Unknown result type (might be due to invalid IL or missing references)
					//IL_0006: Expected O, but got Unknown
					ZPackage val3 = new ZPackage();
					val3.Write(2);
					val3.Write(me.GetPlayerID());
					CraftBackfill.ScanInventory(me).Write(val3);
					rpc.InvokeRoutedRPC(ServerPeerId(rpc), "BuildStats_Scan", new object[1] { val3 });
				});
			}
			if (_serverHasMod && !Pending.IsEmpty && realtimeSinceStartup - _lastSend >= 2f)
			{
				_lastSend = realtimeSinceStartup;
				ZPackage val2 = new ZPackage();
				val2.Write(2);
				Pending.Write(val2);
				Pending.Clear();
				rpc.InvokeRoutedRPC(ServerPeerId(rpc), "BuildStats_Add", new object[1] { val2 });
			}
		}

		private static void EnsureWorldLoaded()
		{
			if (_world != null)
			{
				return;
			}
			string text = ZNet.instance.GetWorldName();
			if (string.IsNullOrEmpty(text))
			{
				return;
			}
			char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
			foreach (char oldChar in invalidFileNameChars)
			{
				text = text.Replace(oldChar, '_');
			}
			string text2 = Path.Combine(Path.Combine(Paths.ConfigPath, "BuildStats"), text + ".tsv");
			bool flag = !File.Exists(text2);
			if (flag && !Backfill.Ready)
			{
				return;
			}
			_worldPath = text2;
			try
			{
				_world = StatsStore.Load(_worldPath);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not read " + _worldPath + "; starting with empty stats. " + ex.Message));
				_world = new StatsStore();
			}
			_lastSave = Time.realtimeSinceStartup;
			if (flag)
			{
				Guard.Run("counting existing builds", delegate
				{
					Backfill.Run(_world);
				});
				_changed = (_unsaved = true);
			}
			Guard.Run("finding names in the world", delegate
			{
				NameUnknowns(NameFinder.FromWorld());
			});
			SaveNow();
		}

		private static void NameUnknowns(Dictionary<long, string> names)
		{
			if (_world == null || names.Count == 0)
			{
				return;
			}
			int num = 0;
			foreach (string item in _world.Players.ToList())
			{
				if (item.StartsWith("id:") && long.TryParse(item.Substring("id:".Length), out var result) && names.TryGetValue(result, out var value) && _world.Rename(item, value))
				{
					num++;
				}
			}
			if (num != 0)
			{
				_changed = (_unsaved = true);
				Plugin.Log.LogInfo((object)$"Named {num} builder(s) from the world.");
			}
		}

		private static ZPackage Snapshot()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(2);
			_world.Write(val);
			return val;
		}

		private static void OnHello(long sender, ZPackage pkg)
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			EnsureWorldLoaded();
			if (_world != null && pkg.ReadInt() == 2)
			{
				long num = pkg.ReadLong();
				string text = pkg.ReadString();
				if (!string.IsNullOrEmpty(text) && _world.Rename("id:" + num, text))
				{
					_changed = (_unsaved = true);
				}
				ZRoutedRpc.instance.InvokeRoutedRPC(sender, "BuildStats_Sync", new object[1] { Snapshot() });
			}
		}

		private static void OnAdd(long sender, ZPackage pkg)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer())
			{
				EnsureWorldLoaded();
				if (_world != null && pkg.ReadInt() == 2)
				{
					_world.AddAll(StatsStore.Read(pkg));
					_changed = (_unsaved = true);
				}
			}
		}

		private static void OnScan(long sender, ZPackage pkg)
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			EnsureWorldLoaded();
			if (_world != null && pkg.ReadInt() == 2)
			{
				string flag = CraftBackfill.PlayerFlag(pkg.ReadLong());
				if (!_world.HasFlag(flag))
				{
					_world.SetFlag(flag);
					_world.AddAll(StatsStore.Read(pkg));
					_changed = (_unsaved = true);
				}
			}
		}

		internal static void SaveNow()
		{
			if (_world != null && _unsaved)
			{
				try
				{
					_world.Save(_worldPath);
					_unsaved = false;
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)("Could not save " + _worldPath + ": " + ex.Message));
				}
				_lastSave = Time.realtimeSinceStartup;
			}
		}

		private static void OnSync(long sender, ZPackage pkg)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsDedicated() && pkg.ReadInt() == 2)
			{
				_fromServer = StatsStore.Read(pkg);
				_serverHasMod = true;
			}
		}
	}
	[HarmonyPatch]
	internal static class StatsWindow
	{
		private enum Tab
		{
			Built,
			Materials,
			Crafted
		}

		private enum MaterialFilter
		{
			All,
			Building,
			Crafting
		}

		private sealed class Row
		{
			public string Name;

			public int[] PerPlayer;

			public int Total;
		}

		private static class Styles
		{
			private static readonly Color Gold = new Color(1f, 0.74f, 0.36f);

			private static readonly Color Text = new Color(0.93f, 0.9f, 0.84f);

			private static readonly Color Hot = new Color(1f, 0.62f, 0.2f);

			private static readonly Color Dim = new Color(0.66f, 0.62f, 0.55f);

			internal static GUIStyle Window;

			internal static GUIStyle Title;

			internal static GUIStyle Close;

			internal static GUIStyle Tab;

			internal static GUIStyle TabOn;

			internal static GUIStyle Filter;

			internal static GUIStyle FilterOn;

			internal static GUIStyle Header;

			internal static GUIStyle HeaderNum;

			internal static GUIStyle HeaderOn;

			internal static GUIStyle HeaderNumOn;

			internal static GUIStyle Search;

			internal static GUIStyle SearchHint;

			internal static GUIStyle Cell;

			internal static GUIStyle CellAlt;

			internal static GUIStyle Num;

			internal static GUIStyle NumAlt;

			internal static GUIStyle Top;

			internal static GUIStyle TopAlt;

			internal static GUIStyle TotalCell;

			internal static GUIStyle TotalNum;

			internal static GUIStyle TotalTop;

			internal static GUIStyle Footer;

			internal static GUIStyle Empty;

			private static bool _made;

			internal static void Ensure()
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_0097: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
				//IL_0114: Unknown result type (might be due to invalid IL or missing references)
				//IL_0120: Unknown result type (might be due to invalid IL or missing references)
				//IL_0125: Unknown result type (might be due to invalid IL or missing references)
				//IL_0131: Unknown result type (might be due to invalid IL or missing references)
				//IL_013a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0144: Expected O, but got Unknown
				//IL_0144: Unknown result type (might be due to invalid IL or missing references)
				//IL_0149: Unknown result type (might be due to invalid IL or missing references)
				//IL_0153: Expected O, but got Unknown
				//IL_0158: Expected O, but got Unknown
				//IL_015b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0171: Unknown result type (might be due to invalid IL or missing references)
				//IL_018e: Unknown result type (might be due to invalid IL or missing references)
				//IL_019b: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b3: Expected O, but got Unknown
				//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
				//IL_01de: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e8: Expected O, but got Unknown
				//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0206: Expected O, but got Unknown
				//IL_0215: Unknown result type (might be due to invalid IL or missing references)
				//IL_0222: Unknown result type (might be due to invalid IL or missing references)
				//IL_022e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0238: Expected O, but got Unknown
				//IL_0240: Unknown result type (might be due to invalid IL or missing references)
				//IL_024c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0256: Expected O, but got Unknown
				//IL_025e: Unknown result type (might be due to invalid IL or missing references)
				//IL_026a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0274: Expected O, but got Unknown
				//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
				//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
				//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
				//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
				//IL_02f8: Expected O, but got Unknown
				//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
				//IL_0302: Unknown result type (might be due to invalid IL or missing references)
				//IL_030f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0315: Unknown result type (might be due to invalid IL or missing references)
				//IL_031f: Unknown result type (might be due to invalid IL or missing references)
				//IL_032c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0332: Unknown result type (might be due to invalid IL or missing references)
				//IL_0341: Expected O, but got Unknown
				//IL_034b: Unknown result type (might be due to invalid IL or missing references)
				//IL_035f: Unknown result type (might be due to invalid IL or missing references)
				//IL_037d: Unknown result type (might be due to invalid IL or missing references)
				//IL_038c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0399: Unknown result type (might be due to invalid IL or missing references)
				//IL_03a3: Expected O, but got Unknown
				//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_03db: Unknown result type (might be due to invalid IL or missing references)
				//IL_03e7: Unknown result type (might be due to invalid IL or missing references)
				//IL_03f1: Expected O, but got Unknown
				//IL_03f9: Unknown result type (might be due to invalid IL or missing references)
				//IL_0405: Unknown result type (might be due to invalid IL or missing references)
				//IL_040f: Expected O, but got Unknown
				//IL_0417: Unknown result type (might be due to invalid IL or missing references)
				//IL_0423: Unknown result type (might be due to invalid IL or missing references)
				//IL_042d: Expected O, but got Unknown
				//IL_0435: Unknown result type (might be due to invalid IL or missing references)
				//IL_0441: Unknown result type (might be due to invalid IL or missing references)
				//IL_044b: Expected O, but got Unknown
				//IL_0453: Unknown result type (might be due to invalid IL or missing references)
				//IL_045f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0469: Expected O, but got Unknown
				//IL_0471: Unknown result type (might be due to invalid IL or missing references)
				//IL_047e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0488: Expected O, but got Unknown
				//IL_0490: Unknown result type (might be due to invalid IL or missing references)
				//IL_049d: Unknown result type (might be due to invalid IL or missing references)
				//IL_04a7: Expected O, but got Unknown
				//IL_04c0: Unknown result type (might be due to invalid IL or missing references)
				//IL_04e0: Unknown result type (might be due to invalid IL or missing references)
				//IL_04ef: Unknown result type (might be due to invalid IL or missing references)
				//IL_04fc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0506: Expected O, but got Unknown
				//IL_0518: Unknown result type (might be due to invalid IL or missing references)
				//IL_0525: Unknown result type (might be due to invalid IL or missing references)
				//IL_052f: Expected O, but got Unknown
				//IL_0537: Unknown result type (might be due to invalid IL or missing references)
				//IL_054c: Unknown result type (might be due to invalid IL or missing references)
				if (!_made)
				{
					_made = true;
					Font? font = ((IEnumerable<Font>)Resources.FindObjectsOfTypeAll<Font>()).FirstOrDefault((Func<Font, bool>)((Font f) => ((Object)f).name.StartsWith("AveriaSerifLibre-Bold"))) ?? ((IEnumerable<Font>)Resources.FindObjectsOfTypeAll<Font>()).FirstOrDefault((Func<Font, bool>)((Font f) => ((Object)f).name.StartsWith("AveriaSerifLibre")));
					Texture2D background = Solid(new Color(0.09f, 0.075f, 0.06f, 0.95f));
					Texture2D bg = Solid(new Color(1f, 1f, 1f, 0.035f));
					Texture2D bg2 = Solid(new Color(0f, 0f, 0f, 0.35f));
					Texture2D bg3 = Solid(new Color(1f, 1f, 1f, 0.06f));
					Texture2D bg4 = Solid(new Color(1f, 0.74f, 0.36f, 0.22f));
					Texture2D bg5 = Solid(new Color(1f, 0.74f, 0.36f, 0.12f));
					GUIStyle val = new GUIStyle();
					val.normal.background = background;
					val.padding = new RectOffset(16, 16, 12, 12);
					val.border = new RectOffset(2, 2, 2, 2);
					Window = val;
					Title = Make(font, 22, Gold, (FontStyle)1, (TextAnchor)3);
					Close = Make(font, 18, Dim, (FontStyle)0, (TextAnchor)4);
					Close.hover.textColor = Gold;
					Tab = Make(font, 15, Dim, (FontStyle)1, (TextAnchor)4, bg3, new RectOffset(14, 14, 6, 6));
					Tab.hover.textColor = Text;
					TabOn = Make(font, 15, Gold, (FontStyle)1, (TextAnchor)4, bg4, new RectOffset(14, 14, 6, 6));
					Filter = Make(font, 13, Dim, (FontStyle)0, (TextAnchor)4, null, new RectOffset(8, 8, 6, 6));
					Filter.hover.textColor = Text;
					FilterOn = Make(font, 13, Gold, (FontStyle)1, (TextAnchor)4, null, new RectOffset(8, 8, 6, 6));
					Header = Make(font, 14, Gold, (FontStyle)1, (TextAnchor)3, bg2, new RectOffset(8, 8, 6, 6));
					HeaderNum = Make(font, 14, Gold, (FontStyle)1, (TextAnchor)5, bg2, new RectOffset(8, 8, 6, 6));
					HeaderNum.wordWrap = true;
					Header.wordWrap = true;
					Texture2D background2 = Solid(new Color(1f, 0.74f, 0.36f, 0.2f));
					GUIStyle val2 = new GUIStyle(Header);
					val2.normal.background = background2;
					val2.normal.textColor = Gold;
					val2.hover.background = background2;
					val2.hover.textColor = Gold;
					HeaderOn = val2;
					GUIStyle val3 = new GUIStyle(HeaderNum);
					val3.normal.background = background2;
					val3.normal.textColor = Gold;
					val3.hover.background = background2;
					val3.hover.textColor = Gold;
					HeaderNumOn = val3;
					Header.hover.textColor = Text;
					HeaderNum.hover.textColor = Text;
					Texture2D val4 = Solid(new Color(0f, 0f, 0f, 0.45f));
					Search = Make(font, 14, Text, (FontStyle)0, (TextAnchor)3, val4, new RectOffset(8, 8, 5, 5));
					Search.focused.background = val4;
					Search.focused.textColor = Text;
					Search.clipping = (TextClipping)1;
					SearchHint = Make(font, 14, Dim, (FontStyle)2, (TextAnchor)3, null, new RectOffset(8, 8, 5, 5));
					Cell = Make(font, 14, Text, (FontStyle)0, (TextAnchor)3, null, new RectOffset(8, 8, 4, 4));
					CellAlt = Make(font, 14, Text, (FontStyle)0, (TextAnchor)3, bg, new RectOffset(8, 8, 4, 4));
					Num = Make(font, 14, Text, (FontStyle)0, (TextAnchor)5, null, new RectOffset(8, 8, 4, 4));
					NumAlt = Make(font, 14, Text, (FontStyle)0, (TextAnchor)5, bg, new RectOffset(8, 8, 4, 4));
					TotalCell = Make(font, 14, Gold, (FontStyle)1, (TextAnchor)3, bg5, new RectOffset(8, 8, 5, 5));
					TotalNum = Make(font, 14, Gold, (FontStyle)1, (TextAnchor)5, bg5, new RectOffset(8, 8, 5, 5));
					Texture2D bg6 = Solid(new Color(1f, 0.55f, 0.1f, 0.28f));
					Texture2D bg7 = Solid(new Color(1f, 0.55f, 0.1f, 0.4f));
					Top = Make(font, 14, Hot, (FontStyle)1, (TextAnchor)5, bg6, new RectOffset(8, 8, 4, 4));
					TopAlt = Top;
					TotalTop = Make(font, 14, Hot, (FontStyle)1, (TextAnchor)5, bg7, new RectOffset(8, 8, 5, 5));
					Footer = Make(font, 12, Dim, (FontStyle)0, (TextAnchor)3);
					Empty = Make(font, 15, Dim, (FontStyle)2, (TextAnchor)4);
				}
			}

			private static GUIStyle Make(Font font, int size, Color color, FontStyle style, TextAnchor anchor = (TextAnchor)3, Texture2D bg = null, RectOffset padding = null)
			{
				//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_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_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//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_0046: Expected O, but got Unknown
				//IL_0046: 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_0053: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				//IL_0066: Unknown result type (might be due to invalid IL or missing references)
				//IL_006c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0085: Unknown result type (might be due to invalid IL or missing references)
				//IL_008b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0099: Expected O, but got Unknown
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				GUIStyle val = new GUIStyle
				{
					font = font,
					fontSize = size,
					fontStyle = style,
					alignment = anchor,
					padding = (RectOffset)(((object)padding) ?? ((object)new RectOffset(2, 2, 2, 2))),
					margin = new RectOffset(0, 2, 0, 0),
					clipping = (TextClipping)1
				};
				val.normal.textColor = color;
				val.normal.background = bg;
				val.hover.textColor = color;
				val.hover.background = bg;
				val.active.textColor = color;
				val.active.background = bg;
				return val;
			}

			private static Texture2D Solid(Color c)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Expected O, but got Unknown
				Texture2D val = new Texture2D(1, 1)
				{
					hideFlags = (HideFlags)61
				};
				val.SetPixel(0, 0, c);
				val.Apply();
				return val;
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static WindowFunction <0>__DrawWindow;
		}

		private const int WindowId = 4346708;

		private const float ItemWidth = 230f;

		private const float NumberWidth = 96f;

		private static bool _open;

		private static Tab _tab;

		private static MaterialFilter _filter;

		private static Tab? _nextTab;

		private const string SortTotal = "#total";

		private const string SortName = "#name";

		private const string SearchControl = "BuildStatsSearch";

		private static string _sortBy = "#total";

		private static bool _sortDescending = true;

		private static string _nextSort;

		private static string _search = "";

		private static bool _searchFocused;

		private static MaterialFilter? _nextFilter;

		private static Vector2 _scroll;

		private static Rect _rect;

		private static bool _tooWide;

		private static float _scale = 1f;

		private static string[] _players = Array.Empty<string>();

		private static string[] _labels = Array.Empty<string>();

		private static List<Row> _rows = new List<Row>();

		private static Row _totals;

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

		internal static bool IsOpen => _open;

		internal static bool SearchFocused => _searchFocused;

		internal static void Tick()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (_open && (Object)(object)Player.m_localPlayer == (Object)null)
			{
				_open = false;
			}
			if (!_open)
			{
				_searchFocused = false;
			}
			if (!_searchFocused && Input.GetKeyDown(Plugin.ToggleKey.Value))
			{
				if (_open)
				{
					_open = false;
				}
				else if (CanOpen())
				{
					Open();
				}
			}
		}

		private static bool CanOpen()
		{
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				return false;
			}
			if (Console.IsVisible() || TextInput.IsVisible() || Menu.IsVisible())
			{
				return false;
			}
			if ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus())
			{
				return false;
			}
			return true;
		}

		private static void Open()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			_open = true;
			_scroll = Vector2.zero;
			if (((Rect)(ref _rect)).width <= 0f)
			{
				_rect = new Rect(0f, 0f, 760f, 520f);
			}
		}

		[HarmonyPatch(typeof(Player), "TakeInput")]
		[HarmonyPostfix]
		private static void BlockPlayerInput(ref bool __result)
		{
			if (_open)
			{
				__result = false;
			}
		}

		[HarmonyPatch(typeof(PlayerController), "TakeInput")]
		[HarmonyPostfix]
		private static void BlockControllerInput(ref bool __result)
		{
			if (_open)
			{
				__result = false;
			}
		}

		[HarmonyPatch(typeof(GameCamera), "UpdateMouseCapture")]
		[HarmonyPrefix]
		private static bool FreeCursor()
		{
			if (!_open)
			{
				return true;
			}
			Cursor.lockState = (CursorLockMode)0;
			Cursor.visible = true;
			return false;
		}

		[HarmonyPatch(typeof(Menu), "Update")]
		[HarmonyPrefix]
		private static bool EscCloses()
		{
			if (!_open)
			{
				return true;
			}
			if (Input.GetKeyDown((KeyCode)27))
			{
				_open = false;
			}
			return false;
		}

		internal static void Draw()
		{
			//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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Invalid comparison between Unknown and I4
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Expected O, but got Unknown
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			if (!_open)
			{
				return;
			}
			Styles.Ensure();
			_scale = Mathf.Max(1f, (float)Screen.height / 1080f);
			GUI.matrix = Matrix4x4.Scale(new Vector3(_scale, _scale, 1f));
			float num = (float)Screen.width / _scale;
			float num2 = (float)Screen.height / _scale;
			if ((int)Event.current.type == 8)
			{
				Tab? nextTab = _nextTab;
				if (nextTab.HasValue)
				{
					Tab valueOrDefault = nextTab.GetValueOrDefault();
					if (valueOrDefault != _tab)
					{
						_tab = valueOrDefault;
						_scroll = Vector2.zero;
					}
				}
				MaterialFilter? nextFilter = _nextFilter;
				if (nextFilter.HasValue)
				{
					MaterialFilter valueOrDefault2 = nextFilter.GetValueOrDefault();
					_filter = valueOrDefault2;
				}
				if (_nextSort != null)
				{
					if (_nextSort == _sortBy)
					{
						_sortDescending = !_sortDescending;
					}
					else
					{
						_sortBy = _nextSort;
						_sortDescending = _sortBy != "#name";
					}
					_nextSort = null;
				}
				_nextTab = null;
				_nextFilter = null;
				BuildRows();
				FitWidth(num);
			}
			if (((Rect)(ref _rect)).x <= 0f && ((Rect)(ref _rect)).y <= 0f)
			{
				((Rect)(ref _rect)).position = new Vector2((num - ((Rect)(ref _rect)).width) / 2f, (num2 - ((Rect)(ref _rect)).height) / 2f);
			}
			Rect rect = _rect;
			object obj = <>O.<0>__DrawWindow;
			if (obj == null)
			{
				WindowFunction val = DrawWindow;
				<>O.<0>__DrawWindow = val;
				obj = (object)val;
			}
			_rect = GUI.Window(4346708, rect, (WindowFunction)obj, GUIContent.none, Styles.Window);
			((Rect)(ref _rect)).x = Mathf.Clamp(((Rect)(ref _rect)).x, 0f, num - ((Rect)(ref _rect)).width);
			((Rect)(ref _rect)).y = Mathf.Clamp(((Rect)(ref _rect)).y, 0f, num2 - ((Rect)(ref _rect)).height);
		}

		private static void DrawWindow(int id)
		{
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Invalid comparison between Unknown and I4
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label("Build stats", Styles.Title, Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			if (GUILayout.Button("x", Styles.Close, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(28f) }))
			{
				_open = false;
			}
			GUILayout.EndHorizontal();
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			TabButton("Things built", Tab.Built);
			TabButton("Resources used", Tab.Materials);
			TabButton("Crafted", Tab.Crafted);
			GUILayout.FlexibleSpace();
			if (_tab == Tab.Materials)
			{
				FilterButton("All", MaterialFilter.All);
				FilterButton("Building", MaterialFilter.Building);
				FilterButton("Crafting", MaterialFilter.Crafting);
			}
			GUILayout.Space(10f);
			GUI.SetNextControlName("BuildStatsSearch");
			_search = GUILayout.TextField(_search ?? "", 40, Styles.Search, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(190f) });
			if (string.IsNullOrEmpty(_search) && GUI.GetNameOfFocusedControl() != "BuildStatsSearch")
			{
				GUI.Label(GUILayoutUtility.GetLastRect(), "Search...", Styles.SearchHint);
			}
			if ((int)Event.current.type == 7)
			{
				_searchFocused = GUI.GetNameOfFocusedControl() == "BuildStatsSearch";
			}
			GUILayout.EndHorizontal();
			GUILayout.Space(6f);
			if (_rows.Count == 0)
			{
				GUILayout.FlexibleSpace();
				GUILayout.Label((!string.IsNullOrEmpty(_search)) ? ("Nothing matches \"" + _search + "\".") : ((_tab == Tab.Built) ? "Nothing built yet." : ((_tab == Tab.Crafted) ? "Nothing crafted yet." : "No resources used yet.")), Styles.Empty, Array.Empty<GUILayoutOption>());
				GUILayout.FlexibleSpace();
			}
			else
			{
				string name = ((_tab == Tab.Built) ? "Piece" : ((_tab == Tab.Crafted) ? "Kind" : "Material"));
				if (_tooWide)
				{
					_scroll = GUILayout.BeginScrollView(_scroll, true, false, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, Array.Empty<GUILayoutOption>());
				}
				DrawRow(name, _labels, null, "Total", Styles.Header, Styles.HeaderNum);
				if (!_tooWide)
				{
					_scroll = GUILayout.BeginScrollView(_scroll, false, false, GUIStyle.none, GUI.skin.verticalScrollbar, Array.Empty<GUILayoutOption>());
				}
				for (int i = 0; i < _rows.Count; i++)
				{
					Row row = _rows[i];
					DrawRow(row.Name, null, row.PerPlayer, row.Total.ToString("N0"), (i % 2 == 0) ? Styles.Cell : Styles.CellAlt, (i % 2 == 0) ? Styles.Num : Styles.NumAlt, (i % 2 == 0) ? Styles.Top : Styles.TopAlt);
				}
				if (!_tooWide)
				{
					GUILayout.EndScrollView();
				}
				DrawRow("All", null, _totals.PerPlayer, _totals.Total.ToString("N0"), Styles.TotalCell, Styles.TotalNum, Styles.TotalTop);
				if (_tooWide)
				{
					GUILayout.EndScrollView();
				}
			}
			GUILayout.Space(4f);
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label(StatusText(), Styles.Footer, Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			GUILayout.Label($"{Plugin.ToggleKey.Value} or Esc to close", Styles.Footer, Array.Empty<GUILayoutOption>());
			GUILayout.EndHorizontal();
			GUI.DragWindow(new Rect(0f, 0f, 10000f, 40f));
		}

		private static void FitWidth(float screenW)
		{
			int num = _players.Length + ((_players.Length > 1) ? 1 : 0);
			float num2 = 264f + (float)num * 98f + 24f;
			float num3 = Mathf.Max(560f, screenW - 40f);
			_tooWide = num2 > num3;
			((Rect)(ref _rect)).width = Mathf.Clamp(num2, 560f, num3);
		}

		private static void DrawRow(string name, string[] heads, int[] values, string total, GUIStyle cell, GUIStyle num, GUIStyle top = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			int num2 = _players.Length;
			GUILayoutOption val = null;
			if (heads != null)
			{
				float num3 = cell.CalcHeight(new GUIContent(name), 230f);
				for (int i = 0; i < num2; i++)
				{
					num3 = Mathf.Max(num3, num.CalcHeight(new GUIContent(heads[i]), 96f));
				}
				val = GUILayout.Height(num3);
			}
			int num4 = 0;
			if (values != null && top != null && num2 > 1)
			{
				for (int j = 0; j < num2; j++)
				{
					num4 = Mathf.Max(num4, values[j]);
				}
			}
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (heads != null)
			{
				HeaderButton(name, "#name", cell, Options(230f, val));
				for (int k = 0; k < num2; k++)
				{
					HeaderButton(heads[k], _players[k], num, Options(96f, val));
				}
				if (num2 > 1)
				{
					HeaderButton(total, "#total", num, Options(96f, val));
				}
			}
			else
			{
				GUILayout.Label(name, cell, Options(230f, val));
				for (int l = 0; l < num2; l++)
				{
					string obj = ((values[l] == 0) ? "-" : values[l].ToString("N0"));
					GUIStyle val2 = ((num4 > 0 && values[l] == num4) ? top : num);
					GUILayout.Label(obj, val2, Options(96f, val));
				}
				if (num2 > 1)
				{
					GUILayout.Label(total, num, Options(96f, val));
				}
			}
			GUILayout.Label(GUIContent.none, cell, (GUILayoutOption[])(object)((val != null) ? new GUILayoutOption[2]
			{
				GUILayout.ExpandWidth(true),
				val
			} : new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }));
			GUILayout.EndHorizontal();
		}

		private static void HeaderButton(string text, string sortKey, GUIStyle style, GUILayoutOption[] options)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Invalid comparison between Unknown and I4
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			bool flag = _sortBy == sortKey;
			if (flag)
			{
				text = (((int)style.alignment == 3 || (int)style.alignment == 0) ? (text + (_sortDescending ? " ▼" : " ▲")) : ((_sortDescending ? "▼ " : "▲ ") + text));
			}
			if (GUILayout.Button(text, (!flag) ? style : ((style == Styles.Header) ? Styles.HeaderOn : Styles.HeaderNumOn), options))
			{
				_nextSort = sortKey;
			}
		}

		private static GUILayoutOption[] Options(float width, GUILayoutOption height)
		{
			if (height == null)
			{
				return (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(width) };
			}
			return (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(width),
				height
			};
		}

		private static void TabButton(string text, Tab tab)
		{
			if (GUILayout.Button(text, (_tab == tab) ? Styles.TabOn : Styles.Tab, Array.Empty<GUILayoutOption>()))
			{
				_nextTab = tab;
			}
		}

		private static void FilterButton(string text, MaterialFilter f)
		{
			if (GUILayout.Button(text, (_filter == f) ? Styles.FilterOn : Styles.Filter, Array.Empty<GUILayoutOption>()))
			{
				_nextFilter = f;
			}
		}

		private static string StatusText()
		{
			if (StatsSync.ServerHasMod)
			{
				return "All players on this world. Kept by the server.";
			}
			if (StatsSync.Waiting)
			{
				return "Getting stats from the server...";
			}
			return "The server doesn't run BuildStats: showing only your builds this session.";
		}

		private static void BuildRows()
		{
			StatsStore view = StatsSync.View;
			List<string> first = view.Players.Where((string p) => !p.StartsWith("id:")).ToList();
			List<string> list = view.Players.Where((string p) => p.StartsWith("id:")).ToList();
			_players = first.Concat(list).ToArray();
			_labels = first.Concat(list.Select((string _, int i) => $"Unknown {i + 1}")).ToArray();
			Category[] array = ((_tab == Tab.Built) ? new Category[1] : ((_tab != Tab.Crafted) ? ((_filter != MaterialFilter.Building) ? ((_filter != MaterialFilter.Crafting) ? new Category[2]
			{
				Category.BuildMaterials,
				Category.CraftMaterials
			} : new Category[1] { Category.CraftMaterials }) : new Category[1] { Category.BuildMaterials }) : new Category[1] { Category.Crafted }));
			List<Row> list2 = new List<Row>();
			_totals = new Row
			{
				Name = "All",
				PerPlayer = new int[_players.Length]
			};
			foreach (string item in array.SelectMany(view.Tokens).Distinct())
			{
				Row row = new Row
				{
					Name = Localize(item),
					PerPlayer = new int[_players.Length]
				};
				for (int num = 0; num < _players.Length; num++)
				{
					Category[] array2 = array;
					foreach (Category category in array2)
					{
						row.PerPlayer[num] += view.Get(_players[num], category, item);
					}
					row.Total += row.PerPlayer[num];
				}
				if (row.Total > 0)
				{
					list2.Add(row);
				}
			}
			if (!string.IsNullOrEmpty(_search))
			{
				list2 = list2.Where((Row r) => r.Name.IndexOf(_search, StringComparison.CurrentCultureIgnoreCase) >= 0).ToList();
			}
			foreach (Row item2 in list2)
			{
				for (int num3 = 0; num3 < _players.Length; num3++)
				{
					_totals.PerPlayer[num3] += item2.PerPlayer[num3];
				}
				_totals.Total += item2.Total;
			}
			int col = Array.IndexOf(_players, _sortBy);
			if (_sortBy != "#total" && _sortBy != "#name" && col < 0)
			{
				_sortBy = "#total";
			}
			int sign = ((!_sortDescending) ? 1 : (-1));
			list2.Sort(delegate(Row a, Row b)
			{
				int num4 = ((!(_sortBy == "#name")) ? (((col >= 0) ? a.PerPlayer[col].CompareTo(b.PerPlayer[col]) : a.Total.CompareTo(b.Total)) * sign) : 0);
				if (num4 == 0 && _sortBy == "#name")
				{
					num4 = string.Compare(a.Name, b.Name, StringComparison.CurrentCultureIgnoreCase) * sign;
				}
				if (num4 == 0 && col >= 0)
				{
					num4 = b.Total.CompareTo(a.Total);
				}
				return (num4 == 0) ? string.Compare(a.Name, b.Name, StringComparison.CurrentCultureIgnoreCase) : num4;
			});
			_rows = list2;
		}

		private static string Localize(string token)
		{
			if (Localized.TryGetValue(token, out var value))
			{
				return value;
			}
			value = ((Localization.instance != null) ? Localization.instance.Localize(token) : token);
			if (string.IsNullOrEmpty(value))
			{
				value = token;
			}
			Localized[token] = value;
			return value;
		}
	}
	[HarmonyPatch]
	internal static class ZoomLock
	{
		private static readonly FieldRef<GameCamera, float> CameraDistance = AccessTools.FieldRefAccess<GameCamera, float>("m_distance");

		[HarmonyPatch(typeof(GameCamera), "UpdateCamera")]
		[HarmonyPrefix]
		private static void RememberZoom(GameCamera __instance, out float __state)
		{
			__state = CameraDistance.Invoke(__instance);
		}

		[HarmonyPatch(typeof(GameCamera), "UpdateCamera")]
		[HarmonyPostfix]
		private static void KeepZoom(GameCamera __instance, float __state)
		{
			if (StatsWindow.IsOpen)
			{
				CameraDistance.Invoke(__instance) = __state;
			}
		}
	}
	[HarmonyPatch]
	internal static class TypingLock
	{
		[HarmonyPatch(typeof(InventoryGui), "Update")]
		[HarmonyPrefix]
		private static bool NoInventoryKeysWhileSearching()
		{
			if (StatsWindow.IsOpen)
			{
				return !StatsWindow.SearchFocused;
			}
			return true;
		}

		[HarmonyPatch(typeof(Minimap), "Update")]
		[HarmonyPrefix]
		private static bool NoMapKeysWhileSearching()
		{
			if (StatsWindow.IsOpen)
			{
				return !StatsWindow.SearchFocused;
			}
			return true;
		}

		[HarmonyPatch(typeof(Chat), "Update")]
		[HarmonyPrefix]
		private static bool NoChatKeysWhileSearching()
		{
			if (StatsWindow.IsOpen)
			{
				return !StatsWindow.SearchFocused;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class Tracking
	{
		private static readonly FieldRef<InventoryGui, Recipe> CraftRecipe = AccessTools.FieldRefAccess<InventoryGui, Recipe>("m_craftRecipe");

		private static readonly FieldRef<InventoryGui, ItemData> CraftUpgradeItem = AccessTools.FieldRefAccess<InventoryGui, ItemData>("m_craftUpgradeItem");

		private static Recipe _crafting;

		private static bool _upgrading;

		[HarmonyPatch(typeof(Player), "PlacePiece")]
		[HarmonyPostfix]
		private static void OnPlacePiece(Player __instance, object[] __args)
		{
			Guard.Run("counting a placed piece", delegate
			{
				CountPiece(__instance, __args);
			});
		}

		private static void CountPiece(Player __instance, object[] __args)
		{
			if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && __args.Length != 0)
			{
				object obj = __args[0];
				Piece val = (Piece)((obj is Piece) ? obj : null);
				if (val != null && val.m_resources != null && val.m_resources.Length != 0)
				{
					StatsSync.Record(Category.Built, val.m_name, 1);
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
		[HarmonyPrefix]
		private static void BeforeCrafting(InventoryGui __instance)
		{
			Guard.Run("noting what is being crafted", delegate
			{
				_crafting = CraftRecipe.Invoke(__instance);
				_upgrading = CraftUpgradeItem.Invoke(__instance) != null;
			});
		}

		[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
		[HarmonyFinalizer]
		private static void AfterCrafting()
		{
			_crafting = null;
		}

		[HarmonyPatch(typeof(Player), "ConsumeResources")]
		[HarmonyPrefix]
		private static void OnConsumeResources(Player __instance, object[] __args)
		{
			Guard.Run("counting used resources", delegate
			{
				CountResources(__instance, __args);
			});
		}

		private static void CountResources(Player __instance, object[] __args)
		{
			if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || __instance.NoCostCheat() || __args.Length < 2 || !(__args[0] is Requirement[] array) || !(__args[1] is int num))
			{
				return;
			}
			int num2 = ((__args.Length <= 3 || !(__args[3] is int num3)) ? 1 : num3);
			bool flag = InventoryGui.IsVisible();
			if (flag && !Plugin.CountCrafting.Value)
			{
				return;
			}
			Category category = ((!flag) ? Category.BuildMaterials : Category.CraftMaterials);
			Requirement[] array2 = array;
			foreach (Requirement val in array2)
			{
				if (!((Object)(object)val?.m_resItem == (Object)null))
				{
					int amount = val.GetAmount(num) * ((num2 < 1) ? 1 : num2);
					StatsSync.Record(category, val.m_resItem.m_itemData.m_shared.m_name, amount);
				}
			}
			if ((Object)(object)_crafting?.m_item != (Object)null)
			{
				string token = (_upgrading ? "Upgrades" : Group(((object)Unsafe.As<ItemType, ItemType>(ref _crafting.m_item.m_itemData.m_shared.m_itemType)/*cast due to .constrained prefix*/).ToString()));
				int amount2 = (_upgrading ? 1 : (Math.Max(1, _crafting.m_amount) * Math.Max(1, num2)));
				StatsSync.Record(Category.Crafted, token, amount2);
			}
		}

		internal static string Group(string itemType)
		{
			switch (itemType)
			{
			case "OneHandedWeapon":
			case "TwoHandedWeapon":
			case "TwoHandedWeaponLeft":
			case "Bow":
			case "Attach_Atgeir":
				return "Weapons";
			case "Shield":
				return "Shields";
			case "Helmet":
			case "Chest":
			case "Hands":
			case "Legs":
			case "Shoulder":
				return "Armor";
			case "Ammo":
			case "AmmoNonEquipable":
				return "Ammo";
			case "Torch":
			case "Tool":
				return "Tools";
			case "Consumable":
				return "Food & potions";
			case "Trinket":
			case "Utility":
				return "Utility & trinkets";
			default:
				return "Other";
			}
		}
	}
}